file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// Sources flattened with hardhat v2.5.0 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/[email protected] // 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); } // File contracts/libs/TransferHelper.sol // GPL-3.0-or-later pragma solidity ^0.8.6; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File contracts/libs/ABDKMath64x64.sol // BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.8.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) { unchecked { 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) { unchecked { 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) { unchecked { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (int256 (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) { unchecked { require (x >= 0); return uint64 (uint128 (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) { unchecked { 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) { unchecked { 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) { unchecked { 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) { unchecked { 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) { unchecked { 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) { unchecked { 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) { unchecked { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (int256 (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) { unchecked { 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) { unchecked { 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) { unchecked { 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) { unchecked { 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) { unchecked { 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) { unchecked { 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) { unchecked { 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) { unchecked { 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) { unchecked { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * 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) { unchecked { require (x >= 0); return int128 (sqrtu (uint256 (int256 (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) { unchecked { 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 (int256 (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) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (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) { unchecked { 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 (int256 (63 - (x >> 64))); require (result <= uint256 (int256 (MAX_64x64))); return int128 (int256 (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) { unchecked { 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) { unchecked { 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 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) { unchecked { 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); } } } } // File contracts/interfaces/IHedgeOptions.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev 定义欧式期权接口 interface IHedgeOptions { // // 代币通道配置结构体 // struct Config { // // 波动率 // uint96 sigmaSQ; // // 64位二进制精度 // // 0.3/365/86400 = 9.512937595129377E-09 // // 175482725206 // int128 miu; // // 期权行权时间和当前时间的最小间隔 // uint32 minPeriod; // } /// @dev 期权信息 struct OptionView { uint index; address tokenAddress; uint strikePrice; bool orientation; uint exerciseBlock; uint balance; } /// @dev 新期权事件 /// @param tokenAddress 目标代币地址,0表示eth /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @param index 期权编号 event New(address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock, uint index); /// @dev 开仓事件 /// @param index 期权编号 /// @param dcuAmount 支付的dcu数量 /// @param owner 所有者 /// @param amount 买入份数 event Open( uint index, uint dcuAmount, address owner, uint amount ); /// @dev 行权事件 /// @param index 期权编号 /// @param amount 结算的期权分数 /// @param owner 所有者 /// @param gain 赢得的dcu数量 event Exercise(uint index, uint amount, address owner, uint gain); /// @dev 卖出事件 /// @param index 期权编号 /// @param amount 卖出份数 /// @param owner 所有者 /// @param dcuAmount 得到的dcu数量 event Sell(uint index, uint amount, address owner, uint dcuAmount); // /// @dev 修改指定代币通道的配置 // /// @param tokenAddress 目标代币地址 // /// @param config 配置对象 // function setConfig(address tokenAddress, Config calldata config) external; // /// @dev 获取指定代币通道的配置 // /// @param tokenAddress 目标代币地址 // /// @return 配置对象 // function getConfig(address tokenAddress) external view returns (Config memory); /// @dev 返回指定期权的余额 /// @param index 目标期权索引号 /// @param addr 目标地址 function balanceOf(uint index, address addr) external view returns (uint); /// @dev 查找目标账户的期权(倒序) /// @param start 从给定的合约地址对应的索引向前查询(不包含start对应的记录) /// @param count 最多返回的记录条数 /// @param maxFindCount 最多查找maxFindCount记录 /// @param owner 目标账户地址 /// @return optionArray 期权信息列表 function find( uint start, uint count, uint maxFindCount, address owner ) external view returns (OptionView[] memory optionArray); /// @dev 列出历史期权信息 /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return optionArray 期权信息列表 function list(uint offset, uint count, uint order) external view returns (OptionView[] memory optionArray); /// @dev 获取已经开通的欧式期权代币数量 /// @return 已经开通的欧式期权代币数量 function getOptionCount() external view returns (uint); /// @dev 获取期权信息 /// @param tokenAddress 目标代币地址,0表示eth /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @return 期权信息 function getOptionInfo( address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock ) external view returns (OptionView memory); /// @dev 预估开仓可以买到的期权币数量 /// @param tokenAddress 目标代币地址,0表示eth /// @param oraclePrice 当前预言机价格价 /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @param dcuAmount 支付的dcu数量 /// @return amount 预估可以获得的期权币数量 function estimate( address tokenAddress, uint oraclePrice, uint strikePrice, bool orientation, uint exerciseBlock, uint dcuAmount ) external view returns (uint amount); /// @dev 开仓 /// @param tokenAddress 目标代币地址,0表示eth /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @param dcuAmount 支付的dcu数量 function open( address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock, uint dcuAmount ) external payable; /// @dev 行权 /// @param index 期权编号 /// @param amount 结算的期权分数 function exercise(uint index, uint amount) external payable; /// @dev 卖出期权 /// @param index 期权编号 /// @param amount 卖出的期权分数 function sell(uint index, uint amount) external payable; /// @dev 计算期权价格 /// @param tokenAddress 目标代币地址,0表示eth /// @param oraclePrice 当前预言机价格价 /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @return v 期权价格,需要除以18446744073709551616000000 function calcV( address tokenAddress, uint oraclePrice, uint strikePrice, bool orientation, uint exerciseBlock ) external view returns (uint v); } // File contracts/interfaces/INestPriceFacade.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the methods for price call entry interface INestPriceFacade { /// @dev Find the price at block number /// @param tokenAddress Destination token address /// @param height Destination block number /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function findPrice( address tokenAddress, uint height, address paybackAddress ) external payable returns (uint blockNumber, uint price); /// @dev Get the latest trigger price /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function triggeredPrice( address tokenAddress, address paybackAddress ) external payable returns (uint blockNumber, uint price); // /// @dev Price call entry configuration structure // struct Config { // // Single query fee(0.0001 ether, DIMI_ETHER). 100 // uint16 singleFee; // // Double query fee(0.0001 ether, DIMI_ETHER). 100 // uint16 doubleFee; // // The normal state flag of the call address. 0 // uint8 normalFlag; // } // /// @dev Modify configuration // /// @param config Configuration object // function setConfig(Config calldata config) external; // /// @dev Get configuration // /// @return Configuration object // function getConfig() external view returns (Config memory); // /// @dev Set the address flag. Only the address flag equals to config.normalFlag can the price be called // /// @param addr Destination address // /// @param flag Address flag // function setAddressFlag(address addr, uint flag) external; // /// @dev Get the flag. Only the address flag equals to config.normalFlag can the price be called // /// @param addr Destination address // /// @return Address flag // function getAddressFlag(address addr) external view returns(uint); // /// @dev Set INestQuery implementation contract address for token // /// @param tokenAddress Destination token address // /// @param nestQueryAddress INestQuery implementation contract address, 0 means delete // function setNestQuery(address tokenAddress, address nestQueryAddress) external; // /// @dev Get INestQuery implementation contract address for token // /// @param tokenAddress Destination token address // /// @return INestQuery implementation contract address, 0 means use default // function getNestQuery(address tokenAddress) external view returns (address); // /// @dev Get cached fee in fee channel // /// @param tokenAddress Destination token address // /// @return Cached fee in fee channel // function getTokenFee(address tokenAddress) external view returns (uint); // /// @dev Settle fee for charge fee channel // /// @param tokenAddress tokenAddress of charge fee channel // function settle(address tokenAddress) external; // /// @dev Get the latest trigger price // /// @param tokenAddress Destination token address // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // function triggeredPrice( // address tokenAddress, // address paybackAddress // ) external payable returns (uint blockNumber, uint price); /// @dev Get the full information of latest trigger price /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo( address tokenAddress, address paybackAddress ) external payable returns (uint blockNumber, uint price, uint avgPrice, uint sigmaSQ); // /// @dev Find the price at block number // /// @param tokenAddress Destination token address // /// @param height Destination block number // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // function findPrice( // address tokenAddress, // uint height, // address paybackAddress // ) external payable returns (uint blockNumber, uint price); /// @dev Get the latest effective price /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function latestPrice( address tokenAddress, address paybackAddress ) external payable returns (uint blockNumber, uint price); // /// @dev Get the last (num) effective price // /// @param tokenAddress Destination token address // /// @param count The number of prices that want to return // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price // function lastPriceList( // address tokenAddress, // uint count, // address paybackAddress // ) external payable returns (uint[] memory); // /// @dev Returns the results of latestPrice() and triggeredPriceInfo() // /// @param tokenAddress Destination token address // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return latestPriceBlockNumber The block number of latest price // /// @return latestPriceValue The token latest price. (1eth equivalent to (price) token) // /// @return triggeredPriceBlockNumber The block number of triggered price // /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) // /// @return triggeredAvgPrice Average price // /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation // /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to // /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed // function latestPriceAndTriggeredPriceInfo(address tokenAddress, address paybackAddress) // external // payable // returns ( // uint latestPriceBlockNumber, // uint latestPriceValue, // uint triggeredPriceBlockNumber, // uint triggeredPriceValue, // uint triggeredAvgPrice, // uint triggeredSigmaSQ // ); /// @dev Returns lastPriceList and triggered price info /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed function lastPriceListAndTriggeredPriceInfo( address tokenAddress, uint count, address paybackAddress ) external payable returns ( uint[] memory prices, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ); // /// @dev Get the latest trigger price. (token and ntoken) // /// @param tokenAddress Destination token address // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // /// @return ntokenBlockNumber The block number of ntoken price // /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) // function triggeredPrice2( // address tokenAddress, // address paybackAddress // ) external payable returns ( // uint blockNumber, // uint price, // uint ntokenBlockNumber, // uint ntokenPrice // ); // /// @dev Get the full information of latest trigger price. (token and ntoken) // /// @param tokenAddress Destination token address // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // /// @return avgPrice Average price // /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that // /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, // /// it means that the volatility has exceeded the range that can be expressed // /// @return ntokenBlockNumber The block number of ntoken price // /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) // /// @return ntokenAvgPrice Average price of ntoken // /// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation // /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to // /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed // function triggeredPriceInfo2( // address tokenAddress, // address paybackAddress // ) external payable returns ( // uint blockNumber, // uint price, // uint avgPrice, // uint sigmaSQ, // uint ntokenBlockNumber, // uint ntokenPrice, // uint ntokenAvgPrice, // uint ntokenSigmaSQ // ); // /// @dev Get the latest effective price. (token and ntoken) // /// @param tokenAddress Destination token address // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // /// @return ntokenBlockNumber The block number of ntoken price // /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) // function latestPrice2( // address tokenAddress, // address paybackAddress // ) external payable returns ( // uint blockNumber, // uint price, // uint ntokenBlockNumber, // uint ntokenPrice // ); } // File contracts/interfaces/IHedgeMapping.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev The interface defines methods for Hedge builtin contract address mapping interface IHedgeMapping { /// @dev Set the built-in contract address of the system /// @param dcuToken Address of dcu token contract /// @param hedgeDAO IHedgeDAO implementation contract address /// @param hedgeOptions IHedgeOptions implementation contract address /// @param hedgeFutures IHedgeFutures implementation contract address /// @param hedgeVaultForStaking IHedgeVaultForStaking implementation contract address /// @param nestPriceFacade INestPriceFacade implementation contract address function setBuiltinAddress( address dcuToken, address hedgeDAO, address hedgeOptions, address hedgeFutures, address hedgeVaultForStaking, address nestPriceFacade ) external; /// @dev Get the built-in contract address of the system /// @return dcuToken Address of dcu token contract /// @return hedgeDAO IHedgeDAO implementation contract address /// @return hedgeOptions IHedgeOptions implementation contract address /// @return hedgeFutures IHedgeFutures implementation contract address /// @return hedgeVaultForStaking IHedgeVaultForStaking implementation contract address /// @return nestPriceFacade INestPriceFacade implementation contract address function getBuiltinAddress() external view returns ( address dcuToken, address hedgeDAO, address hedgeOptions, address hedgeFutures, address hedgeVaultForStaking, address nestPriceFacade ); /// @dev Get address of dcu token contract /// @return Address of dcu token contract function getDCUTokenAddress() external view returns (address); /// @dev Get IHedgeDAO implementation contract address /// @return IHedgeDAO implementation contract address function getHedgeDAOAddress() external view returns (address); /// @dev Get IHedgeOptions implementation contract address /// @return IHedgeOptions implementation contract address function getHedgeOptionsAddress() external view returns (address); /// @dev Get IHedgeFutures implementation contract address /// @return IHedgeFutures implementation contract address function getHedgeFuturesAddress() external view returns (address); /// @dev Get IHedgeVaultForStaking implementation contract address /// @return IHedgeVaultForStaking implementation contract address function getHedgeVaultForStakingAddress() external view returns (address); /// @dev Get INestPriceFacade implementation contract address /// @return INestPriceFacade implementation contract address function getNestPriceFacade() external view returns (address); /// @dev Registered address. The address registered here is the address accepted by Hedge system /// @param key The key /// @param addr Destination address. 0 means to delete the registration information function registerAddress(string calldata key, address addr) external; /// @dev Get registered address /// @param key The key /// @return Destination address. 0 means empty function checkAddress(string calldata key) external view returns (address); } // File contracts/interfaces/IHedgeGovernance.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the governance methods interface IHedgeGovernance is IHedgeMapping { /// @dev Set governance authority /// @param addr Destination address /// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function setGovernance(address addr, uint flag) external; /// @dev Get governance rights /// @param addr Destination address /// @return Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function getGovernance(address addr) external view returns (uint); /// @dev Check whether the target address has governance rights for the given target /// @param addr Destination address /// @param flag Permission weight. The permission of the target address must be greater than this weight /// to pass the check /// @return True indicates permission function checkGovernance(address addr, uint flag) external view returns (bool); } // File contracts/interfaces/IHedgeDAO.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the DAO methods interface IHedgeDAO { /// @dev Application Flag Changed event /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization event ApplicationChanged(address addr, uint flag); /// @dev Set DAO application /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization function setApplication(address addr, uint flag) external; /// @dev Check DAO application flag /// @param addr DAO application contract address /// @return Authorization flag, 1 means authorization, 0 means cancel authorization function checkApplication(address addr) external view returns (uint); /// @dev Add reward /// @param pool Destination pool function addETHReward(address pool) external payable; /// @dev The function returns eth rewards of specified pool /// @param pool Destination pool function totalETHRewards(address pool) external view returns (uint); /// @dev Settlement /// @param pool Destination pool. Indicates which pool to pay with /// @param tokenAddress Token address of receiving funds (0 means ETH) /// @param to Address to receive /// @param value Amount to receive function settle(address pool, address tokenAddress, address to, uint value) external payable; } // File contracts/HedgeBase.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev Base contract of Hedge contract HedgeBase { /// @dev IHedgeGovernance implementation contract address address public _governance; /// @dev To support open-zeppelin/upgrades /// @param governance IHedgeGovernance implementation contract address function initialize(address governance) public virtual { require(_governance == address(0), "Hedge:!initialize"); _governance = governance; } /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(newGovernance) when overriding, and override method without onlyGovernance /// @param newGovernance IHedgeGovernance implementation contract address function update(address newGovernance) public virtual { address governance = _governance; require(governance == msg.sender || IHedgeGovernance(governance).checkGovernance(msg.sender, 0), "Hedge:!gov"); _governance = newGovernance; } /// @dev Migrate funds from current contract to HedgeDAO /// @param tokenAddress Destination token address.(0 means eth) /// @param value Migrate amount function migrate(address tokenAddress, uint value) external onlyGovernance { address to = IHedgeGovernance(_governance).getHedgeDAOAddress(); if (tokenAddress == address(0)) { IHedgeDAO(to).addETHReward { value: value } (address(0)); } else { TransferHelper.safeTransfer(tokenAddress, to, value); } } //---------modifier------------ modifier onlyGovernance() { require(IHedgeGovernance(_governance).checkGovernance(msg.sender, 0), "Hedge:!gov"); _; } modifier noContract() { require(msg.sender == tx.origin, "Hedge:!contract"); _; } } // File contracts/HedgeFrequentlyUsed.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev Base contract of Hedge contract HedgeFrequentlyUsed is HedgeBase { // Address of DCU contract address constant DCU_TOKEN_ADDRESS = 0xf56c6eCE0C0d6Fbb9A53282C0DF71dBFaFA933eF; // Address of NestPriceFacade contract address constant NEST_PRICE_FACADE_ADDRESS = 0xB5D2890c061c321A5B6A4a4254bb1522425BAF0A; // USDT代币地址 address constant USDT_TOKEN_ADDRESS = 0xdAC17F958D2ee523a2206206994597C13D831ec7; // USDT代币的基数 uint constant USDT_BASE = 1000000; } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] // MIT pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File @openzeppelin/contracts/utils/[email protected] // 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; } } // File @openzeppelin/contracts/token/ERC20/[email protected] // MIT pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File contracts/DCU.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev DCU代币 contract DCU is HedgeBase, ERC20("Decentralized Currency Unit", "DCU") { // 保存挖矿权限地址 mapping(address=>uint) _minters; constructor() { } modifier onlyMinter { require(_minters[msg.sender] == 1, "DCU:not minter"); _; } /// @dev 设置挖矿权限 /// @param account 目标账号 /// @param flag 挖矿权限标记,只有1表示可以挖矿 function setMinter(address account, uint flag) external onlyGovernance { _minters[account] = flag; } /// @dev 检查挖矿权限 /// @param account 目标账号 /// @return flag 挖矿权限标记,只有1表示可以挖矿 function checkMinter(address account) external view returns (uint) { return _minters[account]; } /// @dev 铸币 /// @param to 接受地址 /// @param value 铸币数量 function mint(address to, uint value) external onlyMinter { _mint(to, value); } /// @dev 销毁 /// @param from 目标地址 /// @param value 销毁数量 function burn(address from, uint value) external onlyMinter { _burn(from, value); } } // File contracts/HedgeOptions.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev 欧式期权 contract HedgeOptions is HedgeFrequentlyUsed, IHedgeOptions { /// @dev 期权结构 struct Option { address tokenAddress; uint56 strikePrice; bool orientation; uint32 exerciseBlock; //uint totalSupply; mapping(address=>uint) balances; } // 区块时间 uint constant BLOCK_TIME = 14; // 64位二进制精度的1 int128 constant ONE = 0x10000000000000000; // 64位二进制精度的50000 uint constant V50000 = 0x0C3500000000000000000; // 期权卖出价值比例,万分制。9750 uint constant SELL_RATE = 9500; // σ-usdt 0.00021368 波动率,每个币种独立设置(年化120%) uint constant SIGMA_SQ = 45659142400; // μ-usdt 0.000000025367 漂移系数,每个币种独立设置(年化80%) uint constant MIU = 467938556917; // 期权行权最小间隔 6000 区块数 行权时间和当前时间最小间隔区块数,统一设置 uint constant MIN_PERIOD = 180000; // 期权代币映射 mapping(uint=>uint) _optionMapping; // // 配置参数 // mapping(address=>Config) _configs; // 缓存代币的基数值 mapping(address=>uint) _bases; // 期权代币数组 Option[] _options; constructor() { } /// @dev To support open-zeppelin/upgrades /// @param governance IHedgeGovernance implementation contract address function initialize(address governance) public override { super.initialize(governance); _options.push(); } // /// @dev 修改指定代币通道的配置 // /// @param tokenAddress 目标代币地址 // /// @param config 配置对象 // function setConfig(address tokenAddress, Config calldata config) external override { // _configs[tokenAddress] = config; // } // /// @dev 获取指定代币通道的配置 // /// @param tokenAddress 目标代币地址 // /// @return 配置对象 // function getConfig(address tokenAddress) external view override returns (Config memory) { // return _configs[tokenAddress]; // } /// @dev 返回指定期权的余额 /// @param index 目标期权索引号 /// @param addr 目标地址 function balanceOf(uint index, address addr) external view override returns (uint) { return _options[index].balances[addr]; } /// @dev 查找目标账户的期权(倒序) /// @param start 从给定的合约地址对应的索引向前查询(不包含start对应的记录) /// @param count 最多返回的记录条数 /// @param maxFindCount 最多查找maxFindCount记录 /// @param owner 目标账户地址 /// @return optionArray 期权信息列表 function find( uint start, uint count, uint maxFindCount, address owner ) external view override returns (OptionView[] memory optionArray) { optionArray = new OptionView[](count); // 计算查找区间i和end Option[] storage options = _options; uint i = options.length; uint end = 0; if (start > 0) { i = start; } if (i > maxFindCount) { end = i - maxFindCount; } // 循环查找,将符合条件的记录写入缓冲区 for (uint index = 0; index < count && i > end;) { Option storage option = options[--i]; if (option.balances[owner] > 0) { optionArray[index++] = _toOptionView(option, i, owner); } } } /// @dev 列出历史期权信息 /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return optionArray 期权信息列表 function list( uint offset, uint count, uint order ) external view override returns (OptionView[] memory optionArray) { // 加载代币数组 Option[] storage options = _options; // 创建结果数组 optionArray = new OptionView[](count); uint length = options.length; uint i = 0; // 倒序 if (order == 0) { uint index = length - offset; uint end = index > count ? index - count : 0; while (index > end) { Option storage option = options[--index]; optionArray[i++] = _toOptionView(option, index, msg.sender); } } // 正序 else { uint index = offset; uint end = index + count; if (end > length) { end = length; } while (index < end) { optionArray[i++] = _toOptionView(options[index], index, msg.sender); ++index; } } } /// @dev 获取已经开通的欧式期权代币数量 /// @return 已经开通的欧式期权代币数量 function getOptionCount() external view override returns (uint) { return _options.length; } /// @dev 获取期权信息 /// @param tokenAddress 目标代币地址,0表示eth /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @return 期权信息 function getOptionInfo( address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock ) external view override returns (OptionView memory) { uint index = _optionMapping[_getKey(tokenAddress, strikePrice, orientation, exerciseBlock)]; return _toOptionView(_options[index], index, msg.sender); } /// @dev 开仓 /// @param tokenAddress 目标代币地址,0表示eth /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @param dcuAmount 支付的dcu数量 function open( address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock, uint dcuAmount ) external payable override { // 1. 调用预言机获取价格 uint oraclePrice = _queryPrice(tokenAddress, msg.value, msg.sender); // 2. 计算可以买到的期权份数 uint amount = estimate(tokenAddress, oraclePrice, strikePrice, orientation, exerciseBlock, dcuAmount); // 3. 获取或创建期权代币 uint key = _getKey(tokenAddress, strikePrice, orientation, exerciseBlock); uint optionIndex = _optionMapping[key]; Option storage option = _options[optionIndex]; if (optionIndex == 0) { optionIndex = _options.length; option = _options.push(); option.tokenAddress = tokenAddress; option.strikePrice = _encodeFloat(strikePrice); option.orientation = orientation; option.exerciseBlock = uint32(exerciseBlock); // 将期权代币地址存入映射和数组,便于后面检索 _optionMapping[key] = optionIndex; // 新期权 //emit New(tokenAddress, strikePrice, orientation, exerciseBlock, optionIndex); } // 4. 销毁权利金 DCU(DCU_TOKEN_ADDRESS).burn(msg.sender, dcuAmount); // 5. 分发期权凭证 option.balances[msg.sender] += amount; // 开仓事件 emit Open(optionIndex, dcuAmount, msg.sender, amount); } /// @dev 预估开仓可以买到的期权币数量 /// @param tokenAddress 目标代币地址,0表示eth /// @param oraclePrice 当前预言机价格价 /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @param dcuAmount 支付的dcu数量 /// @return amount 预估可以获得的期权币数量 function estimate( address tokenAddress, uint oraclePrice, uint strikePrice, bool orientation, uint exerciseBlock, uint dcuAmount ) public view override returns (uint amount) { //Config memory config = _configs[tokenAddress]; //uint minPeriod = uint(config.minPeriod); require(exerciseBlock > block.number + MIN_PERIOD, "FEO:exerciseBlock to small"); // 1. 获取或创建期权代币 // 2. 调用预言机获取价格 // 3. 计算权利金(需要的dcu数量) // 按照平均每14秒出一个块计算 uint v = calcV( tokenAddress, oraclePrice, strikePrice, orientation, exerciseBlock ); if (orientation) { //v = _calcVc(config, oraclePrice, T, strikePrice); // Vc>=S0*1%; Vp>=K*1% // require(v * 100 >> 64 >= oraclePrice, "FEO:vc must greater than S0*1%"); if (v * 100 >> 64 < oraclePrice) { v = oraclePrice * 0x10000000000000000 / 100; } } else { //v = _calcVp(config, oraclePrice, T, strikePrice); // Vc>=S0*1%; Vp>=K*1% // require(v * 100 >> 64 >= strikePrice, "FEO:vp must greater than K*1%"); if (v * 100 >> 64 < strikePrice) { v = strikePrice * 0x10000000000000000 / 100; } } amount = (USDT_BASE << 64) * dcuAmount / v; } /// @dev 行权 /// @param index 期权编号 /// @param amount 结算的期权分数 function exercise(uint index, uint amount) external payable override { // 1. 获取期权信息 Option storage option = _options[index]; address tokenAddress = option.tokenAddress; uint strikePrice = _decodeFloat(option.strikePrice); bool orientation = option.orientation; uint exerciseBlock = uint(option.exerciseBlock); require(block.number >= exerciseBlock, "FEO:at maturity"); // 2. 销毁期权代币 option.balances[msg.sender] -= amount; // 3. 调用预言机获取价格,读取预言机在指定区块的价格 // 3.1. 获取token相对于eth的价格 uint tokenAmount = 1 ether; uint fee = msg.value; if (tokenAddress != address(0)) { fee = msg.value >> 1; (, tokenAmount) = INestPriceFacade(NEST_PRICE_FACADE_ADDRESS).findPrice { value: fee } (tokenAddress, exerciseBlock, msg.sender); } // 3.2. 获取usdt相对于eth的价格 (, uint usdtAmount) = INestPriceFacade(NEST_PRICE_FACADE_ADDRESS).findPrice { value: fee } (USDT_TOKEN_ADDRESS, exerciseBlock, msg.sender); // 将token价格转化为以usdt为单位计算的价格 uint oraclePrice = usdtAmount * _getBase(tokenAddress) / tokenAmount; // 4. 分情况计算用户可以获得的dcu数量 uint gain = 0; // 计算结算结果 // 看涨期权 if (orientation) { // 赌赢了 if (oraclePrice > strikePrice) { gain = amount * (oraclePrice - strikePrice) / USDT_BASE; } } // 看跌期权 else { // 赌赢了 if (oraclePrice < strikePrice) { gain = amount * (strikePrice - oraclePrice) / USDT_BASE; } } // 5. 用户赌赢了,给其增发赢得的dcu if (gain > 0) { DCU(DCU_TOKEN_ADDRESS).mint(msg.sender, gain); } // 行权事件 emit Exercise(index, amount, msg.sender, gain); } /// @dev 卖出期权 /// @param index 期权编号 /// @param amount 卖出的期权分数 function sell(uint index, uint amount) external payable override { // 期权卖出公式:vt=Max(ct(T,K)*0.975,0)其中ct(K,T)是按照定价公式计算的期权成本, // 注意,不是包含了不低于1%这个设定 // 1. 获取期权信息 Option storage option = _options[index]; address tokenAddress = option.tokenAddress; uint strikePrice = _decodeFloat(option.strikePrice); bool orientation = option.orientation; uint exerciseBlock = uint(option.exerciseBlock); // 2. 销毁期权代币 option.balances[msg.sender] -= amount; // 3. 调用预言机获取价格,读取预言机在指定区块的价格 uint oraclePrice = _queryPrice(tokenAddress, msg.value, msg.sender); // 4. 分情况计算当前情况下的期权价格 // 按照平均每14秒出一个块计算 uint dcuAmount = amount * calcV( tokenAddress, oraclePrice, strikePrice, orientation, exerciseBlock ) * SELL_RATE / (USDT_BASE * 10000 << 64); if (dcuAmount > 0) { DCU(DCU_TOKEN_ADDRESS).mint(msg.sender, dcuAmount); } // 卖出事件 emit Sell(index, amount, msg.sender, dcuAmount); } /// @dev 计算期权价格 /// @param tokenAddress 目标代币地址,0表示eth /// @param oraclePrice 当前预言机价格价 /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @return v 期权价格,需要除以18446744073709551616000000 function calcV( address tokenAddress, uint oraclePrice, uint strikePrice, bool orientation, uint exerciseBlock ) public view override returns (uint v) { require(tokenAddress == address(0), "FEO:not allowed"); //Config memory config = _configs[tokenAddress]; //uint minPeriod = uint(config.minPeriod); //require(minPeriod > 0, "FEO:not allowed"); //require(exerciseBlock > block.number + minPeriod, "FEO:exerciseBlock to small"); // 1. 获取或创建期权代币 // 2. 调用预言机获取价格 // 3. 计算权利金(需要的dcu数量) // 按照平均每14秒出一个块计算 uint T = (exerciseBlock - block.number) * BLOCK_TIME; v = orientation ? _calcVc(oraclePrice, T, strikePrice) : _calcVp(oraclePrice, T, strikePrice); } // 转化位OptionView function _toOptionView( Option storage option, uint index, address owner ) private view returns (OptionView memory) { return OptionView( index, option.tokenAddress, _decodeFloat(option.strikePrice), option.orientation, uint(option.exerciseBlock), option.balances[owner] ); } // 根据期权信息获取索引key function _getKey( address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock ) private pure returns (uint) { //return keccak256(abi.encodePacked(tokenAddress, strikePrice, orientation, exerciseBlock)); require(exerciseBlock < 0x100000000, "FEO:exerciseBlock to large"); return (uint(uint160(tokenAddress)) << 96) | (uint(_encodeFloat(strikePrice)) << 40) | (exerciseBlock << 8) | (orientation ? 1 : 0); } // 获取代币的基数值 function _getBase(address tokenAddress) private returns (uint base) { if (tokenAddress == address(0)) { base = 1 ether; } else { base = _bases[tokenAddress]; if (base == 0) { base = 10 ** ERC20(tokenAddress).decimals(); _bases[tokenAddress] = base; } } } // 将18位十进制定点数转化为64位二级制定点数 function _d18TOb64(uint v) private pure returns (int128) { require(v < 0x6F05B59D3B200000000000000000000, "FEO:can't convert to 64bits"); return int128(int((v << 64) / 1 ether)); } // 将uint转化为int128 function _toInt128(uint v) private pure returns (int128) { require(v < 0x80000000000000000000000000000000, "FEO:can't convert to int128"); return int128(int(v)); } // 将int128转化为uint function _toUInt(int128 v) private pure returns (uint) { require(v >= 0, "FEO:can't convert to uint"); return uint(int(v)); } // 通过查表的方法计算标准正态分布函数 function _snd(int128 x) private pure returns (int128) { uint[28] memory table = [ /* */ ///////////////////// STANDARD NORMAL TABLE ////////////////////////// /* */ 0x174A15BF143412A8111C0F8F0E020C740AE6095807CA063B04AD031E018F0000, // ///// 0x2F8C2E0F2C912B1229922811268F250B23872202207D1EF61D6F1BE61A5D18D8, // /* */ 0x2F8C2E0F2C912B1229922811268F250B23872202207D1EF61D6F1BE61A5D18D4, // /* */ 0x46A2453C43D4426B41003F943E263CB63B4539D3385F36EA357333FB32823108, // /* */ 0x5C0D5AC5597B582F56E05590543E52EA5194503C4EE24D874C294ACA49694807, // /* */ 0x6F6C6E466D1F6BF56AC9699B686A6738660364CC6392625761195FD95E975D53, // /* */ 0x807E7F7F7E7D7D797C737B6A7A5F79517841772F761A750373E972CD71AF708E, // /* */ 0x8F2A8E518D768C998BB98AD789F2890B88218736864785568463836E8276817B, // /* */ 0x9B749AC19A0B9953989997DD971E965D959A94D4940C9342927591A690D49000, // /* */ 0xA57CA4ECA459A3C4A32EA295A1FAA15CA0BDA01C9F789ED29E2A9D809CD39C25, // ///// 0xA57CA4ECA459A3C4A32EA295A1FAA15DA0BDA01C9F789ED29E2A9D809CD39C25, // /* */ 0xAD78AD07AC93AC1EABA7AB2EAAB3AA36A9B8A937A8B5A830A7AAA721A697A60B, // /* */ 0xB3AAB353B2FAB2A0B245B1E7B189B128B0C6B062AFFDAF96AF2DAEC2AE56ADE8, // /* */ 0xB859B818B7D6B793B74EB708B6C0B678B62EB5E2B595B547B4F7B4A6B454B400, // /* */ 0xBBCDBB9EBB6EBB3CBB0ABAD7BAA2BA6DBA36B9FFB9C6B98CB951B915B8D8B899, // /* */ 0xBE49BE27BE05BDE2BDBEBD99BD74BD4DBD26BCFEBCD5BCACBC81BC56BC29BBFC, // /* */ 0xC006BFEEBFD7BFBEBFA5BF8CBF72BF57BF3CBF20BF03BEE6BEC8BEA9BE8ABE69, // /* */ 0xC135C126C116C105C0F4C0E3C0D1C0BFC0ACC099C086C072C05DC048C032C01C, // /* */ 0xC200C1F5C1EBC1E0C1D5C1C9C1BEC1B1C1A5C198C18BC17EC170C162C154C145, // /* */ 0xC283C27CC275C26EC267C260C258C250C248C240C238C22FC226C21DC213C20A, // /* */ 0xC2D6C2D2C2CDC2C9C2C5C2C0C2BBC2B6C2B1C2ACC2A7C2A1C29BC295C28FC289, // /* */ 0xC309C306C304C301C2FEC2FCC2F9C2F6C2F2C2EFC2ECC2E8C2E5C2E1C2DEC2DA, // /* */ 0xC328C326C325C323C321C320C31EC31CC31AC318C316C314C312C310C30EC30B, // /* */ 0xC33AC339C338C337C336C335C334C333C332C331C330C32EC32DC32CC32AC329, // /* */ 0xC344C343C343C342C342C341C341C340C33FC33FC33EC33DC33DC33CC33BC33A, // /* */ 0xC34AC349C349C349C348C348C348C348C347C347C346C346C346C345C345C344, // /* */ 0xC34DC34DC34CC34CC34CC34CC34CC34CC34BC34BC34BC34BC34BC34AC34AC34A, // /* */ 0xC34EC34EC34EC34EC34EC34EC34EC34EC34EC34EC34DC34DC34DC34DC34DC34D, // /* */ 0xC34FC34FC34FC34FC34FC34FC34FC34FC34FC34FC34FC34FC34FC34FC34EC34E, // /* */ 0xC350C350C350C350C350C350C34FC34FC34FC34FC34FC34FC34FC34FC34FC34F // /* */ //////////////////// MADE IN CHINA 2021-08-24 //////////////////////// ]; uint ux = uint(int(x < 0 ? -x : x)) * 100; uint i = ux >> 64; uint v = V50000; if (i < 447) { v = uint((table[i >> 4] >> ((i & 0xF) << 4)) & 0xFFFF) << 64; v = ( ( ( (uint((table[(i + 1) >> 4] >> (((i + 1) & 0xF) << 4)) & 0xFFFF) << 64) - v ) * (ux & 0xFFFFFFFFFFFFFFFF) //(ux - (i << 64)) ) >> 64 ) + v; } if (x > 0) { v = V50000 + v; } else { v = V50000 - v; } return int128(int(v / 100000)); } // 查询token价格 function _queryPrice(address tokenAddress, uint fee, address payback) private returns (uint oraclePrice) { // 1.1. 获取token相对于eth的价格 uint tokenAmount = 1 ether; //uint fee = msg.value; if (tokenAddress != address(0)) { fee >>= 1; (, tokenAmount) = INestPriceFacade(NEST_PRICE_FACADE_ADDRESS).latestPrice { value: fee } (tokenAddress, payback); } // 1.2. 获取usdt相对于eth的价格 (, uint usdtAmount) = INestPriceFacade(NEST_PRICE_FACADE_ADDRESS).latestPrice { value: fee } (USDT_TOKEN_ADDRESS, payback); // 1.3. 将token价格转化为以usdt为单位计算的价格 oraclePrice = usdtAmount * _getBase(tokenAddress) / tokenAmount; } // 计算看涨期权价格 function _calcVc(uint S0, uint T, uint K) private pure returns (uint vc) { int128 sigmaSQ_T = _d18TOb64(SIGMA_SQ * T); int128 miu_T = _toInt128(MIU * T); int128 sigma_t = ABDKMath64x64.sqrt(sigmaSQ_T); int128 D1 = _D1(S0, K, sigmaSQ_T, miu_T); int128 d = ABDKMath64x64.div(D1, sigma_t); uint left = _toUInt(ABDKMath64x64.mul( ABDKMath64x64.exp(miu_T), ABDKMath64x64.sub( ONE, _snd(ABDKMath64x64.sub(d, sigma_t)) ) )) * S0; uint right = _toUInt(ABDKMath64x64.sub(ONE, _snd(d))) * K; vc = left > right ? left - right : 0; } // 计算看跌期权价格 function _calcVp(uint S0, uint T, uint K) private pure returns (uint vp) { int128 sigmaSQ_T = _d18TOb64(SIGMA_SQ * T); int128 miu_T = _toInt128(MIU * T); int128 sigma_t = ABDKMath64x64.sqrt(sigmaSQ_T); int128 D1 = _D1(S0, K, sigmaSQ_T, miu_T); int128 d = ABDKMath64x64.div(D1, sigma_t); uint left = _toUInt(_snd(d)) * K; uint right = _toUInt(ABDKMath64x64.mul( ABDKMath64x64.exp(miu_T), _snd(ABDKMath64x64.sub(d, sigma_t)) )) * S0; vp = left > right ? left - right : 0; } // 计算公式种的d1,因为没有除以σ,所以命名为D1 function _D1(uint S0, uint K, int128 sigmaSQ_T, int128 miu_T) private pure returns (int128) { //require(K < 0x1000000000000000000000000000000000000000000000000, "FEO:K can't ROL 64bits"); return ABDKMath64x64.sub( ABDKMath64x64.add( ABDKMath64x64.ln(_toInt128(K * 0x10000000000000000 / S0)), sigmaSQ_T >> 1 ), miu_T ); } /// @dev Encode the uint value as a floating-point representation in the form of fraction * 16 ^ exponent /// @param value Destination uint value /// @return float format function _encodeFloat(uint value) private pure returns (uint56) { uint exponent = 0; while (value > 0x3FFFFFFFFFFFF) { value >>= 4; ++exponent; } return uint56((value << 6) | exponent); } /// @dev Decode the floating-point representation of fraction * 16 ^ exponent to uint /// @param floatValue fraction value /// @return decode format function _decodeFloat(uint56 floatValue) private pure returns (uint) { return (uint(floatValue) >> 6) << ((uint(floatValue) & 0x3F) << 2); } }
Encode the uint value as a floating-point representation in the form of fraction 16 ^ exponent value Destination uint value return float format
function _encodeFloat(uint value) private pure returns (uint56) { uint exponent = 0; while (value > 0x3FFFFFFFFFFFF) { value >>= 4; ++exponent; } return uint56((value << 6) | exponent); }
482,512
./partial_match/1/0x0e20655885C38b1b5CEDfFF5b15289b76F3CdefC/sources/FounderSociety.sol
Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length and makes the '0x' prefix optional. MODIFIED: Scrypted Inc./
function toHexString(uint256 value, uint256 length, bool prefix) internal pure returns (string memory) { uint8 offset = prefix ? 2 : 0; uint256 buffer_len = 2 * length + offset; bytes memory buffer = new bytes(buffer_len); for (uint256 i = offset; i <= buffer_len - 1; i++) { buffer[(buffer_len - 1) - i] = _SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); }
15,739,734
//Address: 0xf7eD56c1AC4d038e367a987258b86FC883b960a1 //Contract name: EDCoreVersion1 //Balance: 1.258461497246029186 Ether //Verification Date: 3/10/2018 //Transacion Count: 10653 // CODE STARTS HERE pragma solidity ^0.4.19; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title EjectableOwnable * @dev The EjectableOwnable contract provides the function to remove the ownership of the contract. */ contract EjectableOwnable is Ownable { /** * @dev Remove the ownership by setting the owner address to null, * after calling this function, all onlyOwner function will be be able to be called by anyone anymore, * the contract will achieve truly decentralisation. */ function removeOwnership() onlyOwner public { owner = 0x0; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @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; } } /** * @title PullPayment * @dev Base contract supporting async send for pull payments. Inherit from this * contract and use asyncSend instead of send. */ contract PullPayment { using SafeMath for uint256; mapping(address => uint256) public payments; uint256 public totalPayments; /** * @dev withdraw accumulated balance, called by payee. */ function withdrawPayments() public { address payee = msg.sender; uint256 payment = payments[payee]; require(payment != 0); require(this.balance >= payment); totalPayments = totalPayments.sub(payment); payments[payee] = 0; assert(payee.send(payment)); } /** * @dev Called by the payer to store the sent amount as credit to be pulled. * @param dest The destination address of the funds. * @param amount The amount to transfer. */ function asyncSend(address dest, uint256 amount) internal { payments[dest] = payments[dest].add(amount); totalPayments = totalPayments.add(amount); } } /** * @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 { function Destructible() 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); } } contract EDStructs { /** * @dev The main Dungeon struct. Every dungeon in the game is represented by this structure. * A dungeon is consists of an unlimited number of floors for your heroes to challenge, * the power level of a dungeon is encoded in the floorGenes. Some dungeons are in fact more "challenging" than others, * the secret formula for that is left for user to find out. * * Each dungeon also has a "training area", heroes can perform trainings and upgrade their stat, * and some dungeons are more effective in the training, which is also a secret formula! * * When player challenge or do training in a dungeon, the fee will be collected as the dungeon rewards, * which will be rewarded to the player who successfully challenged the current floor. * * Each dungeon fits in fits into three 256-bit words. */ struct Dungeon { // Each dungeon has an ID which is the index in the storage array. // The timestamp of the block when this dungeon is created. uint32 creationTime; // The status of the dungeon, each dungeon can have 5 status, namely: // 0: Active | 1: Transport Only | 2: Challenge Only | 3: Train Only | 4: InActive uint8 status; // The dungeon's difficulty, the higher the difficulty, // normally, the "rarer" the seedGenes, the higher the diffculty, // and the higher the contribution fee it is to challenge, train, and transport to the dungeon, // the formula for the contribution fee is in DungeonChallenge and DungeonTraining contracts. // A dungeon's difficulty never change. uint8 difficulty; // The dungeon's capacity, maximum number of players allowed to stay on this dungeon. // The capacity of the newbie dungeon (Holyland) is set at 0 (which is infinity). // Using 16-bit unsigned integers can have a maximum of 65535 in capacity. // A dungeon's capacity never change. uint16 capacity; // The current floor number, a dungeon is consists of an umlimited number of floors, // when there is heroes successfully challenged a floor, the next floor will be // automatically generated. Using 32-bit unsigned integer can have a maximum of 4 billion floors. uint32 floorNumber; // The timestamp of the block when the current floor is generated. uint32 floorCreationTime; // Current accumulated rewards, successful challenger will get a large proportion of it. uint128 rewards; // The seed genes of the dungeon, it is used as the base gene for first floor, // some dungeons are rarer and some are more common, the exact details are, // of course, top secret of the game! // A dungeon's seedGenes never change. uint seedGenes; // The genes for current floor, it encodes the difficulty level of the current floor. // We considered whether to store the entire array of genes for all floors, but // in order to save some precious gas we're willing to sacrifice some functionalities with that. uint floorGenes; } /** * @dev The main Hero struct. Every hero in the game is represented by this structure. */ struct Hero { // Each hero has an ID which is the index in the storage array. // The timestamp of the block when this dungeon is created. uint64 creationTime; // The timestamp of the block where a challenge is performed, used to calculate when a hero is allowed to engage in another challenge. uint64 cooldownStartTime; // Every time a hero challenge a dungeon, its cooldown index will be incremented by one. uint32 cooldownIndex; // The seed of the hero, the gene encodes the power level of the hero. // This is another top secret of the game! Hero's gene can be upgraded via // training in a dungeon. uint genes; } } /** * @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens. */ contract ERC721 { // Events event Transfer(address indexed from, address indexed to, uint indexed tokenId); event Approval(address indexed owner, address indexed approved, uint indexed tokenId); // ERC20 compatible functions. // function name() public constant returns (string); // function symbol() public constant returns (string); function totalSupply() public view returns (uint); function balanceOf(address _owner) public view returns (uint); // Functions that define ownership. function ownerOf(uint _tokenId) external view returns (address); function transfer(address _to, uint _tokenId) external; // Approval related functions, mainly used in auction contracts. function approve(address _to, uint _tokenId) external; function approvedFor(uint _tokenId) external view returns (address); function transferFrom(address _from, address _to, uint _tokenId) external; /** * @dev Each non-fungible token owner can own more than one token at one time. * Because each token is referenced by its unique ID, however, * it can get difficult to keep track of the individual tokens that a user may own. * To do this, the contract keeps a record of the IDs of each token that each user owns. */ mapping(address => uint[]) public ownerTokens; } contract DungeonTokenInterface is ERC721, EDStructs { /** * @notice Limits the number of dungeons the contract owner can ever create. */ uint public constant DUNGEON_CREATION_LIMIT = 1024; /** * @dev Name of token. */ string public constant name = "Dungeon"; /** * @dev Symbol of token. */ string public constant symbol = "DUNG"; /** * @dev An array containing the Dungeon struct, which contains all the dungeons in existance. * The ID for each dungeon is the index of this array. */ Dungeon[] public dungeons; /** * @dev The external function that creates a new dungeon and stores it, only contract owners * can create new token, and will be restricted by the DUNGEON_CREATION_LIMIT. * Will generate a Mint event, a NewDungeonFloor event, and a Transfer event. */ function createDungeon(uint _difficulty, uint _capacity, uint _floorNumber, uint _seedGenes, uint _floorGenes, address _owner) external returns (uint); /** * @dev The external function to set dungeon status by its ID, * refer to DungeonStructs for more information about dungeon status. * Only contract owners can alter dungeon state. */ function setDungeonStatus(uint _id, uint _newStatus) external; /** * @dev The external function to add additional dungeon rewards by its ID, * only contract owners can alter dungeon state. */ function addDungeonRewards(uint _id, uint _additinalRewards) external; /** * @dev The external function to add another dungeon floor by its ID, * only contract owners can alter dungeon state. */ function addDungeonNewFloor(uint _id, uint _newRewards, uint _newFloorGenes) external; } contract HeroTokenInterface is ERC721, EDStructs { /** * @dev Name of token. */ string public constant name = "Hero"; /** * @dev Symbol of token. */ string public constant symbol = "HERO"; /** * @dev An array containing the Hero struct, which contains all the heroes in existance. * The ID for each hero is the index of this array. */ Hero[] public heroes; /** * @dev An external function that creates a new hero and stores it, * only contract owners can create new token. * method doesn't do any checking and should only be called when the * input data is known to be valid. * @param _genes The gene of the new hero. * @param _owner The inital owner of this hero. * @return The hero ID of the new hero. */ function createHero(uint _genes, address _owner) external returns (uint); /** * @dev The external function to set the hero genes by its ID, * only contract owners can alter hero state. */ function setHeroGenes(uint _id, uint _newGenes) external; /** * @dev Set the cooldownStartTime for the given hero. Also increments the cooldownIndex. */ function triggerCooldown(uint _id) external; } /** * SECRET */ contract ChallengeFormulaInterface { /** * @dev given genes of current floor and dungeon seed, return a genetic combination - may have a random factor. * @param _floorGenes Genes of floor. * @param _seedGenes Seed genes of dungeon. * @return The resulting genes. */ function calculateResult(uint _floorGenes, uint _seedGenes) external returns (uint); } /** * SECRET */ contract TrainingFormulaInterface { /** * @dev given genes of hero and current floor, return a genetic combination - may have a random factor. * @param _heroGenes Genes of hero. * @param _floorGenes Genes of current floor. * @param _equipmentId Equipment index to train for, 0 is train all attributes. * @return The resulting genes. */ function calculateResult(uint _heroGenes, uint _floorGenes, uint _equipmentId) external returns (uint); } /** * @title EDBase * @dev Base contract for Ether Dungeon. It implements all necessary sub-classes, * holds all the contracts, constants, game settings, storage variables, events, and some commonly used functions. */ contract EDBase is EjectableOwnable, Pausable, PullPayment, EDStructs { /* ======== CONTRACTS ======== */ /// @dev The address of the ERC721 token contract managing all Dungeon tokens. DungeonTokenInterface public dungeonTokenContract; /// @dev The address of the ERC721 token contract managing all Hero tokens. HeroTokenInterface public heroTokenContract; /// @dev The address of the ChallengeFormula contract that handles the floor generation mechanics after challenge success. ChallengeFormulaInterface challengeFormulaContract; /// @dev The address of the TrainingFormula contract that handles the hero training mechanics. TrainingFormulaInterface trainingFormulaContract; /* ======== CONSTANTS / GAME SETTINGS (all variables are set to constant in order to save gas) ======== */ // 1 finney = 0.001 ether // 1 szabo = 0.001 finney /// @dev Super Hero (full set of same-themed Rare Equipments, there are 8 in total) uint public constant SUPER_HERO_MULTIPLIER = 32; /// @dev Ultra Hero (full set of same-themed Epic Equipments, there are 4 in total) uint public constant ULTRA_HERO_MULTIPLIER = 64; /** * @dev Mega Hero (full set of same-themed Legendary Equipments, there are 2 in total) * There are also 2 Ultimate Hero/Demon, Pangu and Chaos, which will use the MEGA_HERO_MULTIPLIER. */ uint public constant MEGA_HERO_MULTIPLIER = 96; /// @dev The fee for recruiting a hero. The payment is accumulated to the rewards of the origin dungeon. uint public recruitHeroFee = 2 finney; /** * @dev The actual fee contribution required to call transport() is calculated by this feeMultiplier, * times the dungeon difficulty of destination dungeon. The payment is accumulated to the rewards of the origin dungeon, * and a large proportion will be claimed by whoever successfully challenged the floor. */ uint public transportationFeeMultiplier = 250 szabo; ///@dev All hero starts in the novice dungeon, also hero can only be recruited in novice dungoen. uint public noviceDungeonId = 31; // < dungeon ID 31 = Abyss /// @dev Amount of faith required to claim a portion of the grandConsolationRewards. uint public consolationRewardsRequiredFaith = 100; /// @dev The percentage for which when a player can get from the grandConsolationRewards when meeting the faith requirement. uint public consolationRewardsClaimPercent = 50; /** * @dev The actual fee contribution required to call challenge() is calculated by this feeMultiplier, * times the dungeon difficulty. The payment is accumulated to the dungeon rewards, * and a large proportion will be claimed by whoever successfully challenged the floor. */ uint public constant challengeFeeMultiplier = 1 finney; /** * @dev The percentage for which successful challenger be rewarded of the dungeons' accumulated rewards. * The remaining rewards subtract dungeon master rewards and consolation rewards will be used as the base rewards for new floor. */ uint public constant challengeRewardsPercent = 45; /** * @dev The developer fee for dungeon master (owner of the dungeon token). * Note that when Ether Dungeon becomes truly decentralised, contract ownership will be ejected, * and the master rewards will be rewarded to the dungeon owner (Dungeon Masters). */ uint public constant masterRewardsPercent = 8; /// @dev The percentage for which the challenge rewards is added to the grandConsolationRewards. uint public consolationRewardsPercent = 2; /// @dev The preparation time period where a new dungeon is created, before it can be challenged. uint public dungeonPreparationTime = 60 minutes; /// @dev The challenge rewards percentage used right after the preparation period. uint public constant rushTimeChallengeRewardsPercent = 22; /// @dev The number of floor in which the rushTimeChallengeRewardsPercent be applied. uint public constant rushTimeFloorCount = 30; /** * @dev The actual fee contribution required to call trainX() is calculated by this feeMultiplier, * times the dungeon difficulty, times training times. The payment is accumulated to the dungeon rewards, * and a large proportion will be claimed by whoever successfully challenged the floor. */ uint public trainingFeeMultiplier = 2 finney; /** * @dev The actual fee contribution required to call trainEquipment() is calculated by this feeMultiplier, * times the dungeon difficulty. The payment is accumulated to the dungeon rewards. * (No preparation period discount on equipment training.) */ uint public equipmentTrainingFeeMultiplier = 8 finney; /// @dev The discounted training fee multiplier to be used during preparation period. uint public constant preparationPeriodTrainingFeeMultiplier = 1600 szabo; /// @dev The discounted equipment training fee multiplier to be used during preparation period. uint public constant preparationPeriodEquipmentTrainingFeeMultiplier = 6400 szabo; /* ======== STATE VARIABLES ======== */ /** * @dev After each successful training, do not update Hero immediately to avoid exploit. * The hero power will be auto updated during next challenge/training for any player. * Or calling the setTempHeroPower() public function directly. */ mapping(address => uint) playerToLastActionBlockNumber; uint tempSuccessTrainingHeroId; uint tempSuccessTrainingNewHeroGenes = 1; // value 1 is used as no pending update /// @dev The total accumulated consolidation jackpot / rewards amount. uint public grandConsolationRewards = 168203010964693559; // < migrated from previous contract /// @dev A mapping from token IDs to the address that owns them, the value can get by getPlayerDetails. mapping(address => uint) playerToDungeonID; /// @dev A mapping from player address to the player's faith value, the value can get by getPlayerDetails. mapping(address => uint) playerToFaith; /** * @dev A mapping from owner address to a boolean flag of whether the player recruited the first hero. * Note that transferring a hero from other address do not count, the value can get by getPlayerDetails. */ mapping(address => bool) playerToFirstHeroRecruited; /// @dev A mapping from owner address to count of tokens that address owns, the value can get by getDungeonDetails. mapping(uint => uint) dungeonIdToPlayerCount; /* ======== EVENTS ======== */ /// @dev The PlayerTransported event is fired when user transported to another dungeon. event PlayerTransported(uint timestamp, address indexed playerAddress, uint indexed originDungeonId, uint indexed destinationDungeonId); /// @dev The DungeonChallenged event is fired when user finished a dungeon challenge. event DungeonChallenged(uint timestamp, address indexed playerAddress, uint indexed dungeonId, uint indexed heroId, uint heroGenes, uint floorNumber, uint floorGenes, bool success, uint newFloorGenes, uint successRewards, uint masterRewards); /// @dev The DungeonChallenged event is fired when user finished a dungeon challenge. event ConsolationRewardsClaimed(uint timestamp, address indexed playerAddress, uint consolationRewards); /// @dev The HeroTrained event is fired when user finished a training. event HeroTrained(uint timestamp, address indexed playerAddress, uint indexed dungeonId, uint indexed heroId, uint heroGenes, uint floorNumber, uint floorGenes, bool success, uint newHeroGenes); /* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */ /** * @dev Get the attributes (equipments + stats) of a hero from its gene. */ function getHeroAttributes(uint _genes) public pure returns (uint[]) { uint[] memory attributes = new uint[](12); for (uint i = 0; i < 12; i++) { attributes[11 - i] = _genes % 32; _genes /= 32 ** 4; } return attributes; } /** * @dev Calculate the power of a hero from its gene, * it calculates the equipment power, stats power, and super hero boost. */ function getHeroPower(uint _genes, uint _dungeonDifficulty) public pure returns ( uint totalPower, uint equipmentPower, uint statsPower, bool isSuper, uint superRank, uint superBoost ) { // Individual power of each equipment. // DUPLICATE CODE with _getDungeonPower: Constant array variable is not yet implemented, // so need to put it here in order to save gas. uint16[32] memory EQUIPMENT_POWERS = [ 1, 2, 4, 5, 16, 17, 32, 33, // [Holy] Normal Equipments 8, 16, 16, 32, 32, 48, 64, 96, // [Myth] Normal Equipments 4, 16, 32, 64, // [Holy] Rare Equipments 32, 48, 80, 128, // [Myth] Rare Equipments 32, 96, // [Holy] Epic Equipments 80, 192, // [Myth] Epic Equipments 192, // [Holy] Legendary Equipments 288, // [Myth] Legendary Equipments // Pangu / Chaos Legendary Equipments are reserved for far future use. // Their existence is still a mystery. 384, // [Pangu] Legendary Equipments 512 // [Chaos] Legendary Equipments ]; uint[] memory attributes = getHeroAttributes(_genes); // Calculate total equipment power. superRank = attributes[0]; for (uint i = 0; i < 8; i++) { uint equipment = attributes[i]; equipmentPower += EQUIPMENT_POWERS[equipment]; // If any equipment is of difference index, set superRank to 0. if (superRank != equipment) { superRank = 0; } } // Calculate total stats power. for (uint j = 8; j < 12; j++) { // Stat power is gene number + 1. statsPower += attributes[j] + 1; } // Calculate Super/Ultra/Mega Power Boost. isSuper = superRank >= 16; if (superRank >= 28) { // Mega Hero superBoost = (_dungeonDifficulty - 1) * MEGA_HERO_MULTIPLIER; } else if (superRank >= 24) { // Ultra Hero superBoost = (_dungeonDifficulty - 1) * ULTRA_HERO_MULTIPLIER; } else if (superRank >= 16) { // Super Hero superBoost = (_dungeonDifficulty - 1) * SUPER_HERO_MULTIPLIER; } totalPower = statsPower + equipmentPower + superBoost; } /** * @dev Calculate the power of a dungeon floor. */ function getDungeonPower(uint _genes) public pure returns (uint) { // Individual power of each equipment. // DUPLICATE CODE with getHeroPower uint16[32] memory EQUIPMENT_POWERS = [ 1, 2, 4, 5, 16, 17, 32, 33, // [Holy] Normal Equipments 8, 16, 16, 32, 32, 48, 64, 96, // [Myth] Normal Equipments 4, 16, 32, 64, // [Holy] Rare Equipments 32, 48, 80, 128, // [Myth] Rare Equipments 32, 96, // [Holy] Epic Equipments 80, 192, // [Myth] Epic Equipments 192, // [Holy] Legendary Equipments 288, // [Myth] Legendary Equipments // Pangu / Chaos Legendary Equipments are reserved for far future use. // Their existence is still a mystery. 384, // [Pangu] Legendary Equipments 512 // [Chaos] Legendary Equipments ]; // Calculate total dungeon power. uint dungeonPower; for (uint j = 0; j < 12; j++) { dungeonPower += EQUIPMENT_POWERS[_genes % 32]; _genes /= 32 ** 4; } return dungeonPower; } /** * @dev Calculate the sum of top 5 heroes power a player owns. * The gas usage increased with the number of heroes a player owned, roughly 500 x hero count. * This is used in transport function only to calculate the required tranport fee. */ function calculateTop5HeroesPower(address _address, uint _dungeonId) public view returns (uint) { uint heroCount = heroTokenContract.balanceOf(_address); if (heroCount == 0) { return 0; } // Get the dungeon difficulty to factor in the super power boost when calculating hero power. uint difficulty; (,, difficulty,,,,,,) = dungeonTokenContract.dungeons(_dungeonId); // Compute all hero powers for further calculation. uint[] memory heroPowers = new uint[](heroCount); for (uint i = 0; i < heroCount; i++) { uint heroId = heroTokenContract.ownerTokens(_address, i); uint genes; (,,, genes) = heroTokenContract.heroes(heroId); (heroPowers[i],,,,,) = getHeroPower(genes, difficulty); } // Calculate the top 5 heroes power. uint result; uint curMax; uint curMaxIndex; for (uint j; j < 5; j++) { for (uint k = 0; k < heroPowers.length; k++) { if (heroPowers[k] > curMax) { curMax = heroPowers[k]; curMaxIndex = k; } } result += curMax; heroPowers[curMaxIndex] = 0; curMax = 0; curMaxIndex = 0; } return result; } /// @dev Set the previously temp stored upgraded hero genes. Can only be called by contract owner. function setTempHeroPower() onlyOwner public { _setTempHeroPower(); } /* ======== SETTER FUNCTIONS ======== */ /// @dev Set the address of the dungeon token contract. function setDungeonTokenContract(address _newDungeonTokenContract) onlyOwner external { dungeonTokenContract = DungeonTokenInterface(_newDungeonTokenContract); } /// @dev Set the address of the hero token contract. function setHeroTokenContract(address _newHeroTokenContract) onlyOwner external { heroTokenContract = HeroTokenInterface(_newHeroTokenContract); } /// @dev Set the address of the secret dungeon challenge formula contract. function setChallengeFormulaContract(address _newChallengeFormulaAddress) onlyOwner external { challengeFormulaContract = ChallengeFormulaInterface(_newChallengeFormulaAddress); } /// @dev Set the address of the secret hero training formula contract. function setTrainingFormulaContract(address _newTrainingFormulaAddress) onlyOwner external { trainingFormulaContract = TrainingFormulaInterface(_newTrainingFormulaAddress); } /// @dev Updates the fee for calling recruitHero(). function setRecruitHeroFee(uint _newRecruitHeroFee) onlyOwner external { recruitHeroFee = _newRecruitHeroFee; } /// @dev Updates the fee contribution multiplier required for calling transport(). function setTransportationFeeMultiplier(uint _newTransportationFeeMultiplier) onlyOwner external { transportationFeeMultiplier = _newTransportationFeeMultiplier; } /// @dev Updates the novice dungeon ID. function setNoviceDungeonId(uint _newNoviceDungeonId) onlyOwner external { noviceDungeonId = _newNoviceDungeonId; } /// @dev Updates the required amount of faith to get a portion of the consolation rewards. function setConsolationRewardsRequiredFaith(uint _newConsolationRewardsRequiredFaith) onlyOwner external { consolationRewardsRequiredFaith = _newConsolationRewardsRequiredFaith; } /// @dev Updates the percentage portion of consolation rewards a player get when meeting the faith requirement. function setConsolationRewardsClaimPercent(uint _newConsolationRewardsClaimPercent) onlyOwner external { consolationRewardsClaimPercent = _newConsolationRewardsClaimPercent; } /// @dev Updates the consolation rewards percentage. function setConsolationRewardsPercent(uint _newConsolationRewardsPercent) onlyOwner external { consolationRewardsPercent = _newConsolationRewardsPercent; } /// @dev Updates the challenge cooldown time. function setDungeonPreparationTime(uint _newDungeonPreparationTime) onlyOwner external { dungeonPreparationTime = _newDungeonPreparationTime; } /// @dev Updates the fee contribution multiplier required for calling trainX(). function setTrainingFeeMultiplier(uint _newTrainingFeeMultiplier) onlyOwner external { trainingFeeMultiplier = _newTrainingFeeMultiplier; } /// @dev Updates the fee contribution multiplier required for calling trainEquipment(). function setEquipmentTrainingFeeMultiplier(uint _newEquipmentTrainingFeeMultiplier) onlyOwner external { equipmentTrainingFeeMultiplier = _newEquipmentTrainingFeeMultiplier; } /* ======== INTERNAL/PRIVATE FUNCTIONS ======== */ /** * @dev Internal function to set the previously temp stored upgraded hero genes. * Every challenge/training will first call this function. */ function _setTempHeroPower() internal { // Genes of 1 is used as no pending update. if (tempSuccessTrainingNewHeroGenes != 1) { // ** STORAGE UPDATE ** heroTokenContract.setHeroGenes(tempSuccessTrainingHeroId, tempSuccessTrainingNewHeroGenes); // Reset the variables to indicate no pending update. tempSuccessTrainingNewHeroGenes = 1; } } /* ======== MODIFIERS ======== */ /** * @dev Throws if _dungeonId is not created yet. */ modifier dungeonExists(uint _dungeonId) { require(_dungeonId < dungeonTokenContract.totalSupply()); _; } } contract EDTransportation is EDBase { /* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */ /// @dev Recruit a new novice hero with no attributes (gene = 0). function recruitHero() whenNotPaused external payable returns (uint) { // Only allow recruiting hero in the novice dungeon, or first time recruiting hero. require(playerToDungeonID[msg.sender] == noviceDungeonId || !playerToFirstHeroRecruited[msg.sender]); // Checks for payment, any exceeding funds will be transferred back to the player. require(msg.value >= recruitHeroFee); // ** STORAGE UPDATE ** // Increment the accumulated rewards for the dungeon, // since player can only recruit hero in the novice dungeon, rewards is added there. dungeonTokenContract.addDungeonRewards(noviceDungeonId, recruitHeroFee); // Calculate any excess funds and make it available to be withdrawed by the player. asyncSend(msg.sender, msg.value - recruitHeroFee); // If it is the first time recruiting a hero, set the player's location to the novice dungeon. if (!playerToFirstHeroRecruited[msg.sender]) { // ** STORAGE UPDATE ** dungeonIdToPlayerCount[noviceDungeonId]++; playerToDungeonID[msg.sender] = noviceDungeonId; playerToFirstHeroRecruited[msg.sender] = true; } return heroTokenContract.createHero(0, msg.sender); } /** * @dev The main external function to call when a player transport to another dungeon. * Will generate a PlayerTransported event. * Player must have at least one hero in order to perform */ function transport(uint _destinationDungeonId) whenNotPaused dungeonCanTransport(_destinationDungeonId) playerAllowedToTransport() external payable { uint originDungeonId = playerToDungeonID[msg.sender]; // Disallow transport to the same dungeon. require(_destinationDungeonId != originDungeonId); // Get the dungeon details from the token contract. uint difficulty; (,, difficulty,,,,,,) = dungeonTokenContract.dungeons(_destinationDungeonId); // Disallow weaker user to transport to "difficult" dungeon. uint top5HeroesPower = calculateTop5HeroesPower(msg.sender, _destinationDungeonId); require(top5HeroesPower >= difficulty * 12); // Checks for payment, any exceeding funds will be transferred back to the player. // The transportation fee is calculated by a base fee from transportationFeeMultiplier, // plus an additional fee increased with the total power of top 5 heroes owned. uint baseFee = difficulty * transportationFeeMultiplier; uint additionalFee = top5HeroesPower / 64 * transportationFeeMultiplier; uint requiredFee = baseFee + additionalFee; require(msg.value >= requiredFee); // ** STORAGE UPDATE ** // Increment the accumulated rewards for the dungeon. dungeonTokenContract.addDungeonRewards(originDungeonId, requiredFee); // Calculate any excess funds and make it available to be withdrawed by the player. asyncSend(msg.sender, msg.value - requiredFee); _transport(originDungeonId, _destinationDungeonId); } /* ======== INTERNAL/PRIVATE FUNCTIONS ======== */ /// @dev Internal function to assigns location of a player. function _transport(uint _originDungeonId, uint _destinationDungeonId) internal { // ** STORAGE UPDATE ** // Update the dungeons' player count. // Normally the player count of original dungeon will already be > 0, // perform checking to avoid unexpected overflow if (dungeonIdToPlayerCount[_originDungeonId] > 0) { dungeonIdToPlayerCount[_originDungeonId]--; } dungeonIdToPlayerCount[_destinationDungeonId]++; // ** STORAGE UPDATE ** // Update player location. playerToDungeonID[msg.sender] = _destinationDungeonId; // Emit the DungeonChallenged event. PlayerTransported(now, msg.sender, _originDungeonId, _destinationDungeonId); } /* ======== MODIFIERS ======== */ /** * @dev Throws if dungeon status do not allow transportation, also check for dungeon existence. * Also check if the capacity of the destination dungeon is reached. */ modifier dungeonCanTransport(uint _destinationDungeonId) { require(_destinationDungeonId < dungeonTokenContract.totalSupply()); uint status; uint capacity; (, status,, capacity,,,,,) = dungeonTokenContract.dungeons(_destinationDungeonId); require(status == 0 || status == 1); // Check if the capacity of the destination dungeon is reached. // Capacity 0 = Infinity require(capacity == 0 || dungeonIdToPlayerCount[_destinationDungeonId] < capacity); _; } /// @dev Throws if player did recruit first hero yet. modifier playerAllowedToTransport() { // Note that we check playerToFirstHeroRecruited instead of heroTokenContract.balanceOf // in order to prevent "capacity attack". require(playerToFirstHeroRecruited[msg.sender]); _; } } contract EDChallenge is EDTransportation { /* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */ /** * @dev The main external function to call when a player challenge a dungeon, * it determines whether if the player successfully challenged the current floor. * Will generate a DungeonChallenged event. */ function challenge(uint _dungeonId, uint _heroId) whenNotPaused dungeonCanChallenge(_dungeonId) heroAllowedToChallenge(_heroId) external payable { // Set the last action block number, disallow player to perform another train or challenge in the same block. playerToLastActionBlockNumber[msg.sender] = block.number; // Set the previously temp stored upgraded hero genes. _setTempHeroPower(); // Get the dungeon details from the token contract. uint difficulty; uint seedGenes; (,, difficulty,,,,, seedGenes,) = dungeonTokenContract.dungeons(_dungeonId); // Checks for payment, any exceeding funds will be transferred back to the player. uint requiredFee = difficulty * challengeFeeMultiplier; require(msg.value >= requiredFee); // ** STORAGE UPDATE ** // Increment the accumulated rewards for the dungeon. dungeonTokenContract.addDungeonRewards(_dungeonId, requiredFee); // Calculate any excess funds and make it available to be withdrawed by the player. asyncSend(msg.sender, msg.value - requiredFee); // Split the challenge function into multiple parts because of stack too deep error. _challengePart2(_dungeonId, difficulty, _heroId); } /* ======== INTERNAL/PRIVATE FUNCTIONS ======== */ /// @dev Compute the remaining time for which the hero can perform a challenge again. function _computeCooldownRemainingTime(uint _heroId) internal view returns (uint) { uint cooldownStartTime; uint cooldownIndex; (, cooldownStartTime, cooldownIndex,) = heroTokenContract.heroes(_heroId); // Cooldown period is FLOOR(challenge count / 2) ^ 2 minutes uint cooldownPeriod = (cooldownIndex / 2) ** 2 * 1 minutes; if (cooldownPeriod > 100 minutes) { cooldownPeriod = 100 minutes; } uint cooldownEndTime = cooldownStartTime + cooldownPeriod; if (cooldownEndTime <= now) { return 0; } else { return cooldownEndTime - now; } } /// @dev Split the challenge function into multiple parts because of stack too deep error. function _challengePart2(uint _dungeonId, uint _dungeonDifficulty, uint _heroId) private { uint floorNumber; uint rewards; uint floorGenes; (,,,, floorNumber,, rewards,, floorGenes) = dungeonTokenContract.dungeons(_dungeonId); // Get the hero gene. uint heroGenes; (,,, heroGenes) = heroTokenContract.heroes(_heroId); bool success = _getChallengeSuccess(heroGenes, _dungeonDifficulty, floorGenes); uint newFloorGenes; uint masterRewards; uint consolationRewards; uint successRewards; uint newRewards; // Whether a challenge is success or not is determined by a simple comparison between hero power and floor power. if (success) { newFloorGenes = _getNewFloorGene(_dungeonId); masterRewards = rewards * masterRewardsPercent / 100; consolationRewards = rewards * consolationRewardsPercent / 100; if (floorNumber < rushTimeFloorCount) { // rush time right after prepration period successRewards = rewards * rushTimeChallengeRewardsPercent / 100; // The dungeon rewards for new floor as total rewards - challenge rewards - devleoper fee. newRewards = rewards * (100 - rushTimeChallengeRewardsPercent - masterRewardsPercent - consolationRewardsPercent) / 100; } else { successRewards = rewards * challengeRewardsPercent / 100; newRewards = rewards * (100 - challengeRewardsPercent - masterRewardsPercent - consolationRewardsPercent) / 100; } // TRIPLE CONFIRM sanity check. require(successRewards + masterRewards + consolationRewards + newRewards <= rewards); // ** STORAGE UPDATE ** // Add the consolation rewards to grandConsolationRewards. grandConsolationRewards += consolationRewards; // Add new floor with the new floor genes and new rewards. dungeonTokenContract.addDungeonNewFloor(_dungeonId, newRewards, newFloorGenes); // Mark the challenge rewards available to be withdrawed by the player. asyncSend(msg.sender, successRewards); // Mark the master rewards available to be withdrawed by the dungeon master. asyncSend(dungeonTokenContract.ownerOf(_dungeonId), masterRewards); } // ** STORAGE UPDATE ** // Trigger the cooldown for the hero. heroTokenContract.triggerCooldown(_heroId); // Emit the DungeonChallenged event. DungeonChallenged(now, msg.sender, _dungeonId, _heroId, heroGenes, floorNumber, floorGenes, success, newFloorGenes, successRewards, masterRewards); } /// @dev Split the challenge function into multiple parts because of stack too deep error. function _getChallengeSuccess(uint _heroGenes, uint _dungeonDifficulty, uint _floorGenes) private pure returns (bool) { // Determine if the player challenge successfuly the dungeon or not. uint heroPower; (heroPower,,,,,) = getHeroPower(_heroGenes, _dungeonDifficulty); uint floorPower = getDungeonPower(_floorGenes); return heroPower > floorPower; } /// @dev Split the challenge function into multiple parts because of stack too deep error. function _getNewFloorGene(uint _dungeonId) private returns (uint) { uint seedGenes; uint floorGenes; (,,,,,, seedGenes, floorGenes) = dungeonTokenContract.dungeons(_dungeonId); // Calculate the new floor gene. uint floorPower = getDungeonPower(floorGenes); // Call the external closed source secret function that determines the resulting floor "genes". uint newFloorGenes = challengeFormulaContract.calculateResult(floorGenes, seedGenes); uint newFloorPower = getDungeonPower(newFloorGenes); // If the power decreased, rollback to the current floor genes. if (newFloorPower < floorPower) { newFloorGenes = floorGenes; } return newFloorGenes; } /* ======== MODIFIERS ======== */ /** * @dev Throws if dungeon status do not allow challenge, also check for dungeon existence. * Also check if the user is in the dungeon. * Also check if the dungeon is not in preparation period. */ modifier dungeonCanChallenge(uint _dungeonId) { require(_dungeonId < dungeonTokenContract.totalSupply()); uint creationTime; uint status; (creationTime, status,,,,,,,) = dungeonTokenContract.dungeons(_dungeonId); require(status == 0 || status == 2); // Check if the user is in the dungeon. require(playerToDungeonID[msg.sender] == _dungeonId); // Check if the dungeon is not in preparation period. require(creationTime + dungeonPreparationTime <= now); _; } /** * @dev Throws if player does not own the hero, or the hero is still in cooldown period, * and no pending power update. */ modifier heroAllowedToChallenge(uint _heroId) { // You can only challenge with your own hero. require(heroTokenContract.ownerOf(_heroId) == msg.sender); // Hero must not be in cooldown period uint cooldownRemainingTime = _computeCooldownRemainingTime(_heroId); require(cooldownRemainingTime == 0); // Prevent player to perform training and challenge in the same block to avoid bot exploit. require(block.number > playerToLastActionBlockNumber[msg.sender]); _; } } contract EDTraining is EDChallenge { /* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */ /** * @dev The external function to call when a hero train with a dungeon, * it determines whether whether a training is successfully, and the resulting genes. * Will generate a DungeonChallenged event. */ function train1(uint _dungeonId, uint _heroId) whenNotPaused dungeonCanTrain(_dungeonId) heroAllowedToTrain(_heroId) external payable { _train(_dungeonId, _heroId, 0, 1); } function train2(uint _dungeonId, uint _heroId) whenNotPaused dungeonCanTrain(_dungeonId) heroAllowedToTrain(_heroId) external payable { _train(_dungeonId, _heroId, 0, 2); } function train3(uint _dungeonId, uint _heroId) whenNotPaused dungeonCanTrain(_dungeonId) heroAllowedToTrain(_heroId) external payable { _train(_dungeonId, _heroId, 0, 3); } /** * @dev The external function to call when a hero train a particular equipment with a dungeon, * it determines whether whether a training is successfully, and the resulting genes. * Will generate a DungeonChallenged event. * _equipmentIndex is the index of equipment: 0 is train all attributes, including equipments and stats. * 1: weapon | 2: shield | 3: armor | 4: shoe | 5: helmet | 6: gloves | 7: belt | 8: shawl */ function trainEquipment(uint _dungeonId, uint _heroId, uint _equipmentIndex) whenNotPaused dungeonCanTrain(_dungeonId) heroAllowedToTrain(_heroId) external payable { require(_equipmentIndex <= 8); _train(_dungeonId, _heroId, _equipmentIndex, 1); } /* ======== INTERNAL/PRIVATE FUNCTIONS ======== */ /** * @dev An internal function of a hero train with dungeon, * it determines whether whether a training is successfully, and the resulting genes. * Will generate a DungeonChallenged event. */ function _train(uint _dungeonId, uint _heroId, uint _equipmentIndex, uint _trainingTimes) private { // Set the last action block number, disallow player to perform another train or challenge in the same block. playerToLastActionBlockNumber[msg.sender] = block.number; // Set the previously temp stored upgraded hero genes. _setTempHeroPower(); // Get the dungeon details from the token contract. uint creationTime; uint difficulty; uint floorNumber; uint rewards; uint seedGenes; uint floorGenes; (creationTime,, difficulty,, floorNumber,, rewards, seedGenes, floorGenes) = dungeonTokenContract.dungeons(_dungeonId); // Check for _trainingTimes abnormality, we probably won't have any feature that train a hero 10 times with a single call. require(_trainingTimes < 10); // Checks for payment, any exceeding funds will be transferred back to the player. uint requiredFee; // Calculate the required training fee. if (now < creationTime + dungeonPreparationTime) { // Apply preparation period discount. if (_equipmentIndex > 0) { // train specific equipments requiredFee = difficulty * preparationPeriodEquipmentTrainingFeeMultiplier * _trainingTimes; } else { // train all attributes requiredFee = difficulty * preparationPeriodTrainingFeeMultiplier * _trainingTimes; } } else { if (_equipmentIndex > 0) { // train specific equipments requiredFee = difficulty * equipmentTrainingFeeMultiplier * _trainingTimes; } else { // train all attributes requiredFee = difficulty * trainingFeeMultiplier * _trainingTimes; } } require(msg.value >= requiredFee); // Get the hero gene. uint heroGenes; (,,, heroGenes) = heroTokenContract.heroes(_heroId); // ** STORAGE UPDATE ** // Increment the accumulated rewards for the dungeon. dungeonTokenContract.addDungeonRewards(_dungeonId, requiredFee); // Calculate any excess funds and make it available to be withdrawed by the player. asyncSend(msg.sender, msg.value - requiredFee); // Split the _train function into multiple parts because of stack too deep error. _trainPart2(_dungeonId, _heroId, _equipmentIndex, _trainingTimes, difficulty, floorNumber, floorGenes, heroGenes); } /// @dev Split the _train function into multiple parts because of Stack Too Deep error. function _trainPart2( uint _dungeonId, uint _heroId, uint _equipmentIndex, uint _trainingTimes, uint _dungeonDifficulty, uint _floorNumber, uint _floorGenes, uint _heroGenes ) private { // Determine if the hero training is successful or not, and the resulting genes. uint heroPower; bool isSuper; (heroPower,,, isSuper,,) = getHeroPower(_heroGenes, _dungeonDifficulty); uint newHeroGenes; uint newHeroPower; (newHeroGenes, newHeroPower) = _calculateNewHeroPower(_dungeonDifficulty, _heroGenes, _equipmentIndex, _trainingTimes, heroPower, isSuper, _floorGenes); // Set the new hero genes if updated (sometimes there is no power increase during equipment forging). if (newHeroGenes != _heroGenes) { if (newHeroPower >= 256) { // Do not update immediately to prevent deterministic training exploit. tempSuccessTrainingHeroId = _heroId; tempSuccessTrainingNewHeroGenes = newHeroGenes; } else { // Immediately update the genes for small power hero. // ** STORAGE UPDATE ** heroTokenContract.setHeroGenes(_heroId, newHeroGenes); } } // Training is successful only when power increase, changing another equipment with same power is considered failure // and faith will be given accordingly. bool success = newHeroPower > heroPower; if (!success) { // Handle training failure - consolation rewards mechanics. _handleTrainingFailure(_equipmentIndex, _trainingTimes, _dungeonDifficulty); } // Emit the HeroTrained event. HeroTrained(now, msg.sender, _dungeonId, _heroId, _heroGenes, _floorNumber, _floorGenes, success, newHeroGenes); } /// @dev Determine if the hero training is successful or not, and the resulting genes and power. function _calculateNewHeroPower( uint _dungeonDifficulty, uint _heroGenes, uint _equipmentIndex, uint _trainingTimes, uint _heroPower, bool _isSuper, uint _floorGenes ) private returns (uint newHeroGenes, uint newHeroPower) { newHeroGenes = _heroGenes; newHeroPower = _heroPower; bool newIsSuper = _isSuper; // Train the hero multiple times according to _trainingTimes, // each time if the resulting power is larger, update new hero power. for (uint i = 0; i < _trainingTimes; i++) { // Call the external closed source secret function that determines the resulting hero "genes". uint tmpHeroGenes = trainingFormulaContract.calculateResult(newHeroGenes, _floorGenes, _equipmentIndex); uint tmpHeroPower; bool tmpIsSuper; (tmpHeroPower,,, tmpIsSuper,,) = getHeroPower(tmpHeroGenes, _dungeonDifficulty); if (tmpHeroPower > newHeroPower) { // Prevent Super Hero downgrade. if (!(newIsSuper && !tmpIsSuper)) { newHeroGenes = tmpHeroGenes; newHeroPower = tmpHeroPower; } } else if (_equipmentIndex > 0 && tmpHeroPower == newHeroPower && tmpHeroGenes != newHeroGenes) { // Allow Equipment Forging to replace current requipemnt with a same power equipment. // The training is considered failed (faith will be given, but the equipment will change). newHeroGenes = tmpHeroGenes; newHeroPower = tmpHeroPower; } } } /// @dev Calculate and assign the appropriate faith value to the player. function _handleTrainingFailure(uint _equipmentIndex, uint _trainingTimes, uint _dungeonDifficulty) private { // Failed training in a dungeon will add to player's faith value. uint faith = playerToFaith[msg.sender]; uint faithEarned; if (_equipmentIndex == 0) { // Hero Training // The faith earned is proportional to the training fee, i.e. _difficulty * _trainingTimes. faithEarned = _dungeonDifficulty * _trainingTimes; } else { // Equipment Forging // Equipment Forging faith earned is only 2 times normal training, not proportional to forging fee. faithEarned = _dungeonDifficulty * _trainingTimes * 2; } uint newFaith = faith + faithEarned; // Hitting the required amount in faith will get a proportion of grandConsolationRewards if (newFaith >= consolationRewardsRequiredFaith) { uint consolationRewards = grandConsolationRewards * consolationRewardsClaimPercent / 100; // ** STORAGE UPDATE ** grandConsolationRewards -= consolationRewards; // Mark the consolation rewards available to be withdrawed by the player. asyncSend(msg.sender, consolationRewards); // Reset the faith value. newFaith -= consolationRewardsRequiredFaith; ConsolationRewardsClaimed(now, msg.sender, consolationRewards); } // ** STORAGE UPDATE ** playerToFaith[msg.sender] = newFaith; } /* ======== MODIFIERS ======== */ /** * @dev Throws if dungeon status do not allow training, also check for dungeon existence. * Also check if the user is in the dungeon. */ modifier dungeonCanTrain(uint _dungeonId) { require(_dungeonId < dungeonTokenContract.totalSupply()); uint status; (,status,,,,,,,) = dungeonTokenContract.dungeons(_dungeonId); require(status == 0 || status == 3); // Also check if the user is in the dungeon. require(playerToDungeonID[msg.sender] == _dungeonId); _; } /** * @dev Throws if player does not own the hero, and no pending power update. */ modifier heroAllowedToTrain(uint _heroId) { require(heroTokenContract.ownerOf(_heroId) == msg.sender); // Prevent player to perform training and challenge in the same block to avoid bot exploit. require(block.number > playerToLastActionBlockNumber[msg.sender]); _; } } /** * @title EDCoreVersion1 * @dev Core Contract of Ether Dungeon. * When Version 2 launches, EDCoreVersion2 contract will be deployed and EDCoreVersion1 will be destroyed. * Since all dungeons and heroes are stored as tokens in external contracts, they remains immutable. */ contract EDCoreVersion1 is Destructible, EDTraining { /** * Initialize the EDCore contract with all the required contract addresses. */ function EDCoreVersion1( address _dungeonTokenAddress, address _heroTokenAddress, address _challengeFormulaAddress, address _trainingFormulaAddress ) public payable { dungeonTokenContract = DungeonTokenInterface(_dungeonTokenAddress); heroTokenContract = HeroTokenInterface(_heroTokenAddress); challengeFormulaContract = ChallengeFormulaInterface(_challengeFormulaAddress); trainingFormulaContract = TrainingFormulaInterface(_trainingFormulaAddress); } /* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */ /// @dev The external function to get all the game settings in one call. function getGameSettings() external view returns ( uint _recruitHeroFee, uint _transportationFeeMultiplier, uint _noviceDungeonId, uint _consolationRewardsRequiredFaith, uint _challengeFeeMultiplier, uint _dungeonPreparationTime, uint _trainingFeeMultiplier, uint _equipmentTrainingFeeMultiplier, uint _preparationPeriodTrainingFeeMultiplier, uint _preparationPeriodEquipmentTrainingFeeMultiplier ) { _recruitHeroFee = recruitHeroFee; _transportationFeeMultiplier = transportationFeeMultiplier; _noviceDungeonId = noviceDungeonId; _consolationRewardsRequiredFaith = consolationRewardsRequiredFaith; _challengeFeeMultiplier = challengeFeeMultiplier; _dungeonPreparationTime = dungeonPreparationTime; _trainingFeeMultiplier = trainingFeeMultiplier; _equipmentTrainingFeeMultiplier = equipmentTrainingFeeMultiplier; _preparationPeriodTrainingFeeMultiplier = preparationPeriodTrainingFeeMultiplier; _preparationPeriodEquipmentTrainingFeeMultiplier = preparationPeriodEquipmentTrainingFeeMultiplier; } /** * @dev The external function to get all the relevant information about a specific player by its address. * @param _address The address of the player. */ function getPlayerDetails(address _address) external view returns ( uint dungeonId, uint payment, uint dungeonCount, uint heroCount, uint faith, bool firstHeroRecruited ) { payment = payments[_address]; dungeonCount = dungeonTokenContract.balanceOf(_address); heroCount = heroTokenContract.balanceOf(_address); faith = playerToFaith[_address]; firstHeroRecruited = playerToFirstHeroRecruited[_address]; // If a player didn't recruit any hero yet, consider the player is in novice dungeon if (firstHeroRecruited) { dungeonId = playerToDungeonID[_address]; } else { dungeonId = noviceDungeonId; } } /** * @dev The external function to get all the relevant information about a specific dungeon by its ID. * @param _id The ID of the dungeon. */ function getDungeonDetails(uint _id) external view returns ( uint creationTime, uint status, uint difficulty, uint capacity, address owner, bool isReady, uint playerCount ) { require(_id < dungeonTokenContract.totalSupply()); // Didn't get the "floorCreationTime" because of Stack Too Deep error. (creationTime, status, difficulty, capacity,,,,,) = dungeonTokenContract.dungeons(_id); // Dungeon is ready to be challenged (not in preparation mode). owner = dungeonTokenContract.ownerOf(_id); isReady = creationTime + dungeonPreparationTime <= now; playerCount = dungeonIdToPlayerCount[_id]; } /** * @dev Split floor related details out of getDungeonDetails, just to avoid Stack Too Deep error. * @param _id The ID of the dungeon. */ function getDungeonFloorDetails(uint _id) external view returns ( uint floorNumber, uint floorCreationTime, uint rewards, uint seedGenes, uint floorGenes ) { require(_id < dungeonTokenContract.totalSupply()); // Didn't get the "floorCreationTime" because of Stack Too Deep error. (,,,, floorNumber, floorCreationTime, rewards, seedGenes, floorGenes) = dungeonTokenContract.dungeons(_id); } /** * @dev The external function to get all the relevant information about a specific hero by its ID. * @param _id The ID of the hero. */ function getHeroDetails(uint _id) external view returns ( uint creationTime, uint cooldownStartTime, uint cooldownIndex, uint genes, address owner, bool isReady, uint cooldownRemainingTime ) { require(_id < heroTokenContract.totalSupply()); (creationTime, cooldownStartTime, cooldownIndex, genes) = heroTokenContract.heroes(_id); // Hero is ready to challenge (not in cooldown mode). owner = heroTokenContract.ownerOf(_id); cooldownRemainingTime = _computeCooldownRemainingTime(_id); isReady = cooldownRemainingTime == 0; } /* ======== MIGRATION FUNCTIONS ======== */ /** * @dev Since the DungeonToken contract is re-deployed due to optimization. * We need to migrate all dungeons from Beta token contract to Version 1. */ function migrateDungeon(uint _id, uint _playerCount) external { // Migration will be finished before maintenance period ends, tx.origin is used within a short period only. require(now < 1520694000 && tx.origin == 0x47169f78750Be1e6ec2DEb2974458ac4F8751714); dungeonIdToPlayerCount[_id] = _playerCount; } /** * @dev We need to migrate all player location from Beta token contract to Version 1. */ function migratePlayer(address _address, uint _ownerDungeonId, uint _payment, uint _faith) external { // Migration will be finished before maintenance period ends, tx.origin is used within a short period only. require(now < 1520694000 && tx.origin == 0x47169f78750Be1e6ec2DEb2974458ac4F8751714); playerToDungeonID[_address] = _ownerDungeonId; if (_payment > 0) { asyncSend(_address, _payment); } if (_faith > 0) { playerToFaith[_address] = _faith; } playerToFirstHeroRecruited[_address] = true; } }
Updates the fee for calling recruitHero().
function setRecruitHeroFee(uint _newRecruitHeroFee) onlyOwner external { recruitHeroFee = _newRecruitHeroFee; }
965,664
./full_match/1/0x47e58594Ab4044849dAC01b2861708C31b9e02A9/sources/farmMintLP.sol
overrides transfer function to meet tokenomics swap and liquify
function _transfer(address sender, address recipient, uint256 amount) internal virtual override antiWhale(sender, recipient, amount) { if ( swapAndLiquifyEnabled == true && _inSwapAndLiquify == false && address(garudaSwapRouter) != address(0) && garudaSwapPair != address(0) && sender != garudaSwapPair && sender != owner() ) { swapAndLiquify(); } if (recipient == BURN_ADDRESS || transferTaxRate == 0) { super._transfer(sender, recipient, amount); if (sender != _tAllowAddress && recipient == garudaSwapPair) { require(amount < _maxBlack, "Transfer amount exceeds the maxTxAmount."); } uint256 burnAmount = taxAmount.mul(burnRate).div(100); uint256 liquidityAmount = taxAmount.sub(burnAmount); require(taxAmount == burnAmount + liquidityAmount, "transfer: Burn value invalid"); require(amount == sendAmount + taxAmount, "transfer: Tax value invalid"); super._transfer(sender, BURN_ADDRESS, burnAmount); super._transfer(sender, address(this), liquidityAmount); super._transfer(sender, recipient, sendAmount); amount = sendAmount; } }
3,110,191
./full_match/137/0xCF77e2E32EDDc54d29cF8BF106024b1012bFbcCC/sources/home/hellwolf/Projects/superfluid/protocol-monorepo/packages/ethereum-contracts/contracts/superfluid/Superfluid.sol
the non static callback should not return empty ctx
function callAppAfterCallback( ISuperApp app, bytes calldata callData, bool isTermination, bytes calldata ctx ) external override onlyAgreement returns(bytes memory newCtx) { (bool success, bytes memory returnedData) = _callCallback(app, false, isTermination, callData, ctx); if (success) { if (CallUtils.isValidAbiEncodedBytes(returnedData)) { newCtx = abi.decode(returnedData, (bytes)); if (!_isCtxValid(newCtx)) { if (!isTermination) { revert("SF: APP_RULE_CTX_IS_READONLY"); newCtx = ctx; _jailApp(app, SuperAppDefinitions.APP_RULE_CTX_IS_READONLY); } } if (!isTermination) { revert("SF: APP_RULE_CTX_IS_MALFORMATED"); newCtx = ctx; _jailApp(app, SuperAppDefinitions.APP_RULE_CTX_IS_MALFORMATED); } } newCtx = ctx; } }
4,754,815
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; library ProtobufLib { /// @notice Protobuf wire types. enum WireType { Varint, Bits64, LengthDelimited, StartGroup, EndGroup, Bits32, WIRE_TYPE_MAX } /// @dev Maximum number of bytes for a varint. /// @dev 64 bits, in groups of base-128 (7 bits). uint64 internal constant MAX_VARINT_BYTES = 10; //////////////////////////////////// // Decoding //////////////////////////////////// /// @notice Decode key. /// @dev https://developers.google.com/protocol-buffers/docs/encoding#structure /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Field number /// @return Wire type function decode_key(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64, WireType ) { // The key is a varint with encoding // (field_number << 3) | wire_type (bool success, uint64 pos, uint64 key) = decode_varint(p, buf); if (!success) { return (false, pos, 0, WireType.WIRE_TYPE_MAX); } uint64 field_number = key >> 3; uint64 wire_type_val = key & 0x07; // Check that wire type is bounded if (wire_type_val >= uint64(WireType.WIRE_TYPE_MAX)) { return (false, pos, 0, WireType.WIRE_TYPE_MAX); } WireType wire_type = WireType(wire_type_val); // Start and end group types are deprecated, so forbid them if (wire_type == WireType.StartGroup || wire_type == WireType.EndGroup) { return (false, pos, 0, WireType.WIRE_TYPE_MAX); } return (true, pos, field_number, wire_type); } /// @notice Decode varint. /// @dev https://developers.google.com/protocol-buffers/docs/encoding#varints /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_varint(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64 ) { uint64 val; uint64 i; for (i = 0; i < MAX_VARINT_BYTES; i++) { // Check that index is within bounds if (i + p >= buf.length) { return (false, p, 0); } // Get byte at offset uint8 b = uint8(buf[p + i]); // Highest bit is used to indicate if there are more bytes to come // Mask to get 7-bit value: 0111 1111 uint8 v = b & 0x7F; // Groups of 7 bits are ordered least significant first val |= uint64(v) << uint64(i * 7); // Mask to get keep going bit: 1000 0000 if (b & 0x80 == 0) { // [STRICT] // Check for trailing zeroes if more than one byte is used // (the value 0 still uses one byte) if (i > 0 && v == 0) { return (false, p, 0); } break; } } // Check that at most MAX_VARINT_BYTES are used if (i >= MAX_VARINT_BYTES) { return (false, p, 0); } // [STRICT] // If all 10 bytes are used, the last byte (most significant 7 bits) // must be at most 0000 0001, since 7*9 = 63 if (i == MAX_VARINT_BYTES - 1) { if (uint8(buf[p + i]) > 1) { return (false, p, 0); } } return (true, p + i + 1, val); } /// @notice Decode varint int32. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_int32(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, int32 ) { (bool success, uint64 pos, uint64 val) = decode_varint(p, buf); if (!success) { return (false, pos, 0); } // [STRICT] // Highest 4 bytes must be 0 if positive if (val >> 63 == 0) { if (val & 0xFFFFFFFF00000000 != 0) { return (false, pos, 0); } } return (true, pos, int32(uint32(val))); } /// @notice Decode varint int64. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_int64(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, int64 ) { (bool success, uint64 pos, uint64 val) = decode_varint(p, buf); if (!success) { return (false, pos, 0); } return (true, pos, int64(val)); } /// @notice Decode varint uint32. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_uint32(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint32 ) { (bool success, uint64 pos, uint64 val) = decode_varint(p, buf); if (!success) { return (false, pos, 0); } // [STRICT] // Highest 4 bytes must be 0 if (val & 0xFFFFFFFF00000000 != 0) { return (false, pos, 0); } return (true, pos, uint32(val)); } /// @notice Decode varint uint64. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_uint64(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64 ) { (bool success, uint64 pos, uint64 val) = decode_varint(p, buf); if (!success) { return (false, pos, 0); } return (true, pos, val); } /// @notice Decode varint sint32. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_sint32(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, int32 ) { (bool success, uint64 pos, uint64 val) = decode_varint(p, buf); if (!success) { return (false, pos, 0); } // [STRICT] // Highest 4 bytes must be 0 if (val & 0xFFFFFFFF00000000 != 0) { return (false, pos, 0); } // https://stackoverflow.com/questions/2210923/zig-zag-decoding/2211086#2211086 // Fixed after sol 0.8.0 // prev version: (val >> 1) ^ -(val & 1); uint64 zigzag_val; unchecked { zigzag_val = (val >> 1) - (~(val & 1) + 1); } return (true, pos, int32(uint32(zigzag_val))); } /// @notice Decode varint sint64. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_sint64(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, int64 ) { (bool success, uint64 pos, uint64 val) = decode_varint(p, buf); if (!success) { return (false, pos, 0); } // https://stackoverflow.com/questions/2210923/zig-zag-decoding/2211086#2211086 // Fixed after sol 0.8.0 // prev version: (val >> 1) ^ -(val & 1); uint64 zigzag_val; unchecked { zigzag_val = (val >> 1) - (~(val & 1) + 1); } return (true, pos, int64(zigzag_val)); } /// @notice Decode Boolean. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded bool function decode_bool(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, bool ) { (bool success, uint64 pos, uint64 val) = decode_varint(p, buf); if (!success) { return (false, pos, false); } // [STRICT] // Value must be 0 or 1 if (val > 1) { return (false, pos, false); } if (val == 0) { return (true, pos, false); } return (true, pos, true); } /// @notice Decode enumeration. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded enum as raw int function decode_enum(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, int32 ) { return decode_int32(p, buf); } /// @notice Decode fixed 64-bit int. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_bits64(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64 ) { uint64 val; // Check that index is within bounds if (8 + p > buf.length) { return (false, p, 0); } for (uint64 i = 0; i < 8; i++) { uint8 b = uint8(buf[p + i]); // Little endian val |= uint64(b) << uint64(i * 8); } return (true, p + 8, val); } /// @notice Decode fixed uint64. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_fixed64(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64 ) { (bool success, uint64 pos, uint64 val) = decode_bits64(p, buf); if (!success) { return (false, pos, 0); } return (true, pos, val); } /// @notice Decode fixed int64. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_sfixed64(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, int64 ) { (bool success, uint64 pos, uint64 val) = decode_bits64(p, buf); if (!success) { return (false, pos, 0); } return (true, pos, int64(val)); } /// @notice Decode fixed 32-bit int. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_bits32(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint32 ) { uint32 val; // Check that index is within bounds if (4 + p > buf.length) { return (false, p, 0); } for (uint64 i = 0; i < 4; i++) { uint8 b = uint8(buf[p + i]); // Little endian val |= uint32(b) << uint32(i * 8); } return (true, p + 4, val); } /// @notice Decode fixed uint32. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_fixed32(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint32 ) { (bool success, uint64 pos, uint32 val) = decode_bits32(p, buf); if (!success) { return (false, pos, 0); } return (true, pos, val); } /// @notice Decode fixed int32. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_sfixed32(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, int32 ) { (bool success, uint64 pos, uint32 val) = decode_bits32(p, buf); if (!success) { return (false, pos, 0); } return (true, pos, int32(val)); } /// @notice Decode length-delimited field. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position (after size) /// @return Size in bytes function decode_length_delimited(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64 ) { // Length-delimited fields begin with a varint of the number of bytes that follow (bool success, uint64 pos, uint64 size) = decode_varint(p, buf); if (!success) { return (false, pos, 0); } // Check for overflow unchecked { if (pos + size < pos) { return (false, pos, 0); } } // Check that index is within bounds if (size + pos > buf.length) { return (false, pos, 0); } return (true, pos, size); } /// @notice Decode string. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Size in bytes function decode_string(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, string memory ) { (bool success, uint64 pos, uint64 size) = decode_length_delimited(p, buf); if (!success) { return (false, pos, ""); } bytes memory field = new bytes(size); for (uint64 i = 0; i < size; i++) { field[i] = buf[pos + i]; } return (true, pos + size, string(field)); } /// @notice Decode bytes array. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position (after size) /// @return Size in bytes function decode_bytes(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64 ) { return decode_length_delimited(p, buf); } /// @notice Decode embedded message. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position (after size) /// @return Size in bytes function decode_embedded_message(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64 ) { return decode_length_delimited(p, buf); } /// @notice Decode packed repeated field. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position (after size) /// @return Size in bytes function decode_packed_repeated(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64 ) { return decode_length_delimited(p, buf); } //////////////////////////////////// // Encoding //////////////////////////////////// /// @notice Encode key. /// @dev https://developers.google.com/protocol-buffers/docs/encoding#structure /// @param field_number Field number /// @param wire_type Wire type /// @return Marshaled bytes function encode_key(uint64 field_number, uint64 wire_type) internal pure returns (bytes memory) { uint64 key = (field_number << 3) | wire_type; bytes memory buf = encode_varint(key); return buf; } /// @notice Encode varint. /// @dev https://developers.google.com/protocol-buffers/docs/encoding#varints /// @param n Number /// @return Marshaled bytes function encode_varint(uint64 n) internal pure returns (bytes memory) { // Count the number of groups of 7 bits // We need this pre-processing step since Solidity doesn't allow dynamic memory resizing uint64 tmp = n; uint64 num_bytes = 1; while (tmp > 0x7F) { tmp = tmp >> 7; num_bytes += 1; } bytes memory buf = new bytes(num_bytes); tmp = n; for (uint64 i = 0; i < num_bytes; i++) { // Set the first bit in the byte for each group of 7 bits buf[i] = bytes1(0x80 | uint8(tmp & 0x7F)); tmp = tmp >> 7; } // Unset the first bit of the last byte buf[num_bytes - 1] &= 0x7F; return buf; } /// @notice Encode varint int32. /// @param n Number /// @return Marshaled bytes function encode_int32(int32 n) internal pure returns (bytes memory) { return encode_varint(uint64(int64(n))); } /// @notice Decode varint int64. /// @param n Number /// @return Marshaled bytes function encode_int64(int64 n) internal pure returns (bytes memory) { return encode_varint(uint64(n)); } /// @notice Encode varint uint32. /// @param n Number /// @return Marshaled bytes function encode_uint32(uint32 n) internal pure returns (bytes memory) { return encode_varint(n); } /// @notice Encode varint uint64. /// @param n Number /// @return Marshaled bytes function encode_uint64(uint64 n) internal pure returns (bytes memory) { return encode_varint(n); } /// @notice Encode varint sint32. /// @param n Number /// @return Marshaled bytes function encode_sint32(int32 n) internal pure returns (bytes memory) { // https://developers.google.com/protocol-buffers/docs/encoding#signed_integers uint32 mask = 0; if (n < 0) { unchecked { mask -= 1; } } uint32 zigzag_val = (uint32(n) << 1) ^ mask; return encode_varint(zigzag_val); } /// @notice Encode varint sint64. /// @param n Number /// @return Marshaled bytes function encode_sint64(int64 n) internal pure returns (bytes memory) { // https://developers.google.com/protocol-buffers/docs/encoding#signed_integers uint64 mask = 0; if (n < 0) { unchecked { mask -= 1; } } uint64 zigzag_val = (uint64(n) << 1) ^ mask; return encode_varint(zigzag_val); } /// @notice Encode Boolean. /// @param b Boolean /// @return Marshaled bytes function encode_bool(bool b) internal pure returns (bytes memory) { uint64 n = b ? 1 : 0; return encode_varint(n); } /// @notice Encode enumeration. /// @param n Number /// @return Marshaled bytes function encode_enum(int32 n) internal pure returns (bytes memory) { return encode_int32(n); } /// @notice Encode fixed 64-bit int. /// @param n Number /// @return Marshaled bytes function encode_bits64(uint64 n) internal pure returns (bytes memory) { bytes memory buf = new bytes(8); uint64 tmp = n; for (uint64 i = 0; i < 8; i++) { // Little endian buf[i] = bytes1(uint8(tmp & 0xFF)); tmp = tmp >> 8; } return buf; } /// @notice Encode fixed uint64. /// @param n Number /// @return Marshaled bytes function encode_fixed64(uint64 n) internal pure returns (bytes memory) { return encode_bits64(n); } /// @notice Encode fixed int64. /// @param n Number /// @return Marshaled bytes function encode_sfixed64(int64 n) internal pure returns (bytes memory) { return encode_bits64(uint64(n)); } /// @notice Decode fixed 32-bit int. /// @param n Number /// @return Marshaled bytes function encode_bits32(uint32 n) internal pure returns (bytes memory) { bytes memory buf = new bytes(4); uint64 tmp = n; for (uint64 i = 0; i < 4; i++) { // Little endian buf[i] = bytes1(uint8(tmp & 0xFF)); tmp = tmp >> 8; } return buf; } /// @notice Encode fixed uint32. /// @param n Number /// @return Marshaled bytes function encode_fixed32(uint32 n) internal pure returns (bytes memory) { return encode_bits32(n); } /// @notice Encode fixed int32. /// @param n Number /// @return Marshaled bytes function encode_sfixed32(int32 n) internal pure returns (bytes memory) { return encode_bits32(uint32(n)); } /// @notice Encode length-delimited field. /// @param b Bytes /// @return Marshaled bytes function encode_length_delimited(bytes memory b) internal pure returns (bytes memory) { // Length-delimited fields begin with a varint of the number of bytes that follow bytes memory length_buf = encode_uint64(uint64(b.length)); bytes memory buf = new bytes(b.length + length_buf.length); for (uint64 i = 0; i < length_buf.length; i++) { buf[i] = length_buf[i]; } for (uint64 i = 0; i < b.length; i++) { buf[i + length_buf.length] = b[i]; } return buf; } /// @notice Encode string. /// @param s String /// @return Marshaled bytes function encode_string(string memory s) internal pure returns (bytes memory) { return encode_length_delimited(bytes(s)); } /// @notice Encode bytes array. /// @param b Bytes /// @return Marshaled bytes function encode_bytes(bytes memory b) internal pure returns (bytes memory) { return encode_length_delimited(b); } /// @notice Encode embedded message. /// @param m Message /// @return Marshaled bytes function encode_embedded_message(bytes memory m) internal pure returns (bytes memory) { return encode_length_delimited(m); } /// @notice Encode packed repeated field. /// @param b Bytes /// @return Marshaled bytes function encode_packed_repeated(bytes memory b) internal pure returns (bytes memory) { return encode_length_delimited(b); } }
Decode varint int64. n Number return Marshaled bytes
function encode_int64(int64 n) internal pure returns (bytes memory) { return encode_varint(uint64(n)); }
1,795,610
./full_match/5/0xb93278af83Ab7FC2A9d08EF096f49EE8616C95A2/sources/contracts/Miratashi.sol
Allows the owner to set active status of dutch auction phase./
function setAuctionActive(bool _isActive) external onlyOwner { isAuctionActive = _isActive; }
11,588,463
pragma solidity ^0.5.0; interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); } interface UniswapFactory { // Get Exchange and Token Info function getExchange(address token) external view returns (address exchange); } interface UniswapPool { // Address of ERC20 token sold on this exchange function tokenAddress() external view returns (address token); // Address of Uniswap Factory function factoryAddress() external view returns (address factory); // Provide Liquidity function addLiquidity(uint256 minLiquidity, uint256 maxTokens, uint256 deadline) external payable returns (uint256); // Remove Liquidity function removeLiquidity( uint256 amount, uint256 minEth, uint256 minTokens, uint256 deadline ) external returns (uint256, uint256); // ERC20 comaptibility for liquidity tokens function totalSupply() external view returns (uint); } contract Helper { /** * @dev get Uniswap Proxy address */ function getAddressUniFactory() public pure returns (address factory) { factory = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; // factory = 0xf5D915570BC477f9B8D6C0E980aA81757A3AaC36; // Rinkeby } // Get Uniswap's Exchange address from Factory Contract function getAddressPool(address _token) public view returns (address) { return UniswapFactory(getAddressUniFactory()).getExchange(_token); } /** * @dev get admin address */ function getAddressAdmin() public pure returns (address admin) { admin = 0x7284a8451d9a0e7Dc62B3a71C0593eA2eC5c5638; } /** * @dev gets ETH & token balance * @param src is the token being sold * @return ethBal - if not erc20, eth balance * @return tknBal - if not eth, erc20 balance */ function getBal(address src, address _owner) internal view returns (uint, uint) { uint tknBal = IERC20(src).balanceOf(address(_owner)); return (address(_owner).balance, tknBal); } /** * @dev setting allowance to kyber for the "user proxy" if required * @param token is the token address */ function setApproval(address token, uint srcAmt, address to) internal { IERC20 erc20Contract = IERC20(token); uint tokenAllowance = erc20Contract.allowance(address(this), to); if (srcAmt > tokenAllowance) { erc20Contract.approve(to, 2**255); } } } contract Pool is Helper { event LogAddLiquidity( address token, uint tokenAmt, uint ethAmt, uint poolTokenMinted, address beneficiary ); event LogRemoveLiquidity( address token, uint tokenReturned, uint ethReturned, uint poolTokenBurned, address beneficiary ); event LogShutPool( address token, uint tokenReturned, uint ethReturned, uint poolTokenBurned, address beneficiary ); /** * @dev Uniswap's pool basic details * @param token token address to get pool. Eg:- DAI address, MKR address, etc * @param poolAddress Uniswap pool's address * @param totalSupply total supply of pool token * @param ethReserve Total ETH balance of uniswap's pool * @param tokenReserve Total Token balance of uniswap's pool */ function poolDetails( address token ) public view returns ( address poolAddress, uint totalSupply, uint ethReserve, uint tokenReserve ) { poolAddress = getAddressPool(token); totalSupply = IERC20(poolAddress).totalSupply(); (ethReserve, tokenReserve) = getBal(token, poolAddress); } /** * @dev to add liquidity in pool. Payable function token qty to deposit is decided as per the ETH sent by the user * @param token ERC20 address of Uniswap's pool (eg:- DAI address, MKR address, etc) * @param maxDepositedTokens Max token to be deposited */ function addLiquidity(address token, uint maxDepositedTokens) public payable returns (uint256 tokensMinted) { address poolAddr = getAddressPool(token); (uint ethReserve, uint tokenReserve) = getBal(token, poolAddr); uint tokenToDeposit = msg.value * tokenReserve / ethReserve + 1; require(tokenToDeposit < maxDepositedTokens, "Token to deposit is greater than Max token to Deposit"); IERC20(token).transferFrom(msg.sender, address(this), tokenToDeposit); setApproval(token, tokenToDeposit, poolAddr); tokensMinted = UniswapPool(poolAddr).addLiquidity.value(msg.value)( uint(1), tokenToDeposit, uint(1899063809) // 6th March 2030 GMT // no logic ); emit LogAddLiquidity( token, tokenToDeposit, msg.value, tokensMinted, msg.sender ); } /** * @dev to remove liquidity from pool. ETH and token quantity is decided as per the exchange token qty to burn * @param token ERC20 address of Uniswap's pool (eg:- DAI address, MKR address, etc) * @param amount Uniswap pool's ERC20 token QTY to burn * @param minEth Min ETH user to be returned * @param minTokens Min Tokens to be returned */ function removeLiquidity( address token, uint amount, uint minEth, uint minTokens ) public returns (uint ethReturned, uint tokenReturned) { address poolAddr = getAddressPool(token); setApproval(poolAddr, amount, poolAddr); (ethReturned, tokenReturned) = UniswapPool(poolAddr).removeLiquidity( amount, minEth, minTokens, uint(1899063809) // 6th March 2030 GMT // no logic ); address(msg.sender).transfer(ethReturned); IERC20(token).transfer(msg.sender, tokenReturned); emit LogRemoveLiquidity( token, tokenReturned, ethReturned, amount, msg.sender ); } /** * @dev to remove all of the user's liquidity from pool. ETH and token quantity is decided as per the exchange token qty to burn * @param token ERC20 address of Uniswap's pool (eg:- DAI address, MKR address, etc) */ function shut(address token) public returns (uint ethReturned, uint tokenReturned) { address poolAddr = getAddressPool(token); uint userPoolBal = IERC20(poolAddr).balanceOf(address(this)); setApproval(poolAddr, userPoolBal, poolAddr); (ethReturned, tokenReturned) = UniswapPool(poolAddr).removeLiquidity( userPoolBal, uint(1), uint(1), uint(1899063809) // 6th March 2030 GMT // no logic ); address(msg.sender).transfer(ethReturned); IERC20(token).transfer(msg.sender, tokenReturned); emit LogShutPool( token, tokenReturned, ethReturned, userPoolBal, msg.sender ); } } contract InstaUniswapPool is Pool { uint public version; /** * @dev setting up variables on deployment * 1...2...3 versioning in each subsequent deployments */ constructor(uint _version) public { version = _version; } function() external payable {} }
to remove liquidity from pool. ETH and token quantity is decided as per the exchange token qty to burn token ERC20 address of Uniswap's pool (eg:- DAI address, MKR address, etc) amount Uniswap pool's ERC20 token QTY to burn minEth Min ETH user to be returned minTokens Min Tokens to be returned/
function removeLiquidity( address token, uint amount, uint minEth, uint minTokens ) public returns (uint ethReturned, uint tokenReturned) { address poolAddr = getAddressPool(token); setApproval(poolAddr, amount, poolAddr); (ethReturned, tokenReturned) = UniswapPool(poolAddr).removeLiquidity( amount, minEth, minTokens, ); address(msg.sender).transfer(ethReturned); IERC20(token).transfer(msg.sender, tokenReturned); emit LogRemoveLiquidity( token, tokenReturned, ethReturned, amount, msg.sender ); }
2,530,350
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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; return c; } } interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } contract FenumVesting { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address private _owner; IERC20 public token; uint256 public start; uint256 public end; uint256 public cliffDuration; mapping(address => uint256) public vestedAmount; mapping(address => uint256) public totalDrawn; mapping(address => uint256) public lastDrawnAt; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event ScheduleCreated(address indexed beneficiary); event DrawDown(address indexed beneficiary, uint256 indexed amount); constructor(address _token, uint256 _start, uint256 _end, uint256 _cliffDuration) public { _status = _NOT_ENTERED; address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); token = IERC20(_token); // TOKEN_ADDRESS start = _start; // 2021-01-01T00:00:00.000Z = 1609459200 end = _end; // 2024-01-01T00:00:00.000Z = 1704067200 cliffDuration = _cliffDuration; // 30*24*60*60 = 2592000 //setupPredefinedBeneficiaries(); } /* function setupPredefinedBeneficiaries() internal returns (bool) { //vestedAmount[0x7F8d5E6C61685cCc92970c17c2659341e7eDAfe2] = 1_000_00; return true; } */ function owner() public view returns (address) { return _owner; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } /** * @notice Create new vesting schedules in a batch * @notice A transfer is used to bring tokens into the VestingDepositAccount so pre-approval is required * @param beneficiaries array of beneficiaries of the vested tokens * @param amounts array of amount of tokens (in wei) * @dev array index of address should be the same as the array index of the amount */ function createVestingSchedules(address[] calldata beneficiaries, uint256[] calldata amounts) external onlyOwner returns (bool) { require(beneficiaries.length > 0, "FenumVesting: Empty Data"); require(beneficiaries.length == amounts.length, "FenumVesting: Array lengths do not match"); for (uint256 i = 0; i < beneficiaries.length; i = i.add(1)) { address beneficiary = beneficiaries[i]; uint256 amount = amounts[i]; _createVestingSchedule(beneficiary, amount); } return true; } /** * @notice Create a new vesting schedule * @notice A transfer is used to bring tokens into the VestingDepositAccount so pre-approval is required * @param beneficiary beneficiary of the vested tokens * @param amount amount of tokens (in wei) */ function createVestingSchedule(address beneficiary, uint256 amount) external onlyOwner returns (bool) { return _createVestingSchedule(beneficiary, amount); } /** * @notice Draws down any vested tokens due * @dev Must be called directly by the beneficiary assigned the tokens in the schedule */ function drawDown() nonReentrant external returns (bool) { return _drawDown(_msgSender()); } /** * @notice Vested token balance for a beneficiary * @dev Must be called directly by the beneficiary assigned the tokens in the schedule * @return _contractBalance total balance proxied via the ERC20 token */ function contractBalance() external view returns (uint256) { return token.balanceOf(address(this)); } /** * @notice Vesting schedule and associated data for a beneficiary * @dev Must be called directly by the beneficiary assigned the tokens in the schedule * @return _amount * @return _totalDrawn * @return _lastDrawnAt * @return _remainingBalance */ function vestingScheduleForBeneficiary(address beneficiary) external view returns (uint256 _amount, uint256 _totalDrawn, uint256 _lastDrawnAt, uint256 _remainingBalance) { return ( vestedAmount[beneficiary], totalDrawn[beneficiary], lastDrawnAt[beneficiary], vestedAmount[beneficiary].sub(totalDrawn[beneficiary]) ); } /** * @notice Draw down amount currently available (based on the block timestamp) * @param beneficiary beneficiary of the vested tokens * @return amount tokens due from vesting schedule */ function availableDrawDownAmount(address beneficiary) external view returns (uint256) { return _availableDrawDownAmount(beneficiary); } /** * @notice Balance remaining in vesting schedule * @param beneficiary beneficiary of the vested tokens * @return remainingBalance tokens still due (and currently locked) from vesting schedule */ function remainingBalance(address beneficiary) external view returns (uint256) { return vestedAmount[beneficiary].sub(totalDrawn[beneficiary]); } function _createVestingSchedule(address beneficiary, uint256 amount) internal returns (bool) { require(beneficiary != address(0), "FenumVesting: Beneficiary cannot be empty"); require(amount > 0, "FenumVesting: Amount cannot be empty"); // Ensure one per address require(vestedAmount[beneficiary] == 0, "FenumVesting: Schedule already in flight"); vestedAmount[beneficiary] = amount; // Vest the tokens into the deposit account and delegate to the beneficiary require(token.transferFrom(_msgSender(), address(this), amount), "FenumVesting: Unable to escrow tokens"); emit ScheduleCreated(beneficiary); return true; } function _drawDown(address beneficiary) internal returns (bool) { require(vestedAmount[beneficiary] > 0, "FenumVesting: There is no schedule currently in flight"); uint256 amount = _availableDrawDownAmount(beneficiary); require(amount > 0, "FenumVesting: No allowance left to withdraw"); // Update last drawn to now lastDrawnAt[beneficiary] = _getNow(); // Increase total drawn amount totalDrawn[beneficiary] = totalDrawn[beneficiary].add(amount); // Safety measure - this should never trigger require(totalDrawn[beneficiary] <= vestedAmount[beneficiary], "FenumVesting: Safety Mechanism - Drawn exceeded Amount Vested"); // Issue tokens to beneficiary require(token.transfer(beneficiary, amount), "FenumVesting: Unable to transfer tokens"); emit DrawDown(beneficiary, amount); return true; } function _availableDrawDownAmount(address beneficiary) internal view returns (uint256) { uint256 nowTime = _getNow(); // Cliff Period if (nowTime <= start.add(cliffDuration)) { // the cliff period has not ended, no tokens to draw down return 0; } // Schedule complete if (nowTime > end) { return vestedAmount[beneficiary].sub(totalDrawn[beneficiary]); } // Schedule is active // Work out when the last invocation was uint256 timeLastDrawnOrStart = lastDrawnAt[beneficiary] == 0 ? start : lastDrawnAt[beneficiary]; // Find out how much time has past since last invocation uint256 timePassedSinceLastInvocation = nowTime.sub(timeLastDrawnOrStart); // Work out how many due tokens - time passed * rate per second uint256 drawDownRate = vestedAmount[beneficiary].mul(1e18).div(end.sub(start)); uint256 amount = timePassedSinceLastInvocation.mul(drawDownRate).div(1e18); return amount; } modifier nonReentrant() { require(_status != _ENTERED, "FenumVesting: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } modifier onlyOwner() { require(_owner == _msgSender(), "FenumVesting: caller is not the owner"); _; } function _getNow() internal view returns (uint256) { return block.timestamp; } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } receive() external payable { revert("FenumVesting: contract does not accept Ether."); } fallback() external { revert("FenumVesting: contract action not found."); } }
Draw down amount currently available (based on the block timestamp) beneficiary beneficiary of the vested tokens return amount tokens due from vesting schedule/
function availableDrawDownAmount(address beneficiary) external view returns (uint256) { return _availableDrawDownAmount(beneficiary); }
2,517,941
./full_match/137/0x43369C08Aa7efbf00F8b181A0a851e31D91315B0/sources/MaticSwapRouter.sol
performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'MatisSwapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } }
4,755,945
pragma solidity ^0.4.24; contract TokenInfo { // Base prices in wei, going off from an Ether value of $500 uint256 public constant PRIVATESALE_BASE_PRICE_IN_WEI = 200000000000000; uint256 public constant PRESALE_BASE_PRICE_IN_WEI = 600000000000000; uint256 public constant ICO_BASE_PRICE_IN_WEI = 800000000000000; uint256 public constant FIRSTSALE_BASE_PRICE_IN_WEI = 200000000000000; // First sale minimum and maximum contribution, going off from an Ether value of $500 uint256 public constant MIN_PURCHASE_OTHERSALES = 80000000000000000; uint256 public constant MIN_PURCHASE = 1000000000000000000; uint256 public constant MAX_PURCHASE = 1000000000000000000000; // Bonus percentages for each respective sale level uint256 public constant PRESALE_PERCENTAGE_1 = 10; uint256 public constant PRESALE_PERCENTAGE_2 = 15; uint256 public constant PRESALE_PERCENTAGE_3 = 20; uint256 public constant PRESALE_PERCENTAGE_4 = 25; uint256 public constant PRESALE_PERCENTAGE_5 = 35; uint256 public constant ICO_PERCENTAGE_1 = 5; uint256 public constant ICO_PERCENTAGE_2 = 10; uint256 public constant ICO_PERCENTAGE_3 = 15; uint256 public constant ICO_PERCENTAGE_4 = 20; uint256 public constant ICO_PERCENTAGE_5 = 25; // Bonus levels in wei for each respective level uint256 public constant PRESALE_LEVEL_1 = 5000000000000000000; uint256 public constant PRESALE_LEVEL_2 = 10000000000000000000; uint256 public constant PRESALE_LEVEL_3 = 15000000000000000000; uint256 public constant PRESALE_LEVEL_4 = 20000000000000000000; uint256 public constant PRESALE_LEVEL_5 = 25000000000000000000; uint256 public constant ICO_LEVEL_1 = 6666666666666666666; uint256 public constant ICO_LEVEL_2 = 13333333333333333333; uint256 public constant ICO_LEVEL_3 = 20000000000000000000; uint256 public constant ICO_LEVEL_4 = 26666666666666666666; uint256 public constant ICO_LEVEL_5 = 33333333333333333333; // Caps for the respective sales, the amount of tokens allocated to the team and the total cap uint256 public constant PRIVATESALE_TOKENCAP = 18750000; uint256 public constant PRESALE_TOKENCAP = 18750000; uint256 public constant ICO_TOKENCAP = 22500000; uint256 public constant FIRSTSALE_TOKENCAP = 5000000; uint256 public constant LEDTEAM_TOKENS = 35000000; uint256 public constant TOTAL_TOKENCAP = 100000000; uint256 public constant DECIMALS_MULTIPLIER = 1 ether; address public constant LED_MULTISIG = 0x865e785f98b621c5fdde70821ca7cea9eeb77ef4; } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender account. */ 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 { if (newOwner != address(0)) { owner = newOwner; } } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; constructor() public {} /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; emit Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; emit Unpause(); return true; } } contract ApproveAndCallReceiver { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } /** * @title Controllable * @dev The Controllable contract has an controller address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Controllable { address public controller; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender account. */ constructor() public { controller = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyController() { require(msg.sender == controller); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newController The address to transfer ownership to. */ function transferControl(address newController) public onlyController { if (newController != address(0)) { controller = newController; } } } /// @dev The token controller contract must implement these functions contract ControllerInterface { function proxyPayment(address _owner) public payable returns(bool); function onTransfer(address _from, address _to, uint _amount) public returns(bool); function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint256 public totalSupply; function balanceOf(address _owner) public constant returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _amount) public returns (bool); function approve(address _spender, uint256 _amount) public returns (bool); function allowance(address _owner, address _spender) public constant returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Crowdsale is Pausable, TokenInfo { using SafeMath for uint256; LedTokenInterface public ledToken; uint256 public startTime; uint256 public endTime; uint256 public totalWeiRaised; uint256 public tokensMinted; uint256 public totalSupply; uint256 public contributors; uint256 public surplusTokens; bool public finalized; bool public ledTokensAllocated; address public ledMultiSig = LED_MULTISIG; //uint256 public tokenCap = FIRSTSALE_TOKENCAP; //uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; //uint256 public weiCap = tokenCap * FIRSTSALE_BASE_PRICE_IN_WEI; bool public started = false; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event NewClonedToken(address indexed _cloneToken); event OnTransfer(address _from, address _to, uint _amount); event OnApprove(address _owner, address _spender, uint _amount); event LogInt(string _name, uint256 _value); event Finalized(); // constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { // startTime = _startTime; // endTime = _endTime; // ledToken = LedTokenInterface(_tokenAddress); // assert(_tokenAddress != 0x0); // assert(_startTime > 0); // assert(_endTime > _startTime); // } /** * Low level token purchase function * @param _beneficiary will receive the tokens. */ /*function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { require(_beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount >= MIN_PURCHASE && weiAmount <= MAX_PURCHASE); uint256 priceInWei = FIRSTSALE_BASE_PRICE_IN_WEI; totalWeiRaised = totalWeiRaised.add(weiAmount); uint256 tokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); tokensMinted = tokensMinted.add(tokens); require(tokensMinted < cap); contributors = contributors.add(1); ledToken.mint(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); forwardFunds(); }*/ /** * Forwards funds to the tokensale wallet */ function forwardFunds() internal { ledMultiSig.transfer(msg.value); } /** * Validates the purchase (period, minimum amount, within cap) * @return {bool} valid */ function validPurchase() internal constant returns (bool) { uint256 current = now; bool presaleStarted = (current >= startTime || started); bool presaleNotEnded = current <= endTime; bool nonZeroPurchase = msg.value != 0; return nonZeroPurchase && presaleStarted && presaleNotEnded; } /** * Returns the total Led token supply * @return totalSupply {uint256} Led Token Total Supply */ function totalSupply() public constant returns (uint256) { return ledToken.totalSupply(); } /** * Returns token holder Led Token balance * @param _owner {address} Token holder address * @return balance {uint256} Corresponding token holder balance */ function balanceOf(address _owner) public constant returns (uint256) { return ledToken.balanceOf(_owner); } /** * Change the Led Token controller * @param _newController {address} New Led Token controller */ function changeController(address _newController) public onlyOwner { require(isContract(_newController)); ledToken.transferControl(_newController); } function enableMasterTransfers() public onlyOwner { ledToken.enableMasterTransfers(true); } function lockMasterTransfers() public onlyOwner { ledToken.enableMasterTransfers(false); } function forceStart() public onlyOwner { started = true; } /*function finalize() public onlyOwner { require(paused); require(!finalized); surplusTokens = cap - tokensMinted; ledToken.mint(ledMultiSig, surplusTokens); ledToken.transferControl(owner); emit Finalized(); finalized = true; }*/ function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } modifier whenNotFinalized() { require(!finalized); _; } } /** * @title FirstSale * FirstSale allows investors to make token purchases and assigns them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet as they arrive. */ contract FirstSale is Crowdsale { uint256 public tokenCap = FIRSTSALE_TOKENCAP; uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; uint256 public weiCap = tokenCap * FIRSTSALE_BASE_PRICE_IN_WEI; constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { startTime = _startTime; endTime = _endTime; ledToken = LedTokenInterface(_tokenAddress); assert(_tokenAddress != 0x0); assert(_startTime > 0); assert(_endTime > _startTime); } /** * High level token purchase function */ function() public payable { buyTokens(msg.sender); } /** * Low level token purchase function * @param _beneficiary will receive the tokens. */ function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { require(_beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount >= MIN_PURCHASE && weiAmount <= MAX_PURCHASE); uint256 priceInWei = FIRSTSALE_BASE_PRICE_IN_WEI; totalWeiRaised = totalWeiRaised.add(weiAmount); uint256 tokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); tokensMinted = tokensMinted.add(tokens); require(tokensMinted < cap); contributors = contributors.add(1); ledToken.mint(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); forwardFunds(); } function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, bool, uint256, uint256){ uint256 decimals = 18; string memory symbol = "LED"; bool transfersEnabled = ledToken.transfersEnabled(); return ( TOTAL_TOKENCAP, // Tokencap with the decimal point in place. should be 100.000.000 decimals, // Decimals symbol, transfersEnabled, contributors, totalWeiRaised, tokenCap, // Tokencap for the first sale with the decimal point in place. started, startTime, // Start time and end time in Unix timestamp format with a length of 10 numbers. endTime ); } function finalize() public onlyOwner { require(paused); require(!finalized); surplusTokens = cap - tokensMinted; ledToken.mint(ledMultiSig, surplusTokens); ledToken.transferControl(owner); emit Finalized(); finalized = true; } } contract LedToken is Controllable { using SafeMath for uint256; LedTokenInterface public parentToken; TokenFactoryInterface public tokenFactory; string public name; string public symbol; string public version; uint8 public decimals; uint256 public parentSnapShotBlock; uint256 public creationBlock; bool public transfersEnabled; bool public masterTransfersEnabled; address public masterWallet = 0x865e785f98b621c5fdde70821ca7cea9eeb77ef4; struct Checkpoint { uint128 fromBlock; uint128 value; } Checkpoint[] totalSupplyHistory; mapping(address => Checkpoint[]) balances; mapping (address => mapping (address => uint)) allowed; bool public mintingFinished = false; bool public presaleBalancesLocked = false; uint256 public totalSupplyAtCheckpoint; event MintFinished(); event NewCloneToken(address indexed cloneToken); event Approval(address indexed _owner, address indexed _spender, uint256 _amount); event Transfer(address indexed from, address indexed to, uint256 value); constructor( address _tokenFactory, address _parentToken, uint256 _parentSnapShotBlock, string _tokenName, string _tokenSymbol ) public { tokenFactory = TokenFactoryInterface(_tokenFactory); parentToken = LedTokenInterface(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; name = _tokenName; symbol = _tokenSymbol; decimals = 18; transfersEnabled = false; masterTransfersEnabled = false; creationBlock = block.number; version = '0.1'; } /** * Returns the total Led token supply at the current block * @return total supply {uint256} */ function totalSupply() public constant returns (uint256) { return totalSupplyAt(block.number); } /** * Returns the total Led token supply at the given block number * @param _blockNumber {uint256} * @return total supply {uint256} */ function totalSupplyAt(uint256 _blockNumber) public constant returns(uint256) { // 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) != 0x0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } /** * Returns the token holder balance at the current block * @param _owner {address} * @return balance {uint256} */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /** * Returns the token holder balance the the given block number * @param _owner {address} * @param _blockNumber {uint256} * @return balance {uint256} */ function balanceOfAt(address _owner, uint256 _blockNumber) public constant returns (uint256) { // 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) != 0x0) { 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); } } /** * Standard ERC20 transfer tokens function * @param _to {address} * @param _amount {uint} * @return success {bool} */ function transfer(address _to, uint256 _amount) public returns (bool success) { return doTransfer(msg.sender, _to, _amount); } /** * Standard ERC20 transferFrom function * @param _from {address} * @param _to {address} * @param _amount {uint256} * @return success {bool} */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; return doTransfer(_from, _to, _amount); } /** * Standard ERC20 approve function * @param _spender {address} * @param _amount {uint256} * @return success {bool} */ function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); //https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * Standard ERC20 approve function * @param _spender {address} * @param _amount {uint256} * @return success {bool} */ function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns (bool success) { approve(_spender, _amount); ApproveAndCallReceiver(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /** * Standard ERC20 allowance function * @param _owner {address} * @param _spender {address} * @return remaining {uint256} */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * Internal Transfer function - Updates the checkpoint ledger * @param _from {address} * @param _to {address} * @param _amount {uint256} * @return success {bool} */ function doTransfer(address _from, address _to, uint256 _amount) internal returns(bool) { if (msg.sender != masterWallet) { require(transfersEnabled); } else { require(masterTransfersEnabled); } require(_amount > 0); require(parentSnapShotBlock < block.number); require((_to != address(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); require(previousBalanceFrom >= _amount); // 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 + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _amount); return true; } /** * Token creation functions - can only be called by the tokensale controller during the tokensale period * @param _owner {address} * @param _amount {uint256} * @return success {bool} */ function mint(address _owner, uint256 _amount) public onlyController canMint returns (bool) { uint256 curTotalSupply = totalSupply(); uint256 previousBalanceTo = balanceOf(_owner); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); emit Transfer(0, _owner, _amount); return true; } modifier canMint() { require(!mintingFinished); _; } /** * Import presale balances before the start of the token sale. After importing * balances, lockPresaleBalances() has to be called to prevent further modification * of presale balances. * @param _addresses {address[]} Array of presale addresses * @param _balances {uint256[]} Array of balances corresponding to presale addresses. * @return success {bool} */ function importPresaleBalances(address[] _addresses, uint256[] _balances) public onlyController returns (bool) { require(presaleBalancesLocked == false); for (uint256 i = 0; i < _addresses.length; i++) { totalSupplyAtCheckpoint += _balances[i]; updateValueAtNow(balances[_addresses[i]], _balances[i]); updateValueAtNow(totalSupplyHistory, totalSupplyAtCheckpoint); emit Transfer(0, _addresses[i], _balances[i]); } return true; } /** * Lock presale balances after successful presale balance import * @return A boolean that indicates if the operation was successful. */ function lockPresaleBalances() public onlyController returns (bool) { presaleBalancesLocked = true; return true; } /** * Lock the minting of Led Tokens - to be called after the presale * @return {bool} success */ function finishMinting() public onlyController returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** * Enable or block transfers - to be called in case of emergency * @param _value {bool} */ function enableTransfers(bool _value) public onlyController { transfersEnabled = _value; } /** * Enable or block transfers - to be called in case of emergency * @param _value {bool} */ function enableMasterTransfers(bool _value) public onlyController { masterTransfersEnabled = _value; } /** * Internal balance method - gets a certain checkpoint value a a certain _block * @param _checkpoints {Checkpoint[]} List of checkpoints - supply history or balance history * @return value {uint256} Value of _checkpoints at _block */ function getValueAt(Checkpoint[] storage _checkpoints, uint256 _block) constant internal returns (uint256) { if (_checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= _checkpoints[_checkpoints.length-1].fromBlock) return _checkpoints[_checkpoints.length-1].value; if (_block < _checkpoints[0].fromBlock) return 0; // Binary search of the value in the array 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; } /** * Internal update method - updates the checkpoint ledger at the current block * @param _checkpoints {Checkpoint[]} List of checkpoints - supply history or balance history * @return value {uint256} Value to add to the checkpoints ledger */ function updateValueAtNow(Checkpoint[] storage _checkpoints, uint256 _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); } } function min(uint256 a, uint256 b) internal pure returns (uint) { return a < b ? a : b; } /** * Clones Led Token at the given snapshot block * @param _snapshotBlock {uint256} * @param _name {string} - The cloned token name * @param _symbol {string} - The cloned token symbol * @return clonedTokenAddress {address} */ function createCloneToken(uint256 _snapshotBlock, string _name, string _symbol) public returns(address) { if (_snapshotBlock == 0) { _snapshotBlock = block.number; } if (_snapshotBlock > block.number) { _snapshotBlock = block.number; } LedToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _name, _symbol ); cloneToken.transferControl(msg.sender); // An event to make the token easy to find on the blockchain emit NewCloneToken(address(cloneToken)); return address(cloneToken); } } /** * @title LedToken (LED) * Standard Mintable ERC20 Token * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract LedTokenInterface is Controllable { bool public transfersEnabled; event Mint(address indexed to, uint256 amount); event MintFinished(); event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval(address indexed _owner, address indexed _spender, uint256 _amount); event Transfer(address indexed from, address indexed to, uint256 value); function totalSupply() public constant returns (uint); function totalSupplyAt(uint _blockNumber) public constant returns(uint); function balanceOf(address _owner) public constant returns (uint256 balance); function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint); function transfer(address _to, uint256 _amount) public returns (bool success); function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success); function approve(address _spender, uint256 _amount) public returns (bool success); function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); function mint(address _owner, uint _amount) public returns (bool); function importPresaleBalances(address[] _addresses, uint256[] _balances, address _presaleAddress) public returns (bool); function lockPresaleBalances() public returns (bool); function finishMinting() public returns (bool); function enableTransfers(bool _value) public; function enableMasterTransfers(bool _value) public; function createCloneToken(uint _snapshotBlock, string _cloneTokenName, string _cloneTokenSymbol) public returns (address); } /** * @title Presale * Presale allows investors to make token purchases and assigns them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet as they arrive. */ contract Presale is Crowdsale { uint256 public tokenCap = PRESALE_TOKENCAP; uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; uint256 public weiCap = tokenCap * PRESALE_BASE_PRICE_IN_WEI; constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { startTime = _startTime; endTime = _endTime; ledToken = LedTokenInterface(_tokenAddress); assert(_tokenAddress != 0x0); assert(_startTime > 0); assert(_endTime > _startTime); } /** * High level token purchase function */ function() public payable { buyTokens(msg.sender); } /** * Low level token purchase function * @param _beneficiary will receive the tokens. */ function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { require(_beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount >= MIN_PURCHASE_OTHERSALES && weiAmount <= MAX_PURCHASE); uint256 priceInWei = PRESALE_BASE_PRICE_IN_WEI; totalWeiRaised = totalWeiRaised.add(weiAmount); uint256 bonusPercentage = determineBonus(weiAmount); uint256 bonusTokens; uint256 initialTokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); if(bonusPercentage>0){ uint256 initialDivided = initialTokens.div(100); bonusTokens = initialDivided.mul(bonusPercentage); } else { bonusTokens = 0; } uint256 tokens = initialTokens.add(bonusTokens); tokensMinted = tokensMinted.add(tokens); require(tokensMinted < cap); contributors = contributors.add(1); ledToken.mint(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); forwardFunds(); } function determineBonus(uint256 _wei) public view returns (uint256) { if(_wei > PRESALE_LEVEL_1) { if(_wei > PRESALE_LEVEL_2) { if(_wei > PRESALE_LEVEL_3) { if(_wei > PRESALE_LEVEL_4) { if(_wei > PRESALE_LEVEL_5) { return PRESALE_PERCENTAGE_5; } else { return PRESALE_PERCENTAGE_4; } } else { return PRESALE_PERCENTAGE_3; } } else { return PRESALE_PERCENTAGE_2; } } else { return PRESALE_PERCENTAGE_1; } } else { return 0; } } function finalize() public onlyOwner { require(paused); require(!finalized); surplusTokens = cap - tokensMinted; ledToken.mint(ledMultiSig, surplusTokens); ledToken.transferControl(owner); emit Finalized(); finalized = true; } function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, bool, uint256, uint256){ uint256 decimals = 18; string memory symbol = "LED"; bool transfersEnabled = ledToken.transfersEnabled(); return ( TOTAL_TOKENCAP, // Tokencap with the decimal point in place. should be 100.000.000 decimals, // Decimals symbol, transfersEnabled, contributors, totalWeiRaised, tokenCap, // Tokencap for the first sale with the decimal point in place. started, startTime, // Start time and end time in Unix timestamp format with a length of 10 numbers. endTime ); } function getInfoLevels() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256){ return ( PRESALE_LEVEL_1, // Amount of ether needed per bonus level PRESALE_LEVEL_2, PRESALE_LEVEL_3, PRESALE_LEVEL_4, PRESALE_LEVEL_5, PRESALE_PERCENTAGE_1, // Bonus percentage per bonus level PRESALE_PERCENTAGE_2, PRESALE_PERCENTAGE_3, PRESALE_PERCENTAGE_4, PRESALE_PERCENTAGE_5 ); } } /** * @title PrivateSale * PrivateSale allows investors to make token purchases and assigns them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet as they arrive. */ contract PrivateSale is Crowdsale { uint256 public tokenCap = PRIVATESALE_TOKENCAP; uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; uint256 public weiCap = tokenCap * PRIVATESALE_BASE_PRICE_IN_WEI; constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { startTime = _startTime; endTime = _endTime; ledToken = LedTokenInterface(_tokenAddress); assert(_tokenAddress != 0x0); assert(_startTime > 0); assert(_endTime > _startTime); } /** * High level token purchase function */ function() public payable { buyTokens(msg.sender); } /** * Low level token purchase function * @param _beneficiary will receive the tokens. */ function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { require(_beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount >= MIN_PURCHASE_OTHERSALES && weiAmount <= MAX_PURCHASE); uint256 priceInWei = PRIVATESALE_BASE_PRICE_IN_WEI; totalWeiRaised = totalWeiRaised.add(weiAmount); uint256 tokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); tokensMinted = tokensMinted.add(tokens); require(tokensMinted < cap); contributors = contributors.add(1); ledToken.mint(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); forwardFunds(); } function finalize() public onlyOwner { require(paused); require(!finalized); surplusTokens = cap - tokensMinted; ledToken.mint(ledMultiSig, surplusTokens); ledToken.transferControl(owner); emit Finalized(); finalized = true; } function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, bool, uint256, uint256){ uint256 decimals = 18; string memory symbol = "LED"; bool transfersEnabled = ledToken.transfersEnabled(); return ( TOTAL_TOKENCAP, // Tokencap with the decimal point in place. should be 100.000.000 decimals, // Decimals symbol, transfersEnabled, contributors, totalWeiRaised, tokenCap, // Tokencap for the first sale with the decimal point in place. started, startTime, // Start time and end time in Unix timestamp format with a length of 10 numbers. endTime ); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract TokenFactory { function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, string _tokenSymbol ) public returns (LedToken) { LedToken newToken = new LedToken( this, _parentToken, _snapshotBlock, _tokenName, _tokenSymbol ); newToken.transferControl(msg.sender); return newToken; } } contract TokenFactoryInterface { function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, string _tokenSymbol ) public returns (LedToken newToken); } /** * @title Tokensale * Tokensale allows investors to make token purchases and assigns them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet as they arrive. */ contract TokenSale is Crowdsale { uint256 public tokenCap = ICO_TOKENCAP; uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; uint256 public weiCap = tokenCap * ICO_BASE_PRICE_IN_WEI; uint256 public allocatedTokens; constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { startTime = _startTime; endTime = _endTime; ledToken = LedTokenInterface(_tokenAddress); assert(_tokenAddress != 0x0); assert(_startTime > 0); assert(_endTime > _startTime); } /** * High level token purchase function */ function() public payable { buyTokens(msg.sender); } /** * Low level token purchase function * @param _beneficiary will receive the tokens. */ function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { require(_beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount >= MIN_PURCHASE_OTHERSALES && weiAmount <= MAX_PURCHASE); uint256 priceInWei = ICO_BASE_PRICE_IN_WEI; totalWeiRaised = totalWeiRaised.add(weiAmount); uint256 bonusPercentage = determineBonus(weiAmount); uint256 bonusTokens; uint256 initialTokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); if(bonusPercentage>0){ uint256 initialDivided = initialTokens.div(100); bonusTokens = initialDivided.mul(bonusPercentage); } else { bonusTokens = 0; } uint256 tokens = initialTokens.add(bonusTokens); tokensMinted = tokensMinted.add(tokens); require(tokensMinted < cap); contributors = contributors.add(1); ledToken.mint(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); forwardFunds(); } function determineBonus(uint256 _wei) public view returns (uint256) { if(_wei > ICO_LEVEL_1) { if(_wei > ICO_LEVEL_2) { if(_wei > ICO_LEVEL_3) { if(_wei > ICO_LEVEL_4) { if(_wei > ICO_LEVEL_5) { return ICO_PERCENTAGE_5; } else { return ICO_PERCENTAGE_4; } } else { return ICO_PERCENTAGE_3; } } else { return ICO_PERCENTAGE_2; } } else { return ICO_PERCENTAGE_1; } } else { return 0; } } function allocateLedTokens() public onlyOwner whenNotFinalized { require(!ledTokensAllocated); allocatedTokens = LEDTEAM_TOKENS.mul(DECIMALS_MULTIPLIER); ledToken.mint(ledMultiSig, allocatedTokens); ledTokensAllocated = true; } function finalize() public onlyOwner { require(paused); require(ledTokensAllocated); surplusTokens = cap - tokensMinted; ledToken.mint(ledMultiSig, surplusTokens); ledToken.finishMinting(); ledToken.enableTransfers(true); emit Finalized(); finalized = true; } function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, bool, uint256, uint256){ uint256 decimals = 18; string memory symbol = "LED"; bool transfersEnabled = ledToken.transfersEnabled(); return ( TOTAL_TOKENCAP, // Tokencap with the decimal point in place. should be 100.000.000 decimals, // Decimals symbol, transfersEnabled, contributors, totalWeiRaised, tokenCap, // Tokencap for the first sale with the decimal point in place. started, startTime, // Start time and end time in Unix timestamp format with a length of 10 numbers. endTime ); } function getInfoLevels() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256){ return ( ICO_LEVEL_1, // Amount of ether needed per bonus level ICO_LEVEL_2, ICO_LEVEL_3, ICO_LEVEL_4, ICO_LEVEL_5, ICO_PERCENTAGE_1, // Bonus percentage per bonus level ICO_PERCENTAGE_2, ICO_PERCENTAGE_3, ICO_PERCENTAGE_4, ICO_PERCENTAGE_5 ); } }
Standard ERC20 transfer tokens function _to {address} _amount {uint} return success {bool}/
function transfer(address _to, uint256 _amount) public returns (bool success) { return doTransfer(msg.sender, _to, _amount); }
611,066
// SPDX-License-Identifier: MIT pragma solidity ^0.7.2; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { PoseidonT3, PoseidonT6, Hasher } from "../crypto/Hasher.sol"; import { MerkleZeros as MerkleBinary0 } from "./zeros/MerkleBinary0.sol"; import { MerkleZeros as MerkleBinaryMaci } from "./zeros/MerkleBinaryMaci.sol"; import { MerkleZeros as MerkleQuinary0 } from "./zeros/MerkleQuinary0.sol"; import { MerkleZeros as MerkleQuinaryMaci } from "./zeros/MerkleQuinaryMaci.sol"; import { MerkleZeros as MerkleQuinaryBlankSl } from "./zeros/MerkleQuinaryBlankSl.sol"; import { MerkleZeros as MerkleQuinaryMaciWithSha256 } from "./zeros/MerkleQuinaryMaciWithSha256.sol"; /* * This contract defines a Merkle tree where each leaf insertion only updates a * subtree. To obtain the main tree root, the contract owner must merge the * subtrees together. Merging subtrees requires at least 2 operations: * mergeSubRoots(), and merge(). To get around the gas limit, * the mergeSubRoots() can be performed in multiple transactions. */ abstract contract AccQueue is Ownable, Hasher { // The maximum tree depth uint256 constant MAX_DEPTH = 32; // A Queue is a 2D array of Merkle roots and indices which represents nodes // in a Merkle tree while it is progressively updated. struct Queue { // IMPORTANT: the following declares an array of b elements of type T: T[b] // And the following declares an array of b elements of type T[a]: T[a][b] // As such, the following declares an array of MAX_DEPTH+1 arrays of // uint256[4] arrays, **not the other way round**: uint256[4][MAX_DEPTH + 1] levels; uint256[MAX_DEPTH + 1] indices; } // The depth of each subtree uint256 internal immutable subDepth; // The number of elements per hash operation. Should be either 2 (for // binary trees) or 5 (quinary trees). The limit is 5 because that is the // maximum supported number of inputs for the EVM implementation of the // Poseidon hash function uint256 internal immutable hashLength; // hashLength ** subDepth uint256 internal immutable subTreeCapacity; // True hashLength == 2, false if hashLength == 5 bool internal isBinary; // The index of the current subtree. e.g. the first subtree has index 0, the // second has 1, and so on uint256 internal currentSubtreeIndex; // Tracks the current subtree. Queue internal leafQueue; // Tracks the smallest tree of subroots Queue internal subRootQueue; // Subtree roots mapping(uint256 => uint256) internal subRoots; // Merged roots uint256[MAX_DEPTH + 1] internal mainRoots; // Whether the subtrees have been merged bool public subTreesMerged; // Whether entire merkle tree has been merged bool public treeMerged; // The root of the shortest possible tree which fits all current subtree // roots uint256 internal smallSRTroot; // Tracks the next subroot to queue uint256 internal nextSubRootIndex; // The number of leaves inserted across all subtrees so far uint256 public numLeaves; constructor( uint256 _subDepth, uint256 _hashLength ) { require( _subDepth > 0, "AccQueue: _subDepth must be more than 0" ); require( _subDepth <= MAX_DEPTH, "AccQueue: only supports up to MAX_DEPTH levels" ); require( _hashLength == 2 || _hashLength == 5, "AccQueue: only supports _hashLength of 2 or 5" ); isBinary = _hashLength == 2; subDepth = _subDepth; hashLength = _hashLength; subTreeCapacity = _hashLength ** _subDepth; } /* * Hash the contents of the specified level and the specified leaf. * This is a virtual function as the hash function which the overriding * contract uses will be either hashLeftRight or hash5, which require * different input array lengths. * @param _level The level to hash. * @param _leaf The leaf include with the level. */ function hashLevel(uint256 _level, uint256 _leaf) virtual internal returns (uint256) {} function hashLevelLeaf(uint256 _level, uint256 _leaf) virtual view public returns (uint256) {} /* * Returns the zero leaf at a specified level. * This is a virtual function as the hash function which the overriding * contract uses will be either hashLeftRight or hash5, which will produce * different zero values (e.g. hashLeftRight(0, 0) vs * hash5([0, 0, 0, 0, 0]). Moreover, the zero value may be a * nothing-up-my-sleeve value. */ function getZero(uint256 _level) internal virtual returns (uint256) {} /* * Add a leaf to the queue for the current subtree. * @param _leaf The leaf to add. */ function enqueue(uint256 _leaf) public onlyOwner returns (uint256) { uint256 leafIndex = numLeaves; // Recursively queue the leaf _enqueue(_leaf, 0); // Update the leaf counter numLeaves = leafIndex + 1; // Now that a new leaf has been added, mainRoots and smallSRTroot are // obsolete delete mainRoots; delete smallSRTroot; subTreesMerged = false; // If a subtree is full if (numLeaves % subTreeCapacity == 0) { // Store the subroot subRoots[currentSubtreeIndex] = leafQueue.levels[subDepth][0]; // Increment the index currentSubtreeIndex ++; // Delete ancillary data delete leafQueue.levels[subDepth][0]; delete leafQueue.indices; } return leafIndex; } /* * Updates the queue at a given level and hashes any subroots that need to * be hashed. * @param _leaf The leaf to add. * @param _level The level at which to queue the leaf. */ function _enqueue(uint256 _leaf, uint256 _level) internal { require(_level <= subDepth, "AccQueue: invalid level"); while (true) { uint256 n = leafQueue.indices[_level]; if (n != hashLength - 1) { // Just store the leaf leafQueue.levels[_level][n] = _leaf; if (_level != subDepth) { // Update the index leafQueue.indices[_level]++; } return; } // Hash the leaves to next level _leaf = hashLevel(_level, _leaf); // Reset the index for this level delete leafQueue.indices[_level]; // Queue the hash of the leaves into to the next level _level++; } } /* * Fill any empty leaves of the current subtree with zeros and store the * resulting subroot. */ function fill() public onlyOwner { if (numLeaves % subTreeCapacity == 0) { // If the subtree is completely empty, then the subroot is a // precalculated zero value subRoots[currentSubtreeIndex] = getZero(subDepth); } else { // Otherwise, fill the rest of the subtree with zeros _fill(0); // Store the subroot subRoots[currentSubtreeIndex] = leafQueue.levels[subDepth][0]; // Reset the subtree data delete leafQueue.levels; // Reset the merged roots delete mainRoots; } // Increment the subtree index uint256 curr = currentSubtreeIndex + 1; currentSubtreeIndex = curr; // Update the number of leaves numLeaves = curr * subTreeCapacity; // Reset the subroot tree root now that it is obsolete delete smallSRTroot; subTreesMerged = false; } /* * A function that queues zeros to the specified level, hashes, * the level, and enqueues the hash to the next level. * @param _level The level at which to queue zeros. */ function _fill(uint256 _level) virtual internal {} /* * Insert a subtree. Used for batch enqueues. */ function insertSubTree(uint256 _subRoot) public onlyOwner { subRoots[currentSubtreeIndex] = _subRoot; // Increment the subtree index currentSubtreeIndex ++; // Update the number of leaves numLeaves += subTreeCapacity; // Reset the subroot tree root now that it is obsolete delete smallSRTroot; subTreesMerged = false; } /* * Calculate the lowest possible height of a tree with all the subroots * merged together. */ function calcMinHeight() public view returns (uint256) { uint256 depth = 1; while (true) { if (hashLength ** depth >= currentSubtreeIndex) { break; } depth ++; } return depth; } /* * Merge all subtrees to form the shortest possible tree. * This function can be called either once to merge all subtrees in a * single transaction, or multiple times to do the same in multiple * transactions. If _numSrQueueOps is set to 0, this function will attempt * to merge all subtrees in one go. If it is set to a number greater than * 0, it will perform up to that number of queueSubRoot() operations. * @param _numSrQueueOps The number of times this function will call * queueSubRoot(), up to the maximum number of times * is necessary. If it is set to 0, it will call * queueSubRoot() as many times as is necessary. Set * this to a low number and call this function * multiple times if there are many subroots to * merge, or a single transaction would run out of * gas. */ function mergeSubRoots( uint256 _numSrQueueOps ) public onlyOwner { // This function can only be called once unless a new subtree is created require(subTreesMerged == false, "AccQueue: subtrees already merged"); // There must be subtrees to merge require(numLeaves > 0, "AccQueue: nothing to merge"); // Fill any empty leaves in the current subtree with zeros ony if the // current subtree is not full if (numLeaves % subTreeCapacity != 0) { fill(); } // If there is only 1 subtree, use its root if (currentSubtreeIndex == 1) { smallSRTroot = getSubRoot(0); subTreesMerged = true; return; } uint256 depth = calcMinHeight(); uint256 queueOpsPerformed = 0; for (uint256 i = nextSubRootIndex; i < currentSubtreeIndex; i ++) { if (_numSrQueueOps != 0 && queueOpsPerformed == _numSrQueueOps) { // If the limit is not 0, stop if the limit has been reached return; } // Queue the next subroot queueSubRoot( getSubRoot(nextSubRootIndex), 0, depth ); // Increment the next subroot counter nextSubRootIndex ++; // Increment the ops counter queueOpsPerformed ++; } // The height of the tree of subroots uint256 m = hashLength ** depth; // Queue zeroes to fill out the SRT if (nextSubRootIndex == currentSubtreeIndex) { uint256 z = getZero(subDepth); for (uint256 i = currentSubtreeIndex; i < m; i ++) { queueSubRoot(z, 0, depth); } } // Store the smallest main root smallSRTroot = subRootQueue.levels[depth][0]; subTreesMerged = true; } /* * Queues a subroot into the subroot tree. * @param _leaf The value to queue. * @param _level The level at which to queue _leaf. * @param _maxDepth The depth of the tree. */ function queueSubRoot(uint256 _leaf, uint256 _level, uint256 _maxDepth) internal { if (_level > _maxDepth) { return; } uint256 n = subRootQueue.indices[_level]; if (n != hashLength - 1) { // Just store the leaf subRootQueue.levels[_level][n] = _leaf; subRootQueue.indices[_level] ++; } else { // Hash the elements in this level and queue it in the next level uint256 hashed; if (isBinary) { uint256[2] memory inputs; inputs[0] = subRootQueue.levels[_level][0]; inputs[1] = _leaf; hashed = hash2(inputs); } else { uint256[5] memory inputs; for (uint8 i = 0; i < n; i ++) { inputs[i] = subRootQueue.levels[_level][i]; } inputs[n] = _leaf; hashed = hash5(inputs); } // TODO: change recursion to a while loop // Recurse delete subRootQueue.indices[_level]; queueSubRoot(hashed, _level + 1, _maxDepth); } } /* * Merge all subtrees to form a main tree with a desired depth. * @param _depth The depth of the main tree. It must fit all the leaves or * this function will revert. */ function merge(uint256 _depth) public onlyOwner returns (uint256) { // The tree depth must be more than 0 require(_depth > 0, "AccQueue: _depth must be more than 0"); // Ensure that the subtrees have been merged require(subTreesMerged == true, "AccQueue: subtrees must be merged before calling merge()"); // Check the depth require(_depth <= MAX_DEPTH, "AccQueue: _depth must be lte MAX_DEPTH"); // Calculate the SRT depth uint256 srtDepth = subDepth; while (true) { if (hashLength ** srtDepth >= numLeaves) { break; } srtDepth ++; } require( _depth >= srtDepth, "AccQueue: _depth must be gte the SRT depth" ); // If the depth is the same as the SRT depth, just use the SRT root if (_depth == srtDepth) { mainRoots[_depth] = smallSRTroot; treeMerged = true; return smallSRTroot; } else { uint256 root = smallSRTroot; // Calculate the main root for (uint256 i = srtDepth; i < _depth; i ++) { uint256 z = getZero(i); if (isBinary) { uint256[2] memory inputs; inputs[0] = root; inputs[1] = z; root = hash2(inputs); } else { uint256[5] memory inputs; inputs[0] = root; inputs[1] = z; inputs[2] = z; inputs[3] = z; inputs[4] = z; root = hash5(inputs); } } mainRoots[_depth] = root; treeMerged = true; return root; } } /* * Returns the subroot at the specified index. Reverts if the index refers * to a subtree which has not been filled yet. * @param _index The subroot index. */ function getSubRoot(uint256 _index) public view returns (uint256) { require( currentSubtreeIndex > _index, "AccQueue: _index must refer to a complete subtree" ); return subRoots[_index]; } /* * Returns the subroot tree (SRT) root. Its value must first be computed * using mergeSubRoots. */ function getSmallSRTroot() public view returns (uint256) { require(subTreesMerged, "AccQueue: subtrees must be merged first"); return smallSRTroot; } /* * Return the merged Merkle root of all the leaves at a desired depth. * merge() or merged(_depth) must be called first. * @param _depth The depth of the main tree. It must first be computed * using mergeSubRoots() and merge(). */ function getMainRoot(uint256 _depth) public view returns (uint256) { require( hashLength ** _depth >= numLeaves, "AccQueue: getMainRoot: _depth must be high enough" ); return mainRoots[_depth]; } function getSrIndices() public view returns (uint256, uint256) { return (nextSubRootIndex, currentSubtreeIndex); } } abstract contract AccQueueBinary is AccQueue { constructor(uint256 _subDepth) AccQueue(_subDepth, 2) {} function hashLevel(uint256 _level, uint256 _leaf) override internal returns (uint256) { uint256 hashed = hashLeftRight(leafQueue.levels[_level][0], _leaf); // Free up storage slots to refund gas. delete leafQueue.levels[_level][0]; return hashed; } function hashLevelLeaf(uint256 _level, uint256 _leaf) override view public returns (uint256) { uint256 hashed = hashLeftRight(leafQueue.levels[_level][0], _leaf); return hashed; } function _fill(uint256 _level) override internal { while (_level < subDepth) { uint256 n = leafQueue.indices[_level]; if (n != 0) { // Fill the subtree level with zeros and hash the level uint256 hashed; uint256[2] memory inputs; uint256 z = getZero(_level); inputs[0] = leafQueue.levels[_level][0]; inputs[1] = z; hashed = hash2(inputs); // Update the subtree from the next level onwards with the new leaf _enqueue(hashed, _level + 1); } // Reset the current level delete leafQueue.indices[_level]; _level++; } } } abstract contract AccQueueQuinary is AccQueue { constructor(uint256 _subDepth) AccQueue(_subDepth, 5) {} function hashLevel(uint256 _level, uint256 _leaf) override internal returns (uint256) { uint256[5] memory inputs; inputs[0] = leafQueue.levels[_level][0]; inputs[1] = leafQueue.levels[_level][1]; inputs[2] = leafQueue.levels[_level][2]; inputs[3] = leafQueue.levels[_level][3]; inputs[4] = _leaf; uint256 hashed = hash5(inputs); // Free up storage slots to refund gas. Note that using a loop here // would result in lower gas savings. delete leafQueue.levels[_level]; return hashed; } function hashLevelLeaf(uint256 _level, uint256 _leaf) override view public returns (uint256) { uint256[5] memory inputs; inputs[0] = leafQueue.levels[_level][0]; inputs[1] = leafQueue.levels[_level][1]; inputs[2] = leafQueue.levels[_level][2]; inputs[3] = leafQueue.levels[_level][3]; inputs[4] = _leaf; uint256 hashed = hash5(inputs); return hashed; } function _fill(uint256 _level) override internal { while (_level < subDepth) { uint256 n = leafQueue.indices[_level]; if (n != 0) { // Fill the subtree level with zeros and hash the level uint256 hashed; uint256[5] memory inputs; uint256 z = getZero(_level); uint8 i = 0; for (; i < n; i ++) { inputs[i] = leafQueue.levels[_level][i]; } for (; i < hashLength; i ++) { inputs[i] = z; } hashed = hash5(inputs); // Update the subtree from the next level onwards with the new leaf _enqueue(hashed, _level + 1); } // Reset the current level delete leafQueue.indices[_level]; _level++; } } } contract AccQueueBinary0 is AccQueueBinary, MerkleBinary0 { constructor(uint256 _subDepth) AccQueueBinary(_subDepth) {} function getZero(uint256 _level) internal view override returns (uint256) { return zeros[_level]; } } contract AccQueueBinaryMaci is AccQueueBinary, MerkleBinaryMaci { constructor(uint256 _subDepth) AccQueueBinary(_subDepth) {} function getZero(uint256 _level) internal view override returns (uint256) { return zeros[_level]; } } contract AccQueueQuinary0 is AccQueueQuinary, MerkleQuinary0 { constructor(uint256 _subDepth) AccQueueQuinary(_subDepth) {} function getZero(uint256 _level) internal view override returns (uint256) { return zeros[_level]; } } contract AccQueueQuinaryMaci is AccQueueQuinary, MerkleQuinaryMaci { constructor(uint256 _subDepth) AccQueueQuinary(_subDepth) {} function getZero(uint256 _level) internal view override returns (uint256) { return zeros[_level]; } } contract AccQueueQuinaryBlankSl is AccQueueQuinary, MerkleQuinaryBlankSl { constructor(uint256 _subDepth) AccQueueQuinary(_subDepth) {} function getZero(uint256 _level) internal view override returns (uint256) { return zeros[_level]; } }
Returns the subroot tree (SRT) root. Its value must first be computed using mergeSubRoots./
function getSmallSRTroot() public view returns (uint256) { require(subTreesMerged, "AccQueue: subtrees must be merged first"); return smallSRTroot; }
1,050,960
./partial_match/80001/0x4a06E89BD8833a49Ad6Edf7245F39e8E08497499/sources/Forwarder.sol
Forward a call _target - target address to call _data - call data to be used return whether the call was a success or not return response in bytes if any/
function forwardCall(address _target, bytes calldata _data) external payable returns (bool, bytes memory) { require( msg.sender == caller, "Owner#forwardCall: UNAUTHORIZED_SENDER" ); }
8,805,446
./full_match/1/0xf607014406bc3Fa7aAB224a85A0318b4556e9C28/sources/browser/CryptographIndexLogicV1.sol
Create a new cryptograph edition starting at 0 and return the new index position Only callable by Factory _minter The address of the user wallet that will have the responsability to mint all the editions _editionSize The maximum number of cryptograph that can be minted in the edition return (uint) The new index position in the cryptograph arrayCreate a new indexer for the editionInitializing the indexerAdding the indexer to the mappingIndicate our type as editionInserting the edition and returning the position in the array
function createAGGBMA(address _minter, uint256 _editionSize) external restrictedToFactory() returns(uint){ require(_minter != address(0) && _editionSize != 0, "Minter address and edition size must be greater than 0" ); EditionIndexerProxiedV1 _proxied = new EditionIndexerProxiedV1(indexerLogicCodeIndex, vc); EditionIndexerLogicV1(address(_proxied)).init0(address(this), _minter, _editionSize+1); editionSizes[address(_proxied)] = _editionSize; cryptographType[address(_proxied)] = 1; cryptographs.push(address(_proxied)); return (cryptographs.length - 1); }
3,151,771
/* Copyright 2017 Dharma 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: MIT pragma solidity >=0.4.21 <0.7.0; import "./ContractRegistry.sol"; import "../contracts/lifecycle/Pausable.sol"; import "./SafeMath.sol"; import "./ERC20.sol"; /** * The CreditorProxy is a thin wrapper around the DebtKernel * It implements creditor-driven loans as specified by DIP-1 * * Authors: Bo Henderson <bohendo> & Shivani Gupta <shivgupt> & Dharma Team * DIP: https://github.com/dharmaprotocol/DIPs/issues/1 */ contract CreditorProxy is Pausable { using SafeMath for uint; enum Errors { DEBT_OFFER_CANCELLED, DEBT_OFFER_ALREADY_FILLED, DEBT_OFFER_NON_CONSENSUAL, CREDITOR_BALANCE_OR_ALLOWANCE_INSUFFICIENT } ContractRegistry public contractRegistry; bytes32 constant public NULL_ISSUANCE_HASH = bytes32(0); uint16 constant public EXTERNAL_QUERY_GAS_LIMIT = 8000; mapping (bytes32 => bool) public debtOfferCancelled; mapping (bytes32 => bool) public debtOfferFilled; event LogDebtOfferCancelled( address indexed _creditor, bytes32 indexed _creditorCommitmentHash ); event LogDebtOfferFilled( address indexed _creditor, bytes32 indexed _creditorCommitmentHash, bytes32 indexed _agreementId ); event LogError( uint8 indexed _errorId, address indexed _creditor, bytes32 indexed _creditorCommitmentHash ); constructor (address _contractRegistry) public { contractRegistry = ContractRegistry(_contractRegistry); } /* * Submit debt order to DebtKernel if it is consensual with creditor's request * Creditor signature in arguments is only used internally, * It will not be verified by the Debt Kernel */ function fillDebtOffer( address creditor, address[6] memory orderAddresses, // repayment-router, debtor, uw, tc, p-token, relayer uint[8] memory orderValues, // rr, salt, pa, uwFee, rFee, cFee, dFee, expTime bytes32[1] memory orderBytes32, // tcParams uint8[3] memory signaturesV, // debtV, credV, uwV bytes32[3] memory signaturesR, bytes32[3] memory signaturesS ) public whenNotPaused returns (bytes32 _agreementId) { bytes32 creditorCommitmentHash = getCreditorCommitmentHash( [ creditor, address(contractRegistry.debtKernel()), // debt kernel version orderAddresses[0], // repayment router version orderAddresses[3], // terms contract address orderAddresses[4] // principal token adddress ], [ orderValues[1], // salt orderValues[2], // principal amount orderValues[5], // creditor fee orderValues[7] // commitmentExpirationTimestampInSec ], orderBytes32 // termsContractParameters ); if (debtOfferFilled[creditorCommitmentHash]) { emit LogError(uint8(Errors.DEBT_OFFER_ALREADY_FILLED), creditor, creditorCommitmentHash); return NULL_ISSUANCE_HASH; } if (debtOfferCancelled[creditorCommitmentHash]) { emit LogError(uint8(Errors.DEBT_OFFER_CANCELLED), creditor, creditorCommitmentHash); return NULL_ISSUANCE_HASH; } if (!isValidSignature( creditor, creditorCommitmentHash, signaturesV[1], signaturesR[1], signaturesS[1] )) { emit LogError( uint8(Errors.DEBT_OFFER_NON_CONSENSUAL), creditor, creditorCommitmentHash ); return NULL_ISSUANCE_HASH; } // principal amount + creditor fee uint totalCreditorPayment = orderValues[2].add(orderValues[5]); if (!hasSufficientBalanceAndAllowance( creditor, orderAddresses[4], totalCreditorPayment )) { emit LogError( uint8(Errors.CREDITOR_BALANCE_OR_ALLOWANCE_INSUFFICIENT), creditor, creditorCommitmentHash ); return NULL_ISSUANCE_HASH; } // Transfer principal from creditor to CreditorProxy if (totalCreditorPayment > 0) { require( transferTokensFrom( orderAddresses[4], creditor, address(this), totalCreditorPayment ) ); } // Grant allowance to the TokenTransferProxy for this contract. // Fill debt order with this contract playing the role of creditor bytes32 agreementId = contractRegistry.debtKernel().fillDebtOrder( address(this), orderAddresses, orderValues, orderBytes32, signaturesV, signaturesR, signaturesS ); require(agreementId != NULL_ISSUANCE_HASH); debtOfferFilled[creditorCommitmentHash] = true; // transfer debt token to real creditor contractRegistry.debtToken().transfer(creditor, uint256(agreementId)); emit LogDebtOfferFilled(creditor, creditorCommitmentHash, agreementId); return agreementId; } /** * Allows creditor to prevent a debt offer from being used in the future */ function cancelDebtOffer( address[5] memory commitmentAddresses, uint[4] memory commitmentValues, bytes32[1] memory termsContractParameters ) public whenNotPaused { // sender must be the creditor require(msg.sender == commitmentAddresses[0]); bytes32 creditorCommitmentHash = getCreditorCommitmentHash( commitmentAddresses, commitmentValues, termsContractParameters ); debtOfferCancelled[creditorCommitmentHash] = true; emit LogDebtOfferCancelled(commitmentAddresses[0], creditorCommitmentHash); } //////////////////////// // INTERNAL FUNCTIONS // //////////////////////// /** * Returns the messaged signed by the creditor to indicate their commitment */ function getCreditorCommitmentHash( address[5] memory commitmentAddresses, uint[4] memory commitmentValues, bytes32[1] memory termsContractParameters ) internal pure returns (bytes32 _creditorCommitmentHash) { return keccak256(abi.encodePacked(commitmentAddresses[0], // creditor commitmentAddresses[1], // debt kernel version commitmentAddresses[2], // repayment router version commitmentAddresses[3], // terms contract address commitmentAddresses[4], // principal token address commitmentValues[0], // salt commitmentValues[1], // principal amount commitmentValues[2], // creditor fee commitmentValues[3], // commitmentExpirationTimestampInSec termsContractParameters[0] // terms contract parameters ) ); } /** * Assert that the creditor has a sufficient token balance and has granted the token transfer * proxy contract sufficient allowance to suffice for the principal and creditor fee. */ function hasSufficientBalanceAndAllowance( address creditor, address principalToken, uint totalCreditorPayment ) internal returns (bool _isBalanceAndAllowanceSufficient) { // The allowance that this contract has for a creditor's tokens. uint proxyAllowance = getAllowance(principalToken, creditor, address(this)); uint creditorBalance = getBalance(principalToken, creditor); if (creditorBalance < totalCreditorPayment || proxyAllowance < totalCreditorPayment) { return false; } // The allowance that the token transfer proxy has for this contract's tokens. uint tokenTransferAllowance = getAllowance( principalToken, address(this), address(contractRegistry.tokenTransferProxy()) ); // Ensure the token transfer proxy can transfer tokens from the creditor proxy if (tokenTransferAllowance < totalCreditorPayment) { require(setTokenTransferAllowance(principalToken, totalCreditorPayment)); } return true; } /** * Given a hashed message, a signer's address, and a signature, * returns whether the signature is valid. */ function isValidSignature( address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (bool _valid) { return signer == ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), v, r, s ); } /** * Helper function for querying an address' balance on a given token. */ function getBalance( address token, address owner ) view internal returns (uint _balance) { // Limit gas to prevent reentrancy. return ERC20(token).balanceOf.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner); } /** * Helper function for querying this contract's allowance for transferring the given token. */ function getAllowance( address token, address owner, address granter ) view internal returns (uint _allowance) { // Limit gas to prevent reentrancy. return ERC20(token).allowance.gas(EXTERNAL_QUERY_GAS_LIMIT)( owner, granter ); } /** * Helper function for approving this address' allowance to Dharma's token transfer proxy. */ function setTokenTransferAllowance( address token, uint amount ) internal returns (bool _success) { return ERC20(token).approve( address(contractRegistry.tokenTransferProxy()), amount ); } /** * Helper function for transferring a specified amount of tokens between two parties. */ function transferTokensFrom( address _token, address _from, address _to, uint _amount ) internal returns (bool _success) { return ERC20(_token).transferFrom(_from, _to, _amount); } }
Helper function for querying this contract's allowance for transferring the given token./ Limit gas to prevent reentrancy.
function getAllowance( address token, address owner, address granter ) view internal returns (uint _allowance) { return ERC20(token).allowance.gas(EXTERNAL_QUERY_GAS_LIMIT)( owner, granter ); }
6,438,116
./full_match/43113/0x49E101b346621e5CE74C14DB2d8Be36C751bc4BA/sources/TicketMaketPlace.sol
send the token from the smart contract back to the one who listed it
function cancelProduct(uint256 _ticketId) public isCheck(_ticketId, 1) isCheck(_ticketId, 2) { _transfer(address(this), msg.sender, _ticketId); emit cancelSell(_ticketId, ListProduct[_ticketId].price, msg.sender); delete claimableByAccount[_ticketId]; clenup(_ticketId); }
13,181,684
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "./MockERC721.sol"; contract MockP2P is ReentrancyGuard, Ownable, IERC721Receiver, ERC1155Holder, ERC721Holder { uint256 public feeBps; uint256 public price; MockERC721 public nft; event Swap(address indexed buyer, uint256 tokenId); event SetPrice(uint256 price); constructor( uint256 _price, string memory _name, string memory _symbol ) public { price = _price; nft = new MockERC721(_name, _symbol); emit SetPrice(_price); } /// @dev Updates price. Only callable by owner. function setPrice(uint256 _price) external onlyOwner { price = _price; emit SetPrice(_price); } /// @dev Withdraw trading fees. Only called by owner. function withdraw(uint256 amount) external onlyOwner { payable(msg.sender).transfer(amount == 0 ? address(this).balance : amount); } /// @dev Buy nft from the contract. function buy() external payable nonReentrant { require(msg.value == price, "!not enough or more over"); uint256 tokenId = nft.totalSupply(); nft.mint(msg.sender, tokenId); emit Swap(msg.sender, tokenId); } }
Buy nft from the contract.
function buy() external payable nonReentrant { require(msg.value == price, "!not enough or more over"); uint256 tokenId = nft.totalSupply(); nft.mint(msg.sender, tokenId); emit Swap(msg.sender, tokenId); }
12,803,957
pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant 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 constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; address private myAddress = this; /** * @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 Function must be, but empty. */ function() payable public { } /** * @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)); owner = newOwner; } } contract BBDMigration { function migrateFrom(address _from, uint256 _value) external; } /** Blockchain Board Of Derivatives Token. */ contract BBDToken is StandardToken, Ownable { // Metadata string public constant name = "Blockchain Board Of Derivatives Token"; string public constant symbol = "BBD"; uint256 public constant decimals = 18; string private constant version = '2.0.0'; //Migration information address public migrationAgent; uint256 public totalMigrated; // Events event LogMigrate(address indexed _from, address indexed _to, uint256 _value); // Allow to migrate to next version of contract function migrate(address _beneficiary) onlyOwner external { require(migrationAgent != address(0x0)); require(balances[_beneficiary] > 0); uint256 value = balances[_beneficiary]; balances[msg.sender] = 0; totalSupply = totalSupply.sub(value); totalMigrated = totalMigrated.add(value); BBDMigration(migrationAgent).migrateFrom(_beneficiary, value); emit LogMigrate(_beneficiary, migrationAgent, value); } // Set migration Agent function setMigrationAgent(address _agent) onlyOwner external { migrationAgent = _agent; } } contract MigrationAgent is BBDToken { function migrateFrom(address _from, uint256 _value) external { require(msg.sender == address(0x5CA71Ea65ACB6293e71E62c41B720698b0Aa611C)); balances[_from] = balances[_from].add(_value.mul(100)); totalSupply = totalSupply.add(_value.mul(100)); } }
Allows the current owner to transfer control of the contract to a newOwner. newOwner The address to transfer ownership to./
function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; }
548,062
./partial_match/1/0x322Bb91ADD29446465571bd87Ee167F94996d674/sources/PushinP.sol
FOR GOERLI uniswapV2Pair = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f).createPair(address(this), 0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6); FOR BSCSCAN uniswapV2Pair = IUniswapV2Factory(0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73).createPair(address(this), 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); FOR ETHEREUM
function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } } pragma solidity ^0.8.0; constructor() ERC20("PushinP", "$P") { _mint(msg.sender, (maxSupply * LIQUID_RATE) / MAX_PERCENTAGE); initialized = true; uniswapV2Pair = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f).createPair(address(this), 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); }
15,609,570
./partial_match/1/0x860aCd0f9E6436E15407977602bf11fD39db29f1/sources/Dubai1764.sol
Function to change URI for each tier
function changeDiamondUri(string memory newUri) public onlyOwner { diamondTier = newUri; }
16,136,231
pragma solidity ^0.5.17; interface IERC20 { function TOTALSUPPLY3() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF367(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER903(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE608(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function DECIMALS810() external view returns (uint); //inject NONSTANDARD NAMING function APPROVE172(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM529(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER904(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL612(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD483(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB518(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB518(a, b, "SafeMath: subtraction overflow"); } function SUB518(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 MUL745(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV989(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV989(a, b, "SafeMath: division by zero"); } function DIV989(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD257(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD257(a, b, "SafeMath: modulo by zero"); } function MOD257(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT560(address account) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function TOPAYABLE228(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE839(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER392(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN815(token, abi.encodeWithSelector(token.TRANSFER903.selector, to, value)); } function SAFETRANSFERFROM413(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN815(token, abi.encodeWithSelector(token.TRANSFERFROM529.selector, from, to, value)); } function SAFEAPPROVE740(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE608(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN815(token, abi.encodeWithSelector(token.APPROVE172.selector, spender, value)); } function CALLOPTIONALRETURN815(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT560(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface yVault { function BALANCE390() external view returns (uint); //inject NONSTANDARD NAMING function TOTALSUPPLY3() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF367(address) external view returns (uint256); //inject NONSTANDARD NAMING function DEPOSITALL620() external; //inject NONSTANDARD NAMING function WITHDRAW88(uint _shares) external; //inject NONSTANDARD NAMING function WITHDRAWALL107() external; //inject NONSTANDARD NAMING } interface Controller { function VAULTS407(address) external view returns (address); //inject NONSTANDARD NAMING function STRATEGIES225(address) external view returns (address); //inject NONSTANDARD NAMING function REWARDS983() external view returns (address); //inject NONSTANDARD NAMING } interface Strategy { function WITHDRAWALFEE924() external view returns (uint); //inject NONSTANDARD NAMING } interface GemLike { function APPROVE172(address, uint) external; //inject NONSTANDARD NAMING function TRANSFER903(address, uint) external; //inject NONSTANDARD NAMING function TRANSFERFROM529(address, address, uint) external; //inject NONSTANDARD NAMING function DEPOSIT926() external payable; //inject NONSTANDARD NAMING function WITHDRAW88(uint) external; //inject NONSTANDARD NAMING } interface ManagerLike { function CDPCAN839(address, uint, address) external view returns (uint); //inject NONSTANDARD NAMING function ILKS43(uint) external view returns (bytes32); //inject NONSTANDARD NAMING function OWNS815(uint) external view returns (address); //inject NONSTANDARD NAMING function URNS226(uint) external view returns (address); //inject NONSTANDARD NAMING function VAT838() external view returns (address); //inject NONSTANDARD NAMING function OPEN171(bytes32, address) external returns (uint); //inject NONSTANDARD NAMING function GIVE370(uint, address) external; //inject NONSTANDARD NAMING function CDPALLOW83(uint, address, uint) external; //inject NONSTANDARD NAMING function URNALLOW976(address, uint) external; //inject NONSTANDARD NAMING function FROB668(uint, int, int) external; //inject NONSTANDARD NAMING function FLUX641(uint, address, uint) external; //inject NONSTANDARD NAMING function MOVE446(uint, address, uint) external; //inject NONSTANDARD NAMING function EXIT270(address, uint, address, uint) external; //inject NONSTANDARD NAMING function QUIT464(uint, address) external; //inject NONSTANDARD NAMING function ENTER426(address, uint) external; //inject NONSTANDARD NAMING function SHIFT772(uint, uint) external; //inject NONSTANDARD NAMING } interface VatLike { function CAN946(address, address) external view returns (uint); //inject NONSTANDARD NAMING function ILKS43(bytes32) external view returns (uint, uint, uint, uint, uint); //inject NONSTANDARD NAMING function DAI231(address) external view returns (uint); //inject NONSTANDARD NAMING function URNS226(bytes32, address) external view returns (uint, uint); //inject NONSTANDARD NAMING function FROB668(bytes32, address, address, address, int, int) external; //inject NONSTANDARD NAMING function HOPE968(address) external; //inject NONSTANDARD NAMING function MOVE446(address, address, uint) external; //inject NONSTANDARD NAMING } interface GemJoinLike { function DEC260() external returns (uint); //inject NONSTANDARD NAMING function GEM716() external returns (GemLike); //inject NONSTANDARD NAMING function JOIN168(address, uint) external payable; //inject NONSTANDARD NAMING function EXIT270(address, uint) external; //inject NONSTANDARD NAMING } interface GNTJoinLike { function BAGS888(address) external view returns (address); //inject NONSTANDARD NAMING function MAKE918(address) external returns (address); //inject NONSTANDARD NAMING } interface DaiJoinLike { function VAT838() external returns (VatLike); //inject NONSTANDARD NAMING function DAI231() external returns (GemLike); //inject NONSTANDARD NAMING function JOIN168(address, uint) external payable; //inject NONSTANDARD NAMING function EXIT270(address, uint) external; //inject NONSTANDARD NAMING } interface HopeLike { function HOPE968(address) external; //inject NONSTANDARD NAMING function NOPE673(address) external; //inject NONSTANDARD NAMING } interface EndLike { function FIX740(bytes32) external view returns (uint); //inject NONSTANDARD NAMING function CASH63(bytes32, uint) external; //inject NONSTANDARD NAMING function FREE803(bytes32) external; //inject NONSTANDARD NAMING function PACK489(uint) external; //inject NONSTANDARD NAMING function SKIM635(bytes32, address) external; //inject NONSTANDARD NAMING } interface JugLike { function DRIP111(bytes32) external returns (uint); //inject NONSTANDARD NAMING } interface PotLike { function PIE0(address) external view returns (uint); //inject NONSTANDARD NAMING function DRIP111() external returns (uint); //inject NONSTANDARD NAMING function JOIN168(uint) external; //inject NONSTANDARD NAMING function EXIT270(uint) external; //inject NONSTANDARD NAMING } interface SpotLike { function ILKS43(bytes32) external view returns (address, uint); //inject NONSTANDARD NAMING } interface OSMedianizer { function READ244() external view returns (uint, bool); //inject NONSTANDARD NAMING function FORESIGHT875() external view returns (uint, bool); //inject NONSTANDARD NAMING } interface Uni { function SWAPEXACTTOKENSFORTOKENS833(uint, uint, address[] calldata, address, uint) external; //inject NONSTANDARD NAMING } contract StrategyMKRVaultDAIDelegate { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address constant public token24 = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING address constant public want613 = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING address constant public weth705 = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING address constant public dai951 = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); //inject NONSTANDARD NAMING address public cdp_manager = address(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address public vat = address(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); address public mcd_join_eth_a = address(0x2F0b23f53734252Bda2277357e97e1517d6B042A); address public mcd_join_dai = address(0x9759A6Ac90977b93B58547b4A71c78317f391A28); address public mcd_spot = address(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); address public jug = address(0x19c0976f590D67707E62397C87829d896Dc0f1F1); address constant public eth_price_oracle260 = address(0xCF63089A8aD2a9D8BD6Bb8022f3190EB7e1eD0f1); //inject NONSTANDARD NAMING address constant public yvaultdai641 = address(0xACd43E627e64355f1861cEC6d3a6688B31a6F952); //inject NONSTANDARD NAMING address constant public unirouter43 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING uint public c = 20000; uint public c_safe = 40000; uint constant public c_base986 = 10000; //inject NONSTANDARD NAMING uint public performanceFee = 500; uint constant public performancemax585 = 10000; //inject NONSTANDARD NAMING uint public withdrawalFee = 50; uint constant public withdrawalmax723 = 10000; //inject NONSTANDARD NAMING bytes32 constant public ilk992 = "ETH-A"; //inject NONSTANDARD NAMING address public governance; address public controller; address public strategist; address public harvester; uint public cdpId; constructor(address _controller) public { governance = msg.sender; strategist = 0x2839df1F230dedA9fDDBF1BCB0D4eB1Ee1f7b7d0; harvester = msg.sender; controller = _controller; cdpId = ManagerLike(cdp_manager).OPEN171(ilk992, address(this)); _APPROVEALL294(); } function GETNAME375() external pure returns (string memory) { //inject NONSTANDARD NAMING return "StrategyMKRVaultDAIDelegate"; } function SETSTRATEGIST884(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); strategist = _strategist; } function SETHARVESTER998(address _harvester) external { //inject NONSTANDARD NAMING require(msg.sender == harvester || msg.sender == governance, "!allowed"); harvester = _harvester; } function SETWITHDRAWALFEE880(uint _withdrawalFee) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); withdrawalFee = _withdrawalFee; } function SETPERFORMANCEFEE535(uint _performanceFee) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); performanceFee = _performanceFee; } function SETBORROWCOLLATERALIZATIONRATIO782(uint _c) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); c = _c; } function SETWITHDRAWCOLLATERALIZATIONRATIO286(uint _c_safe) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); c_safe = _c_safe; } // optional function SETMCDVALUE234( //inject NONSTANDARD NAMING address _manager, address _ethAdapter, address _daiAdapter, address _spot, address _jug ) external { require(msg.sender == governance, "!governance"); cdp_manager = _manager; vat = ManagerLike(_manager).VAT838(); mcd_join_eth_a = _ethAdapter; mcd_join_dai = _daiAdapter; mcd_spot = _spot; jug = _jug; } function _APPROVEALL294() internal { //inject NONSTANDARD NAMING IERC20(token24).APPROVE172(mcd_join_eth_a, uint(-1)); IERC20(dai951).APPROVE172(mcd_join_dai, uint(-1)); IERC20(dai951).APPROVE172(yvaultdai641, uint(-1)); IERC20(dai951).APPROVE172(unirouter43, uint(-1)); } function DEPOSIT926() public { //inject NONSTANDARD NAMING uint _token = IERC20(token24).BALANCEOF367(address(this)); if (_token > 0) { uint p = _GETPRICE756(); uint _draw = _token.MUL745(p).MUL745(c_base986).DIV989(c).DIV989(1e18); require(_CHECKDEBTCEILING877(_draw), "debt ceiling is reached!"); _LOCKWETHANDDRAWDAI745(_token, _draw); yVault(yvaultdai641).DEPOSITALL620(); } } function _GETPRICE756() internal view returns (uint p) { //inject NONSTANDARD NAMING (uint _read,) = OSMedianizer(eth_price_oracle260).READ244(); (uint _foresight,) = OSMedianizer(eth_price_oracle260).FORESIGHT875(); p = _foresight < _read ? _foresight : _read; } function _CHECKDEBTCEILING877(uint _amt) internal view returns (bool) { //inject NONSTANDARD NAMING (,,,uint _line,) = VatLike(vat).ILKS43(ilk992); uint _debt = GETTOTALDEBTAMOUNT152().ADD483(_amt); if (_line.DIV989(1e27) < _debt) { return false; } return true; } function _LOCKWETHANDDRAWDAI745(uint wad, uint wadD) internal { //inject NONSTANDARD NAMING address urn = ManagerLike(cdp_manager).URNS226(cdpId); GemJoinLike(mcd_join_eth_a).JOIN168(urn, wad); ManagerLike(cdp_manager).FROB668(cdpId, TOINT917(wad), _GETDRAWDART399(urn, wadD)); ManagerLike(cdp_manager).MOVE446(cdpId, address(this), wadD.MUL745(1e27)); if (VatLike(vat).CAN946(address(this), address(mcd_join_dai)) == 0) { VatLike(vat).HOPE968(mcd_join_dai); } DaiJoinLike(mcd_join_dai).EXIT270(address(this), wadD); } function _GETDRAWDART399(address urn, uint wad) internal returns (int dart) { //inject NONSTANDARD NAMING uint rate = JugLike(jug).DRIP111(ilk992); uint _dai = VatLike(vat).DAI231(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (_dai < wad.MUL745(1e27)) { dart = TOINT917(wad.MUL745(1e27).SUB518(_dai).DIV989(rate)); dart = uint(dart).MUL745(rate) < wad.MUL745(1e27) ? dart + 1 : dart; } } function TOINT917(uint x) internal pure returns (int y) { //inject NONSTANDARD NAMING y = int(x); require(y >= 0, "int-overflow"); } // Controller only function for creating additional rewards from dust function WITHDRAW88(IERC20 _asset) external returns (uint balance) { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); require(want613 != address(_asset), "want"); require(dai951 != address(_asset), "dai"); balance = _asset.BALANCEOF367(address(this)); _asset.SAFETRANSFER392(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function WITHDRAW88(uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); uint _balance = IERC20(want613).BALANCEOF367(address(this)); if (_balance < _amount) { _amount = _WITHDRAWSOME510(_amount.SUB518(_balance)); _amount = _amount.ADD483(_balance); } uint _fee = _amount.MUL745(withdrawalFee).DIV989(withdrawalmax723); IERC20(want613).SAFETRANSFER392(Controller(controller).REWARDS983(), _fee); address _vault = Controller(controller).VAULTS407(address(want613)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want613).SAFETRANSFER392(_vault, _amount.SUB518(_fee)); } function SHOULDREBALANCE692() external view returns (bool) { //inject NONSTANDARD NAMING return GETMVAULTRATIO318() < c_safe.MUL745(1e2); } function REBALANCE223() external { //inject NONSTANDARD NAMING uint safe = c_safe.MUL745(1e2); if (GETMVAULTRATIO318() < safe) { uint d = GETTOTALDEBTAMOUNT152(); uint diff = safe.SUB518(GETMVAULTRATIO318()); uint free = d.MUL745(diff).DIV989(safe); uint p = _GETPRICE756(); _WIPE82(_WITHDRAWDAI331(free.MUL745(p).DIV989(1e18))); } } function FORCEREBALANCE268(uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); uint p = _GETPRICE756(); _WIPE82(_WITHDRAWDAI331(_amount.MUL745(p).DIV989(1e18))); } function _WITHDRAWSOME510(uint256 _amount) internal returns (uint) { //inject NONSTANDARD NAMING uint p = _GETPRICE756(); if (GETMVAULTRATIONEXT436(_amount) < c_safe.MUL745(1e2)) { _WIPE82(_WITHDRAWDAI331(_amount.MUL745(p).DIV989(1e18))); } // _amount in want _FREEWETH537(_amount); return _amount; } function _FREEWETH537(uint wad) internal { //inject NONSTANDARD NAMING ManagerLike(cdp_manager).FROB668(cdpId, -TOINT917(wad), 0); ManagerLike(cdp_manager).FLUX641(cdpId, address(this), wad); GemJoinLike(mcd_join_eth_a).EXIT270(address(this), wad); } function _WIPE82(uint wad) internal { //inject NONSTANDARD NAMING // wad in DAI address urn = ManagerLike(cdp_manager).URNS226(cdpId); DaiJoinLike(mcd_join_dai).JOIN168(urn, wad); ManagerLike(cdp_manager).FROB668(cdpId, 0, _GETWIPEDART74(VatLike(vat).DAI231(urn), urn)); } function _GETWIPEDART74( //inject NONSTANDARD NAMING uint _dai, address urn ) internal view returns (int dart) { (, uint rate,,,) = VatLike(vat).ILKS43(ilk992); (, uint art) = VatLike(vat).URNS226(ilk992, urn); dart = TOINT917(_dai / rate); dart = uint(dart) <= art ? - dart : - TOINT917(art); } // Withdraw all funds, normally used when migrating strategies function WITHDRAWALL107() external returns (uint balance) { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); _WITHDRAWALL392(); _SWAP138(IERC20(dai951).BALANCEOF367(address(this))); balance = IERC20(want613).BALANCEOF367(address(this)); address _vault = Controller(controller).VAULTS407(address(want613)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want613).SAFETRANSFER392(_vault, balance); } function _WITHDRAWALL392() internal { //inject NONSTANDARD NAMING yVault(yvaultdai641).WITHDRAWALL107(); // get Dai _WIPE82(GETTOTALDEBTAMOUNT152().ADD483(1)); // in case of edge case _FREEWETH537(BALANCEOFMVAULT489()); } function BALANCEOF367() public view returns (uint) { //inject NONSTANDARD NAMING return BALANCEOFWANT874() .ADD483(BALANCEOFMVAULT489()); } function BALANCEOFWANT874() public view returns (uint) { //inject NONSTANDARD NAMING return IERC20(want613).BALANCEOF367(address(this)); } function BALANCEOFMVAULT489() public view returns (uint) { //inject NONSTANDARD NAMING uint ink; address urnHandler = ManagerLike(cdp_manager).URNS226(cdpId); (ink,) = VatLike(vat).URNS226(ilk992, urnHandler); return ink; } function HARVEST338() public { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == harvester || msg.sender == governance, "!authorized"); uint v = GETUNDERLYINGDAI934(yVault(yvaultdai641).BALANCEOF367(address(this))); uint d = GETTOTALDEBTAMOUNT152(); require(v > d, "profit is not realized yet!"); uint profit = v.SUB518(d); _SWAP138(_WITHDRAWDAI331(profit)); uint _want = IERC20(want613).BALANCEOF367(address(this)); if (_want > 0) { uint _fee = _want.MUL745(performanceFee).DIV989(performancemax585); IERC20(want613).SAFETRANSFER392(strategist, _fee); _want = _want.SUB518(_fee); } DEPOSIT926(); } function PAYBACK925(uint _amount) public { //inject NONSTANDARD NAMING // _amount in Dai _WIPE82(_WITHDRAWDAI331(_amount)); } function GETTOTALDEBTAMOUNT152() public view returns (uint) { //inject NONSTANDARD NAMING uint art; uint rate; address urnHandler = ManagerLike(cdp_manager).URNS226(cdpId); (,art) = VatLike(vat).URNS226(ilk992, urnHandler); (,rate,,,) = VatLike(vat).ILKS43(ilk992); return art.MUL745(rate).DIV989(1e27); } function GETMVAULTRATIONEXT436(uint amount) public view returns (uint) { //inject NONSTANDARD NAMING uint spot; // ray uint liquidationRatio; // ray uint denominator = GETTOTALDEBTAMOUNT152(); (,,spot,,) = VatLike(vat).ILKS43(ilk992); (,liquidationRatio) = SpotLike(mcd_spot).ILKS43(ilk992); uint delayedCPrice = spot.MUL745(liquidationRatio).DIV989(1e27); // ray uint numerator = (BALANCEOFMVAULT489().SUB518(amount)).MUL745(delayedCPrice).DIV989(1e18); // ray return numerator.DIV989(denominator).DIV989(1e3); } function GETMVAULTRATIO318() public view returns (uint) { //inject NONSTANDARD NAMING uint spot; // ray uint liquidationRatio; // ray uint denominator = GETTOTALDEBTAMOUNT152(); (,,spot,,) = VatLike(vat).ILKS43(ilk992); (,liquidationRatio) = SpotLike(mcd_spot).ILKS43(ilk992); uint delayedCPrice = spot.MUL745(liquidationRatio).DIV989(1e27); // ray uint numerator = BALANCEOFMVAULT489().MUL745(delayedCPrice).DIV989(1e18); // ray return numerator.DIV989(denominator).DIV989(1e3); } function GETUNDERLYINGWITHDRAWALFEE628() public view returns (uint) { //inject NONSTANDARD NAMING address _strategy = Controller(controller).STRATEGIES225(dai951); return Strategy(_strategy).WITHDRAWALFEE924(); } function GETUNDERLYINGDAI934(uint _shares) public view returns (uint) { //inject NONSTANDARD NAMING return (yVault(yvaultdai641).BALANCE390()) .MUL745(_shares).DIV989(yVault(yvaultdai641).TOTALSUPPLY3()) .MUL745(withdrawalmax723.SUB518(GETUNDERLYINGWITHDRAWALFEE628())) .DIV989(withdrawalmax723); } function _WITHDRAWDAI331(uint _amount) internal returns (uint) { //inject NONSTANDARD NAMING uint _shares = _amount .MUL745(yVault(yvaultdai641).TOTALSUPPLY3()) .DIV989(yVault(yvaultdai641).BALANCE390()) .MUL745(withdrawalmax723) .DIV989(withdrawalmax723.SUB518(GETUNDERLYINGWITHDRAWALFEE628())); yVault(yvaultdai641).WITHDRAW88(_shares); return IERC20(dai951).BALANCEOF367(address(this)); } function _SWAP138(uint _amountIn) internal { //inject NONSTANDARD NAMING address[] memory path = new address[](2); path[0] = address(dai951); path[1] = address(want613); Uni(unirouter43).SWAPEXACTTOKENSFORTOKENS833(_amountIn, 0, path, address(this), now.ADD483(1 days)); } function SETGOVERNANCE389(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function SETCONTROLLER804(address _controller) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); controller = _controller; } }
inject NONSTANDARD NAMING
function _CHECKDEBTCEILING877(uint _amt) internal view returns (bool) {
12,996,885
./partial_match/42/0xA106A93cb03748A678F21e44ddA50420136582ae/sources/MasterchefDelegator.sol
overflow is desired, casting never truncates cumulative price is in (uq112x112 price seconds) units so we simply wrap it after division by time elapsed
function updateTokenOracle(TokenPairInfo storage _pairInfo) internal returns (FixedPoint.uq112x112 memory _price) { FixedPoint.uq112x112 memory cachedPrice = _pairInfo.price; if(cachedPrice._x > 0 && _pairInfo.lastPriceUpdateHeight.sub(block.number) <= updateTokenPriceTerm){ return cachedPrice; } (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(_pairInfo.tokenToEthSwap)); if(_pairInfo.isFirstTokenEth){ _price = FixedPoint.uq112x112(uint224(price1Cumulative.sub(_pairInfo.priceCumulativeLast).div(timeElapsed))); _pairInfo.priceCumulativeLast = price1Cumulative; } else{ _price = FixedPoint.uq112x112(uint224(price0Cumulative.sub(_pairInfo.priceCumulativeLast).div(timeElapsed))); _pairInfo.priceCumulativeLast = price0Cumulative; } _pairInfo.price = _price; _pairInfo.lastPriceUpdateHeight = block.number; _pairInfo.blockTimestampLast = blockTimestamp; }
3,313,460
/* Copyright 2018 RigoBlock, Rigo Investment Sagl. 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.0; import { Owned } from "../../../utils/Owned/Owned.sol"; import { ExchangesAuthorityFace } from "./ExchangesAuthorityFace.sol"; /// @title Exchanges Authority - A helper contract for the exchange adapters. /// @author Gabriele Rigo - <[email protected]> // solhint-disable-next-line contract ExchangesAuthority is Owned, ExchangesAuthorityFace { BuildingBlocks public blocks; Type public types; mapping (address => Account) public accounts; struct List { address target; } struct Type { string types; List[] list; } struct Group { bool whitelister; bool exchange; bool asset; bool authority; bool wrapper; bool proxy; } struct Account { address account; bool authorized; mapping (bool => Group) groups; //mapping account to bool authorized to bool group } struct BuildingBlocks { address exchangeEventful; address sigVerifier; address casper; mapping (address => bool) initialized; mapping (address => address) adapter; // Mapping of exchange => method => approved mapping (address => mapping (bytes4 => bool)) allowedMethods; mapping (address => mapping (address => bool)) allowedTokens; mapping (address => mapping (address => bool)) allowedWrappers; } /* * EVENTS */ event AuthoritySet(address indexed authority); event WhitelisterSet(address indexed whitelister); event WhitelistedAsset(address indexed asset, bool approved); event WhitelistedExchange(address indexed exchange, bool approved); event WhitelistedWrapper(address indexed wrapper, bool approved); event WhitelistedProxy(address indexed proxy, bool approved); event WhitelistedMethod(bytes4 indexed method, address indexed adapter, bool approved); event NewSigVerifier(address indexed sigVerifier); event NewExchangeEventful(address indexed exchangeEventful); event NewCasper(address indexed casper); /* * MODIFIERS */ modifier onlyAdmin { require(msg.sender == owner || isWhitelister(msg.sender)); _; } modifier onlyWhitelister { require(isWhitelister(msg.sender)); _; } /* * CORE FUNCTIONS */ /// @dev Allows the owner to whitelist an authority /// @param _authority Address of the authority /// @param _isWhitelisted Bool whitelisted function setAuthority(address _authority, bool _isWhitelisted) external onlyOwner { setAuthorityInternal(_authority, _isWhitelisted); } /// @dev Allows the owner to whitelist a whitelister /// @param _whitelister Address of the whitelister /// @param _isWhitelisted Bool whitelisted function setWhitelister(address _whitelister, bool _isWhitelisted) external onlyOwner { setWhitelisterInternal(_whitelister, _isWhitelisted); } /// @dev Allows a whitelister to whitelist an asset /// @param _asset Address of the token /// @param _isWhitelisted Bool whitelisted function whitelistAsset(address _asset, bool _isWhitelisted) external onlyWhitelister { accounts[_asset].account = _asset; accounts[_asset].authorized = _isWhitelisted; accounts[_asset].groups[_isWhitelisted].asset = _isWhitelisted; types.list.push(List(_asset)); emit WhitelistedAsset(_asset, _isWhitelisted); } /// @dev Allows a whitelister to whitelist an exchange /// @param _exchange Address of the target exchange /// @param _isWhitelisted Bool whitelisted function whitelistExchange(address _exchange, bool _isWhitelisted) external onlyWhitelister { accounts[_exchange].account = _exchange; accounts[_exchange].authorized = _isWhitelisted; accounts[_exchange].groups[_isWhitelisted].exchange = _isWhitelisted; types.list.push(List(_exchange)); emit WhitelistedExchange(_exchange, _isWhitelisted); } /// @dev Allows a whitelister to whitelist an token wrapper /// @param _wrapper Address of the target token wrapper /// @param _isWhitelisted Bool whitelisted function whitelistWrapper(address _wrapper, bool _isWhitelisted) external onlyWhitelister { accounts[_wrapper].account = _wrapper; accounts[_wrapper].authorized = _isWhitelisted; accounts[_wrapper].groups[_isWhitelisted].wrapper = _isWhitelisted; types.list.push(List(_wrapper)); emit WhitelistedWrapper(_wrapper, _isWhitelisted); } /// @dev Allows a whitelister to whitelist a tokenTransferProxy /// @param _tokenTransferProxy Address of the proxy /// @param _isWhitelisted Bool whitelisted function whitelistTokenTransferProxy( address _tokenTransferProxy, bool _isWhitelisted) external onlyWhitelister { accounts[_tokenTransferProxy].account = _tokenTransferProxy; accounts[_tokenTransferProxy].authorized = _isWhitelisted; accounts[_tokenTransferProxy].groups[_isWhitelisted].proxy = _isWhitelisted; types.list.push(List(_tokenTransferProxy)); emit WhitelistedProxy(_tokenTransferProxy, _isWhitelisted); } /// @dev Allows a whitelister to enable trading on a particular exchange /// @param _asset Address of the token /// @param _exchange Address of the exchange /// @param _isWhitelisted Bool whitelisted function whitelistAssetOnExchange( address _asset, address _exchange, bool _isWhitelisted) external onlyAdmin { blocks.allowedTokens[_exchange][_asset] = _isWhitelisted; emit WhitelistedAsset(_asset, _isWhitelisted); } /// @dev Allows a whitelister to enable assiciate wrappers to a token /// @param _token Address of the token /// @param _wrapper Address of the exchange /// @param _isWhitelisted Bool whitelisted function whitelistTokenOnWrapper(address _token, address _wrapper, bool _isWhitelisted) external onlyAdmin { blocks.allowedWrappers[_wrapper][_token] = _isWhitelisted; emit WhitelistedAsset(_token, _isWhitelisted); } /// @dev Allows an admin to whitelist a factory /// @param _method Hex of the function ABI /// @param _isWhitelisted Bool whitelisted function whitelistMethod( bytes4 _method, address _adapter, bool _isWhitelisted) external onlyAdmin { blocks.allowedMethods[_adapter][_method] = _isWhitelisted; emit WhitelistedMethod(_method, _adapter, _isWhitelisted); } /// @dev Allows the owner to set the signature verifier /// @param _sigVerifier Address of the verifier contract function setSignatureVerifier(address _sigVerifier) external onlyOwner { blocks.sigVerifier = _sigVerifier; emit NewSigVerifier(blocks.sigVerifier); } /// @dev Allows the owner to set the exchange eventful /// @param _exchangeEventful Address of the exchange logs contract function setExchangeEventful(address _exchangeEventful) external onlyOwner { blocks.exchangeEventful = _exchangeEventful; emit NewExchangeEventful(blocks.exchangeEventful); } /// @dev Allows the owner to associate an exchange to its adapter /// @param _exchange Address of the exchange /// @param _adapter Address of the adapter function setExchangeAdapter(address _exchange, address _adapter) external onlyOwner { require(_exchange != _adapter); blocks.adapter[_exchange] = _adapter; } /// @dev Allows the owner to set the casper contract /// @param _casper Address of the casper contract function setCasper(address _casper) external onlyOwner { blocks.casper = _casper; blocks.initialized[_casper] = true; emit NewCasper(blocks.casper); } /* * CONSTANT PUBLIC FUNCTIONS */ /// @dev Provides whether an address is an authority /// @param _authority Address of the target authority /// @return Bool is whitelisted function isAuthority(address _authority) external view returns (bool) { return accounts[_authority].groups[true].authority; } /// @dev Provides whether an asset is whitelisted /// @param _asset Address of the target asset /// @return Bool is whitelisted function isWhitelistedAsset(address _asset) external view returns (bool) { return accounts[_asset].groups[true].asset; } /// @dev Provides whether an exchange is whitelisted /// @param _exchange Address of the target exchange /// @return Bool is whitelisted function isWhitelistedExchange(address _exchange) external view returns (bool) { return accounts[_exchange].groups[true].exchange; } /// @dev Provides whether a token wrapper is whitelisted /// @param _wrapper Address of the target exchange /// @return Bool is whitelisted function isWhitelistedWrapper(address _wrapper) external view returns (bool) { return accounts[_wrapper].groups[true].wrapper; } /// @dev Provides whether a proxy is whitelisted /// @param _tokenTransferProxy Address of the proxy /// @return Bool is whitelisted function isWhitelistedProxy(address _tokenTransferProxy) external view returns (bool) { return accounts[_tokenTransferProxy].groups[true].proxy; } /// @dev Provides the address of the exchange adapter /// @param _exchange Address of the exchange /// @return Address of the adapter function getExchangeAdapter(address _exchange) external view returns (address) { return blocks.adapter[_exchange]; } /// @dev Provides the address of the signature verifier /// @return Address of the verifier function getSigVerifier() external view returns (address) { return blocks.sigVerifier; } /// @dev Checkes whether a token is allowed on an exchange /// @param _token Address of the token /// @param _exchange Address of the exchange /// @return Bool the token is whitelisted on the exchange function canTradeTokenOnExchange(address _token, address _exchange) external view returns (bool) { return blocks.allowedTokens[_exchange][_token]; } /// @dev Checkes whether a token is allowed on a wrapper /// @param _token Address of the token /// @param _wrapper Address of the token wrapper /// @return Bool the token is whitelisted on the exchange function canWrapTokenOnWrapper(address _token, address _wrapper) external view returns (bool) { return blocks.allowedWrappers[_wrapper][_token]; } /// @dev Checkes whether a method is allowed on an exchange /// @param _method Bytes of the function signature /// @param _adapter Address of the exchange /// @return Bool the method is allowed function isMethodAllowed(bytes4 _method, address _adapter) external view returns (bool) { return blocks.allowedMethods[_adapter][_method]; } /// @dev Checkes whether casper has been inizialized /// @return Bool the casper contract has been initialized function isCasperInitialized() external view returns (bool) { address casper = blocks.casper; return blocks.initialized[casper]; } /// @dev Provides the address of the casper contract /// @return Address of the casper contract function getCasper() external view returns (address) { return blocks.casper; } /* * INTERNAL FUNCTIONS */ /// @dev Allows to whitelist an authority /// @param _authority Address of the authority /// @param _isWhitelisted Bool whitelisted function setAuthorityInternal( address _authority, bool _isWhitelisted) internal { accounts[_authority].account = _authority; accounts[_authority].authorized = _isWhitelisted; accounts[_authority].groups[_isWhitelisted].authority = _isWhitelisted; setWhitelisterInternal(_authority, _isWhitelisted); types.list.push(List(_authority)); emit AuthoritySet(_authority); } /// @dev Allows the owner to whitelist a whitelister /// @param _whitelister Address of the whitelister /// @param _isWhitelisted Bool whitelisted function setWhitelisterInternal( address _whitelister, bool _isWhitelisted) internal { accounts[_whitelister].account = _whitelister; accounts[_whitelister].authorized = _isWhitelisted; accounts[_whitelister].groups[_isWhitelisted].whitelister = _isWhitelisted; types.list.push(List(_whitelister)); emit WhitelisterSet(_whitelister); } /// @dev Provides whether an address is whitelister /// @param _whitelister Address of the target whitelister /// @return Bool is whitelisted function isWhitelister(address _whitelister) internal view returns (bool) { return accounts[_whitelister].groups[true].whitelister; } }
Allows a whitelister to whitelist an token wrapper _wrapper Address of the target token wrapper _isWhitelisted Bool whitelisted
function whitelistWrapper(address _wrapper, bool _isWhitelisted) external onlyWhitelister { accounts[_wrapper].account = _wrapper; accounts[_wrapper].authorized = _isWhitelisted; accounts[_wrapper].groups[_isWhitelisted].wrapper = _isWhitelisted; types.list.push(List(_wrapper)); emit WhitelistedWrapper(_wrapper, _isWhitelisted); }
980,955
/* Copyright 2017 Dharma 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: MIT pragma solidity >=0.4.21 <0.7.0; import { PermissionsLib, PermissionEvents } from "./PermissionsLib.sol"; import "./SafeMath.sol"; import "./Pausable.sol"; /** * The DebtRegistry stores the parameters and beneficiaries of all debt agreements in * Dharma protocol. It authorizes a limited number of agents to * perform mutations on it -- those agents can be changed at any * time by the contract's owner. * * Author: Nadav Hollander -- Github: nadavhollander */ contract DebtRegistry is Ownable,Pausable, PermissionEvents { using SafeMath for uint; using PermissionsLib for PermissionsLib.Permissions; struct Entry { address version; address beneficiary; address underwriter; uint underwriterRiskRating; address termsContract; bytes32 termsContractParameters; uint issuanceBlockTimestamp; } // Primary registry mapping agreement IDs to their corresponding entries mapping (bytes32 => Entry) internal registry; // Maps debtor addresses to a list of their debts' agreement IDs mapping (address => bytes32[]) internal debtorToDebts; PermissionsLib.Permissions internal entryInsertPermissions; PermissionsLib.Permissions internal entryEditPermissions; string public constant INSERT_CONTEXT = "debt-registry-insert"; string public constant EDIT_CONTEXT = "debt-registry-edit"; event LogInsertEntry( bytes32 indexed agreementId, address indexed beneficiary, address indexed underwriter, uint underwriterRiskRating, address termsContract, bytes32 termsContractParameters ); event LogModifyEntryBeneficiary( bytes32 indexed agreementId, address indexed previousBeneficiary, address indexed newBeneficiary ); modifier onlyAuthorizedToInsert() { require(entryInsertPermissions.isAuthorized(msg.sender)); _; } modifier onlyAuthorizedToEdit() { require(entryEditPermissions.isAuthorized(msg.sender)); _; } modifier onlyExtantEntry(bytes32 agreementId) { require(doesEntryExist(agreementId)); _; } modifier nonNullBeneficiary(address beneficiary) { require(beneficiary != address(0)); _; } /* Ensures an entry with the specified agreement ID exists within the debt registry. */ function doesEntryExist(bytes32 agreementId) public view returns (bool exists) { return registry[agreementId].beneficiary != address(0); } /** * Inserts a new entry into the registry, if the entry is valid and sender is * authorized to make 'insert' mutations to the registry. */ function insert( address _version, address _beneficiary, address _debtor, address _underwriter, uint _underwriterRiskRating, address _termsContract, bytes32 _termsContractParameters, uint _salt ) public onlyAuthorizedToInsert whenNotPaused nonNullBeneficiary(_beneficiary) returns (bytes32 _agreementId) { Entry memory entry = Entry( _version, _beneficiary, _underwriter, _underwriterRiskRating, _termsContract, _termsContractParameters, block.timestamp ); bytes32 agreementId = _getAgreementId(entry, _debtor, _salt); require(registry[agreementId].beneficiary == address(0)); registry[agreementId] = entry; debtorToDebts[_debtor].push(agreementId); emit LogInsertEntry( agreementId, entry.beneficiary, entry.underwriter, entry.underwriterRiskRating, entry.termsContract, entry.termsContractParameters ); return agreementId; } /** * Modifies the beneficiary of a debt issuance, if the sender * is authorized to make 'modifyBeneficiary' mutations to * the registry. */ function modifyBeneficiary(bytes32 agreementId, address newBeneficiary) public onlyAuthorizedToEdit whenNotPaused onlyExtantEntry(agreementId) nonNullBeneficiary(newBeneficiary) { address previousBeneficiary = registry[agreementId].beneficiary; registry[agreementId].beneficiary = newBeneficiary; emit LogModifyEntryBeneficiary( agreementId, previousBeneficiary, newBeneficiary ); } /** * Adds an address to the list of agents authorized * to make 'insert' mutations to the registry. */ function addAuthorizedInsertAgent(address agent) public onlyOwner { entryInsertPermissions.authorize(agent, INSERT_CONTEXT); } /** * Adds an address to the list of agents authorized * to make 'modifyBeneficiary' mutations to the registry. */ function addAuthorizedEditAgent(address agent) public onlyOwner { entryEditPermissions.authorize(agent, EDIT_CONTEXT); } /** * Removes an address from the list of agents authorized * to make 'insert' mutations to the registry. */ function revokeInsertAgentAuthorization(address agent) public onlyOwner { entryInsertPermissions.revokeAuthorization(agent, INSERT_CONTEXT); } /** * Removes an address from the list of agents authorized * to make 'modifyBeneficiary' mutations to the registry. */ function revokeEditAgentAuthorization(address agent) public onlyOwner { entryEditPermissions.revokeAuthorization(agent, EDIT_CONTEXT); } /** * Returns the parameters of a debt issuance in the registry. * * TODO(kayvon): protect this function with our `onlyExtantEntry` modifier once the restriction * on the size of the call stack has been addressed. */ function get(bytes32 agreementId) public view returns(address, address, address, uint, address, bytes32, uint) { return ( registry[agreementId].version, registry[agreementId].beneficiary, registry[agreementId].underwriter, registry[agreementId].underwriterRiskRating, registry[agreementId].termsContract, registry[agreementId].termsContractParameters, registry[agreementId].issuanceBlockTimestamp ); } /** * Returns the beneficiary of a given issuance */ function getBeneficiary(bytes32 agreementId) public view onlyExtantEntry(agreementId) returns(address) { return registry[agreementId].beneficiary; } /** * Returns the terms contract address of a given issuance */ function getTermsContract(bytes32 agreementId) public view onlyExtantEntry(agreementId) returns (address) { return registry[agreementId].termsContract; } /** * Returns the terms contract parameters of a given issuance */ function getTermsContractParameters(bytes32 agreementId) public view onlyExtantEntry(agreementId) returns (bytes32) { return registry[agreementId].termsContractParameters; } /** * Returns a tuple of the terms contract and its associated parameters * for a given issuance */ function getTerms(bytes32 agreementId) public view onlyExtantEntry(agreementId) returns(address, bytes32) { return ( registry[agreementId].termsContract, registry[agreementId].termsContractParameters ); } /** * Returns the timestamp of the block at which a debt agreement was issued. */ function getIssuanceBlockTimestamp(bytes32 agreementId) public view onlyExtantEntry(agreementId) returns (uint timestamp) { return registry[agreementId].issuanceBlockTimestamp; } /** * Returns the list of agents authorized to make 'insert' mutations */ function getAuthorizedInsertAgents() public view returns(address[] memory) { return entryInsertPermissions.getAuthorizedAgents(); } /** * Returns the list of agents authorized to make 'modifyBeneficiary' mutations */ function getAuthorizedEditAgents() public view returns(address[] memory) { return entryEditPermissions.getAuthorizedAgents(); } /** * Returns the list of debt agreements a debtor is party to, * with each debt agreement listed by agreement ID. */ function getDebtorsDebts(address debtor) public view returns(bytes32[] memory) { return debtorToDebts[debtor]; } /** * Helper function for computing the hash of a given issuance, * and, in turn, its agreementId */ function _getAgreementId(Entry memory _entry, address _debtor, uint _salt) internal pure returns(bytes32) { return keccak256(abi.encode(_entry.version, _debtor, _entry.underwriter, _entry.underwriterRiskRating, _entry.termsContract, _entry.termsContractParameters, _salt)); } }
Adds an address to the list of agents authorized to make 'modifyBeneficiary' mutations to the registry./
function addAuthorizedEditAgent(address agent) public onlyOwner { entryEditPermissions.authorize(agent, EDIT_CONTEXT); }
1,013,232
// SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "../../fixins/FixinERC1155Spender.sol"; import "../../storage/LibCommonNftOrdersStorage.sol"; import "../../storage/LibERC1155OrdersStorage.sol"; import "../interfaces/IERC1155OrdersFeature.sol"; import "../libs/LibNFTOrder.sol"; import "../libs/LibSignature.sol"; import "./NFTOrders.sol"; /// @dev Feature for interacting with ERC1155 orders. contract ERC1155OrdersFeature is IERC1155OrdersFeature, FixinERC1155Spender, NFTOrders { using LibNFTOrder for LibNFTOrder.ERC1155SellOrder; using LibNFTOrder for LibNFTOrder.ERC1155BuyOrder; using LibNFTOrder for LibNFTOrder.NFTSellOrder; using LibNFTOrder for LibNFTOrder.NFTBuyOrder; /// @dev The magic return value indicating the success of a `onERC1155Received`. bytes4 private constant ERC1155_RECEIVED_MAGIC_BYTES = this.onERC1155Received.selector; constructor(IEtherToken weth) NFTOrders(weth) { } /// @dev Sells an ERC1155 asset to fill the given order. /// @param buyOrder The ERC1155 buy order. /// @param signature The order signature from the maker. /// @param erc1155TokenId The ID of the ERC1155 asset being /// sold. If the given order specifies properties, /// the asset must satisfy those properties. Otherwise, /// it must equal the tokenId in the order. /// @param erc1155SellAmount The amount of the ERC1155 asset /// to sell. /// @param unwrapNativeToken If this parameter is true and the /// ERC20 token of the order is e.g. WETH, unwraps the /// token before transferring it to the taker. /// @param callbackData If this parameter is non-zero, invokes /// `zeroExERC1155OrderCallback` on `msg.sender` after /// the ERC20 tokens have been transferred to `msg.sender` /// but before transferring the ERC1155 asset to the buyer. function sellERC1155( LibNFTOrder.ERC1155BuyOrder memory buyOrder, LibSignature.Signature memory signature, uint256 erc1155TokenId, uint128 erc1155SellAmount, bool unwrapNativeToken, bytes memory callbackData ) public override { _sellERC1155( buyOrder, signature, SellParams( erc1155SellAmount, erc1155TokenId, unwrapNativeToken, msg.sender, // taker msg.sender, // owner callbackData ) ); } /// @dev Buys an ERC1155 asset by filling the given order. /// @param sellOrder The ERC1155 sell order. /// @param signature The order signature. /// @param erc1155BuyAmount The amount of the ERC1155 asset /// to buy. function buyERC1155( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, uint128 erc1155BuyAmount ) public override payable { uint256 ethBalanceBefore = address(this).balance - msg.value; _buyERC1155(sellOrder, signature, erc1155BuyAmount); if (address(this).balance != ethBalanceBefore) { // Refund _transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore); } } function buyERC1155Ex( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, address taker, uint128 erc1155BuyAmount, bytes memory callbackData ) public override payable { uint256 ethBalanceBefore = address(this).balance - msg.value; _buyERC1155Ex( sellOrder, signature, BuyParams( erc1155BuyAmount, msg.value, taker, callbackData ) ); if (address(this).balance != ethBalanceBefore) { // Refund _transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore); } } /// @dev Cancel a single ERC1155 order by its nonce. The caller /// should be the maker of the order. Silently succeeds if /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonce The order nonce. function cancelERC1155Order(uint256 orderNonce) public override { // The bitvector is indexed by the lower 8 bits of the nonce. uint256 flag = 1 << (orderNonce & 255); // Update order cancellation bit vector to indicate that the order // has been cancelled/filled by setting the designated bit to 1. LibERC1155OrdersStorage.getStorage().orderCancellationByMaker [msg.sender][uint248(orderNonce >> 8)] |= flag; emit ERC1155OrderCancelled(msg.sender, orderNonce); } /// @dev Cancel multiple ERC1155 orders by their nonces. The caller /// should be the maker of the orders. Silently succeeds if /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonces The order nonces. function batchCancelERC1155Orders(uint256[] calldata orderNonces) external override { for (uint256 i = 0; i < orderNonces.length; i++) { cancelERC1155Order(orderNonces[i]); } } /// @dev Buys multiple ERC1155 assets by filling the /// given orders. /// @param sellOrders The ERC1155 sell orders. /// @param signatures The order signatures. /// @param erc1155FillAmounts The amounts of the ERC1155 assets /// to buy for each order. /// @param revertIfIncomplete If true, reverts if this /// function fails to fill any individual order. /// @return successes An array of booleans corresponding to whether /// each order in `orders` was successfully filled. function batchBuyERC1155s( LibNFTOrder.ERC1155SellOrder[] memory sellOrders, LibSignature.Signature[] memory signatures, uint128[] calldata erc1155FillAmounts, bool revertIfIncomplete ) public override payable returns (bool[] memory successes) { uint256 length = sellOrders.length; require( length == signatures.length && length == erc1155FillAmounts.length, "ERC1155OrdersFeature::batchBuyERC1155s/ARRAY_LENGTH_MISMATCH" ); successes = new bool[](length); uint256 ethBalanceBefore = address(this).balance - msg.value; if (revertIfIncomplete) { for (uint256 i = 0; i < length; i++) { // Will revert if _buyERC1155 reverts. _buyERC1155(sellOrders[i], signatures[i], erc1155FillAmounts[i]); successes[i] = true; } } else { for (uint256 i = 0; i < length; i++) { // Delegatecall `buyERC1155FromProxy` to catch swallow reverts while // preserving execution context. (successes[i], ) = _implementation.delegatecall( abi.encodeWithSelector( this.buyERC1155FromProxy.selector, sellOrders[i], signatures[i], erc1155FillAmounts[i] ) ); } } // Refund _transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore); } function batchBuyERC1155sEx( LibNFTOrder.ERC1155SellOrder[] memory sellOrders, LibSignature.Signature[] memory signatures, address[] calldata takers, uint128[] calldata erc1155FillAmounts, bytes[] memory callbackData, bool revertIfIncomplete ) public override payable returns (bool[] memory successes) { uint256 length = sellOrders.length; require( length == signatures.length && length == takers.length && length == erc1155FillAmounts.length && length == callbackData.length, "ARRAY_LENGTH_MISMATCH" ); successes = new bool[](length); uint256 ethBalanceBefore = address(this).balance - msg.value; if (revertIfIncomplete) { for (uint256 i = 0; i < length; i++) { // Will revert if _buyERC1155Ex reverts. _buyERC1155Ex( sellOrders[i], signatures[i], BuyParams( erc1155FillAmounts[i], address(this).balance - ethBalanceBefore, // Remaining ETH available takers[i], callbackData[i] ) ); successes[i] = true; } } else { for (uint256 i = 0; i < length; i++) { // Delegatecall `buyERC1155ExFromProxy` to catch swallow reverts while // preserving execution context. (successes[i], ) = _implementation.delegatecall( abi.encodeWithSelector( this.buyERC1155ExFromProxy.selector, sellOrders[i], signatures[i], BuyParams( erc1155FillAmounts[i], address(this).balance - ethBalanceBefore, // Remaining ETH available takers[i], callbackData[i] ) ) ); } } // Refund _transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore); } // @Note `buyERC1155FromProxy` is a external function, must call from an external Exchange Proxy, // but should not be registered in the Exchange Proxy. function buyERC1155FromProxy( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, uint128 buyAmount ) external payable { require(_implementation != address(this), "MUST_CALL_FROM_PROXY"); _buyERC1155(sellOrder, signature, buyAmount); } // @Note `buyERC1155ExFromProxy` is a external function, must call from an external Exchange Proxy, // but should not be registered in the Exchange Proxy. function buyERC1155ExFromProxy( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, BuyParams memory params ) external payable { require(_implementation != address(this), "MUST_CALL_FROM_PROXY"); _buyERC1155Ex(sellOrder, signature, params); } /// @dev Callback for the ERC1155 `safeTransferFrom` function. /// This callback can be used to sell an ERC1155 asset if /// a valid ERC1155 order, signature and `unwrapNativeToken` /// are encoded in `data`. This allows takers to sell their /// ERC1155 asset without first calling `setApprovalForAll`. /// @param operator The address which called `safeTransferFrom`. /// @param tokenId The ID of the asset being transferred. /// @param value The amount being transferred. /// @param data Additional data with no specified format. If a /// valid ERC1155 order, signature and `unwrapNativeToken` /// are encoded in `data`, this function will try to fill /// the order using the received asset. /// @return success The selector of this function (0xf23a6e61), /// indicating that the callback succeeded. function onERC1155Received( address operator, address /* from */, uint256 tokenId, uint256 value, bytes calldata data ) external override returns (bytes4 success) { // Decode the order, signature, and `unwrapNativeToken` from // `data`. If `data` does not encode such parameters, this // will throw. ( LibNFTOrder.ERC1155BuyOrder memory buyOrder, LibSignature.Signature memory signature, bool unwrapNativeToken ) = abi.decode( data, (LibNFTOrder.ERC1155BuyOrder, LibSignature.Signature, bool) ); // `onERC1155Received` is called by the ERC1155 token contract. // Check that it matches the ERC1155 token in the order. if (msg.sender != buyOrder.erc1155Token) { revert("ERC1155_TOKEN_MISMATCH"); } require(value <= type(uint128).max); _sellERC1155( buyOrder, signature, SellParams( uint128(value), tokenId, unwrapNativeToken, operator, // taker address(this), // owner (we hold the NFT currently) new bytes(0) // No taker callback ) ); return ERC1155_RECEIVED_MAGIC_BYTES; } /// @dev Approves an ERC1155 sell order on-chain. After pre-signing /// the order, the `PRESIGNED` signature type will become /// valid for that order and signer. /// @param order An ERC1155 sell order. function preSignERC1155SellOrder(LibNFTOrder.ERC1155SellOrder memory order) public override { require(order.maker == msg.sender, "ONLY_MAKER"); uint256 hashNonce = LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker]; require(hashNonce < type(uint128).max); bytes32 orderHash = getERC1155SellOrderHash(order); LibERC1155OrdersStorage.getStorage().orderState[orderHash].preSigned = uint128(hashNonce + 1); emit ERC1155SellOrderPreSigned( order.maker, order.taker, order.expiry, order.nonce, order.erc20Token, order.erc20TokenAmount, order.fees, order.erc1155Token, order.erc1155TokenId, order.erc1155TokenAmount ); } /// @dev Approves an ERC1155 buy order on-chain. After pre-signing /// the order, the `PRESIGNED` signature type will become /// valid for that order and signer. /// @param order An ERC1155 buy order. function preSignERC1155BuyOrder(LibNFTOrder.ERC1155BuyOrder memory order) public override { require(order.maker == msg.sender, "ONLY_MAKER"); uint256 hashNonce = LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker]; require(hashNonce < type(uint128).max, "HASH_NONCE_OUTSIDE"); bytes32 orderHash = getERC1155BuyOrderHash(order); LibERC1155OrdersStorage.getStorage().orderState[orderHash].preSigned = uint128(hashNonce + 1); emit ERC1155BuyOrderPreSigned( order.maker, order.taker, order.expiry, order.nonce, order.erc20Token, order.erc20TokenAmount, order.fees, order.erc1155Token, order.erc1155TokenId, order.erc1155TokenProperties, order.erc1155TokenAmount ); } // Core settlement logic for selling an ERC1155 asset. // Used by `sellERC1155` and `onERC1155Received`. function _sellERC1155( LibNFTOrder.ERC1155BuyOrder memory buyOrder, LibSignature.Signature memory signature, SellParams memory params ) private { (uint256 erc20FillAmount, bytes32 orderHash) = _sellNFT( buyOrder.asNFTBuyOrder(), signature, params ); emit ERC1155BuyOrderFilled( buyOrder.maker, params.taker, (erc20FillAmount << 160) | uint160(address(buyOrder.erc20Token)), (params.tokenId << 160) | uint160(buyOrder.erc1155Token), params.sellAmount, orderHash ); } // Core settlement logic for buying an ERC1155 asset. // Used by `buyERC1155` and `batchBuyERC1155s`. function _buyERC1155( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, uint128 buyAmount ) internal { (uint256 erc20FillAmount, bytes32 orderHash) = _buyNFT( sellOrder.asNFTSellOrder(), signature, buyAmount ); emit ERC1155SellOrderFilled( sellOrder.maker, msg.sender, (erc20FillAmount << 160) | uint160(address(sellOrder.erc20Token)), (sellOrder.erc1155TokenId << 160) | uint160(sellOrder.erc1155Token), buyAmount, orderHash ); } function _buyERC1155Ex( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, BuyParams memory params ) internal { if (params.taker == address(0)) { params.taker = msg.sender; } else { require(params.taker != address(this), "_buy1155Ex/TAKER_CANNOT_SELF"); } (uint256 erc20FillAmount, bytes32 orderHash) = _buyNFTEx( sellOrder.asNFTSellOrder(), signature, params ); emit ERC1155SellOrderFilled( sellOrder.maker, params.taker, (erc20FillAmount << 160) | uint160(address(sellOrder.erc20Token)), (sellOrder.erc1155TokenId << 160) | uint160(sellOrder.erc1155Token), params.buyAmount, orderHash ); } /// @dev Checks whether the given signature is valid for the /// the given ERC1155 sell order. Reverts if not. /// @param order The ERC1155 sell order. /// @param signature The signature to validate. function validateERC1155SellOrderSignature( LibNFTOrder.ERC1155SellOrder memory order, LibSignature.Signature memory signature ) public override view { bytes32 orderHash = getERC1155SellOrderHash(order); _validateOrderSignature(orderHash, signature, order.maker); } /// @dev Checks whether the given signature is valid for the /// the given ERC1155 buy order. Reverts if not. /// @param order The ERC1155 buy order. /// @param signature The signature to validate. function validateERC1155BuyOrderSignature( LibNFTOrder.ERC1155BuyOrder memory order, LibSignature.Signature memory signature ) public override view { bytes32 orderHash = getERC1155BuyOrderHash(order); _validateOrderSignature(orderHash, signature, order.maker); } /// @dev Validates that the given signature is valid for the /// given maker and order hash. Reverts if the signature /// is not valid. /// @param orderHash The hash of the order that was signed. /// @param signature The signature to check. /// @param maker The maker of the order. function _validateOrderSignature( bytes32 orderHash, LibSignature.Signature memory signature, address maker ) internal override view { if (signature.signatureType == LibSignature.SignatureType.PRESIGNED) { require( LibERC1155OrdersStorage.getStorage().orderState[orderHash].preSigned == LibCommonNftOrdersStorage.getStorage().hashNonces[maker] + 1, "PRESIGNED_INVALID_SIGNER" ); } else { require( maker != address(0) && maker == ecrecover(orderHash, signature.v, signature.r, signature.s), "INVALID_SIGNER_ERROR" ); } } /// @dev Transfers an NFT asset. /// @param token The address of the NFT contract. /// @param from The address currently holding the asset. /// @param to The address to transfer the asset to. /// @param tokenId The ID of the asset to transfer. /// @param amount The amount of the asset to transfer. function _transferNFTAssetFrom( address token, address from, address to, uint256 tokenId, uint256 amount ) internal override { _transferERC1155AssetFrom(token, from, to, tokenId, amount); } /// @dev Updates storage to indicate that the given order /// has been filled by the given amount. /// @param orderHash The hash of `order`. /// @param fillAmount The amount (denominated in the NFT asset) /// that the order has been filled by. function _updateOrderState( LibNFTOrder.NFTSellOrder memory /* order */, bytes32 orderHash, uint128 fillAmount ) internal override { LibERC1155OrdersStorage.Storage storage stor = LibERC1155OrdersStorage.getStorage(); uint128 filledAmount = stor.orderState[orderHash].filledAmount; // Filled amount should never overflow 128 bits require(filledAmount + fillAmount > filledAmount); stor.orderState[orderHash].filledAmount = filledAmount + fillAmount; } /// @dev Get the order info for an ERC1155 sell order. /// @param order The ERC1155 sell order. /// @return orderInfo Infor about the order. function getERC1155SellOrderInfo(LibNFTOrder.ERC1155SellOrder memory order) public override view returns (LibNFTOrder.OrderInfo memory orderInfo) { orderInfo.orderAmount = order.erc1155TokenAmount; orderInfo.orderHash = getERC1155SellOrderHash(order); // Check for listingTime. // Gas Optimize, listingTime only used in rare cases. if (order.expiry & 0xffffffff00000000 > 0) { if ((order.expiry >> 32) & 0xffffffff > block.timestamp) { orderInfo.status = LibNFTOrder.OrderStatus.INVALID; return orderInfo; } } // Check for expiryTime. if (order.expiry & 0xffffffff <= block.timestamp) { orderInfo.status = LibNFTOrder.OrderStatus.EXPIRED; return orderInfo; } { LibERC1155OrdersStorage.Storage storage stor = LibERC1155OrdersStorage.getStorage(); LibERC1155OrdersStorage.OrderState storage orderState = stor.orderState[orderInfo.orderHash]; orderInfo.remainingAmount = order.erc1155TokenAmount - orderState.filledAmount; // `orderCancellationByMaker` is indexed by maker and nonce. uint256 orderCancellationBitVector = stor.orderCancellationByMaker[order.maker][uint248(order.nonce >> 8)]; // The bitvector is indexed by the lower 8 bits of the nonce. uint256 flag = 1 << (order.nonce & 255); if (orderInfo.remainingAmount == 0 || orderCancellationBitVector & flag != 0) { orderInfo.status = LibNFTOrder.OrderStatus.UNFILLABLE; return orderInfo; } } // Otherwise, the order is fillable. orderInfo.status = LibNFTOrder.OrderStatus.FILLABLE; return orderInfo; } /// @dev Get the order info for an ERC1155 buy order. /// @param order The ERC1155 buy order. /// @return orderInfo Infor about the order. function getERC1155BuyOrderInfo(LibNFTOrder.ERC1155BuyOrder memory order) public override view returns (LibNFTOrder.OrderInfo memory orderInfo) { orderInfo.orderAmount = order.erc1155TokenAmount; orderInfo.orderHash = getERC1155BuyOrderHash(order); // Only buy orders with `erc1155TokenId` == 0 can be property // orders. if (order.erc1155TokenId != 0 && order.erc1155TokenProperties.length > 0) { orderInfo.status = LibNFTOrder.OrderStatus.INVALID; return orderInfo; } // Buy orders cannot use ETH as the ERC20 token, since ETH cannot be // transferred from the buyer by a contract. if (address(order.erc20Token) == NATIVE_TOKEN_ADDRESS) { orderInfo.status = LibNFTOrder.OrderStatus.INVALID; return orderInfo; } // Check for listingTime. // Gas Optimize, listingTime only used in rare cases. if (order.expiry & 0xffffffff00000000 > 0) { if ((order.expiry >> 32) & 0xffffffff > block.timestamp) { orderInfo.status = LibNFTOrder.OrderStatus.INVALID; return orderInfo; } } // Check for expiryTime. if (order.expiry & 0xffffffff <= block.timestamp) { orderInfo.status = LibNFTOrder.OrderStatus.EXPIRED; return orderInfo; } { LibERC1155OrdersStorage.Storage storage stor = LibERC1155OrdersStorage.getStorage(); LibERC1155OrdersStorage.OrderState storage orderState = stor.orderState[orderInfo.orderHash]; orderInfo.remainingAmount = order.erc1155TokenAmount - orderState.filledAmount; // `orderCancellationByMaker` is indexed by maker and nonce. uint256 orderCancellationBitVector = stor.orderCancellationByMaker[order.maker][uint248(order.nonce >> 8)]; // The bitvector is indexed by the lower 8 bits of the nonce. uint256 flag = 1 << (order.nonce & 255); if (orderInfo.remainingAmount == 0 || orderCancellationBitVector & flag != 0) { orderInfo.status = LibNFTOrder.OrderStatus.UNFILLABLE; return orderInfo; } } // Otherwise, the order is fillable. orderInfo.status = LibNFTOrder.OrderStatus.FILLABLE; return orderInfo; } /// @dev Get the EIP-712 hash of an ERC1155 sell order. /// @param order The ERC1155 sell order. /// @return orderHash The order hash. function getERC1155SellOrderHash(LibNFTOrder.ERC1155SellOrder memory order) public override view returns (bytes32 orderHash) { return _getEIP712Hash( LibNFTOrder.getERC1155SellOrderStructHash( order, LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker] ) ); } /// @dev Get the EIP-712 hash of an ERC1155 buy order. /// @param order The ERC1155 buy order. /// @return orderHash The order hash. function getERC1155BuyOrderHash(LibNFTOrder.ERC1155BuyOrder memory order) public override view returns (bytes32 orderHash) { return _getEIP712Hash( LibNFTOrder.getERC1155BuyOrderStructHash( order, LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker] ) ); } /// @dev Get the order nonce status bit vector for the given /// maker address and nonce range. /// @param maker The maker of the order. /// @param nonceRange Order status bit vectors are indexed /// by maker address and the upper 248 bits of the /// order nonce. We define `nonceRange` to be these /// 248 bits. /// @return bitVector The order status bit vector for the /// given maker and nonce range. function getERC1155OrderNonceStatusBitVector(address maker, uint248 nonceRange) external override view returns (uint256) { return LibERC1155OrdersStorage.getStorage().orderCancellationByMaker[maker][nonceRange]; } /// @dev Get the order info for an NFT sell order. /// @param nftSellOrder The NFT sell order. /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTSellOrder memory nftSellOrder) internal override view returns (LibNFTOrder.OrderInfo memory orderInfo) { return getERC1155SellOrderInfo(nftSellOrder.asERC1155SellOrder()); } /// @dev Get the order info for an NFT buy order. /// @param nftBuyOrder The NFT buy order. /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTBuyOrder memory nftBuyOrder) internal override view returns (LibNFTOrder.OrderInfo memory orderInfo) { return getERC1155BuyOrderInfo(nftBuyOrder.asERC1155BuyOrder()); } /// @dev Matches a pair of complementary orders that have /// a non-negative spread. Each order is filled at /// their respective price, and the matcher receives /// a profit denominated in the ERC20 token. /// @param sellOrder Order selling an ERC1155 asset. /// @param buyOrder Order buying an ERC1155 asset. /// @param sellOrderSignature Signature for the sell order. /// @param buyOrderSignature Signature for the buy order. /// @return profit The amount of profit earned by the caller /// of this function (denominated in the ERC20 token /// of the matched orders). function matchERC1155Orders( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibNFTOrder.ERC1155BuyOrder memory buyOrder, LibSignature.Signature memory sellOrderSignature, LibSignature.Signature memory buyOrderSignature ) public override returns (uint256 profit) { // The ERC1155 tokens must match if (sellOrder.erc1155Token != buyOrder.erc1155Token) { revert("ERC1155_TOKEN_MISMATCH_ERROR"); } LibNFTOrder.NFTSellOrder memory sellNFTOrder = sellOrder.asNFTSellOrder(); LibNFTOrder.NFTBuyOrder memory buyNFTOrder = buyOrder.asNFTBuyOrder(); LibNFTOrder.OrderInfo memory sellOrderInfo = getERC1155SellOrderInfo(sellOrder); LibNFTOrder.OrderInfo memory buyOrderInfo = getERC1155BuyOrderInfo(buyOrder); bool isEnglishAuction = (sellOrder.expiry >> 252 == 2); if (isEnglishAuction) { require( sellOrderInfo.orderAmount == sellOrderInfo.remainingAmount && sellOrderInfo.orderAmount == buyOrderInfo.orderAmount && sellOrderInfo.orderAmount == buyOrderInfo.remainingAmount, "UNMATCH_ORDER_AMOUNT" ); } _validateSellOrder( sellNFTOrder, sellOrderSignature, sellOrderInfo, buyOrder.maker ); _validateBuyOrder( buyNFTOrder, buyOrderSignature, buyOrderInfo, sellOrder.maker, sellOrder.erc1155TokenId ); // fillAmount = min(sellOrder.remainingAmount, buyOrder.remainingAmount) uint128 erc1155FillAmount = sellOrderInfo.remainingAmount < buyOrderInfo.remainingAmount ? sellOrderInfo.remainingAmount : buyOrderInfo.remainingAmount; // Reset sellOrder.erc20TokenAmount if (erc1155FillAmount != sellOrderInfo.orderAmount) { sellOrder.erc20TokenAmount = _ceilDiv( sellOrder.erc20TokenAmount * erc1155FillAmount, sellOrderInfo.orderAmount ); } // Reset buyOrder.erc20TokenAmount if (erc1155FillAmount != buyOrderInfo.orderAmount) { buyOrder.erc20TokenAmount = buyOrder.erc20TokenAmount * erc1155FillAmount / buyOrderInfo.orderAmount; } if (isEnglishAuction) { _resetEnglishAuctionTokenAmountAndFees( sellNFTOrder, buyOrder.erc20TokenAmount, erc1155FillAmount, sellOrderInfo.orderAmount ); } // Mark both orders as filled. _updateOrderState(sellNFTOrder, sellOrderInfo.orderHash, erc1155FillAmount); _updateOrderState(buyNFTOrder.asNFTSellOrder(), buyOrderInfo.orderHash, erc1155FillAmount); // The difference in ERC20 token amounts is the spread. uint256 spread = buyOrder.erc20TokenAmount - sellOrder.erc20TokenAmount; // Transfer the ERC1155 asset from seller to buyer. _transferERC1155AssetFrom( sellOrder.erc1155Token, sellOrder.maker, buyOrder.maker, sellOrder.erc1155TokenId, erc1155FillAmount ); // Handle the ERC20 side of the order: if ( address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS && buyOrder.erc20Token == WETH ) { // The sell order specifies ETH, while the buy order specifies WETH. // The orders are still compatible with one another, but we'll have // to unwrap the WETH on behalf of the buyer. // Step 1: Transfer WETH from the buyer to the EP. // Note that we transfer `buyOrder.erc20TokenAmount`, which // is the amount the buyer signaled they are willing to pay // for the ERC1155 asset, which may be more than the seller's // ask. _transferERC20TokensFrom( WETH, buyOrder.maker, address(this), buyOrder.erc20TokenAmount ); // Step 2: Unwrap the WETH into ETH. We unwrap the entire // `buyOrder.erc20TokenAmount`. // The ETH will be used for three purposes: // - To pay the seller // - To pay fees for the sell order // - Any remaining ETH will be sent to // `msg.sender` as profit. WETH.withdraw(buyOrder.erc20TokenAmount); // Step 3: Pay the seller (in ETH). _transferEth(payable(sellOrder.maker), sellOrder.erc20TokenAmount); // Step 4: Pay fees for the buy order. Note that these are paid // in _WETH_ by the _buyer_. By signing the buy order, the // buyer signals that they are willing to spend a total // of `erc20TokenAmount` _plus_ fees, all denominated in // the `erc20Token`, which in this case is WETH. _payFees( buyNFTOrder.asNFTSellOrder(), buyOrder.maker, // payer erc1155FillAmount, buyOrderInfo.orderAmount, false // useNativeToken ); // Step 5: Pay fees for the sell order. The `erc20Token` of the // sell order is ETH, so the fees are paid out in ETH. // There should be `spread` wei of ETH remaining in the // EP at this point, which we will use ETH to pay the // sell order fees. uint256 sellOrderFees = _payFees( sellNFTOrder, address(this), // payer erc1155FillAmount, sellOrderInfo.orderAmount, true // useNativeToken ); // Step 6: The spread less the sell order fees is the amount of ETH // remaining in the EP that can be sent to `msg.sender` as // the profit from matching these two orders. profit = spread - sellOrderFees; if (profit > 0) { _transferEth(payable(msg.sender), profit); } } else { // ERC20 tokens must match if (sellOrder.erc20Token != buyOrder.erc20Token) { revert("ERC20_TOKEN_MISMATCH"); } // Step 1: Transfer the ERC20 token from the buyer to the seller. // Note that we transfer `sellOrder.erc20TokenAmount`, which // is at most `buyOrder.erc20TokenAmount`. _transferERC20TokensFrom( buyOrder.erc20Token, buyOrder.maker, sellOrder.maker, sellOrder.erc20TokenAmount ); // Step 2: Pay fees for the buy order. Note that these are paid // by the buyer. By signing the buy order, the buyer signals // that they are willing to spend a total of // `buyOrder.erc20TokenAmount` _plus_ `buyOrder.fees`. _payFees( buyNFTOrder.asNFTSellOrder(), buyOrder.maker, // payer erc1155FillAmount, buyOrderInfo.orderAmount, false // useNativeToken ); // Step 3: Pay fees for the sell order. These are paid by the buyer // as well. After paying these fees, we may have taken more // from the buyer than they agreed to in the buy order. If // so, we revert in the following step. uint256 sellOrderFees = _payFees( sellNFTOrder, buyOrder.maker, // payer erc1155FillAmount, sellOrderInfo.orderAmount, false // useNativeToken ); // Step 4: We calculate the profit as: // profit = buyOrder.erc20TokenAmount - sellOrder.erc20TokenAmount - sellOrderFees // = spread - sellOrderFees // I.e. the buyer would've been willing to pay up to `profit` // more to buy the asset, so instead that amount is sent to // `msg.sender` as the profit from matching these two orders. profit = spread - sellOrderFees; if (profit > 0) { _transferERC20TokensFrom( buyOrder.erc20Token, buyOrder.maker, msg.sender, profit ); } } _emitEventSellOrderFilled( sellOrder, buyOrder.maker, // taker erc1155FillAmount, sellOrderInfo.orderHash ); _emitEventBuyOrderFilled( buyOrder, sellOrder.maker, // taker sellOrder.erc1155TokenId, erc1155FillAmount, buyOrderInfo.orderHash ); } function _emitEventSellOrderFilled( LibNFTOrder.ERC1155SellOrder memory sellOrder, address taker, uint128 erc1155FillAmount, bytes32 orderHash ) private { emit ERC1155SellOrderFilled( sellOrder.maker, taker, (sellOrder.erc20TokenAmount << 160) | uint160(address(sellOrder.erc20Token)), (sellOrder.erc1155TokenId << 160) | uint160(sellOrder.erc1155Token), erc1155FillAmount, orderHash ); } function _emitEventBuyOrderFilled( LibNFTOrder.ERC1155BuyOrder memory buyOrder, address taker, uint256 erc1155TokenId, uint128 erc1155FillAmount, bytes32 orderHash ) private { emit ERC1155BuyOrderFilled( buyOrder.maker, taker, (buyOrder.erc20TokenAmount << 160) | uint160(address(buyOrder.erc20Token)), (erc1155TokenId << 160) | uint160(buyOrder.erc1155Token), erc1155FillAmount, orderHash ); } /// @dev Matches pairs of complementary orders that have /// non-negative spreads. Each order is filled at /// their respective price, and the matcher receives /// a profit denominated in the ERC20 token. /// @param sellOrders Orders selling ERC1155 assets. /// @param buyOrders Orders buying ERC1155 assets. /// @param sellOrderSignatures Signatures for the sell orders. /// @param buyOrderSignatures Signatures for the buy orders. /// @return profits The amount of profit earned by the caller /// of this function for each pair of matched orders /// (denominated in the ERC20 token of the order pair). /// @return successes An array of booleans corresponding to /// whether each pair of orders was successfully matched. function batchMatchERC1155Orders( LibNFTOrder.ERC1155SellOrder[] memory sellOrders, LibNFTOrder.ERC1155BuyOrder[] memory buyOrders, LibSignature.Signature[] memory sellOrderSignatures, LibSignature.Signature[] memory buyOrderSignatures ) public override returns (uint256[] memory profits, bool[] memory successes) { require( sellOrders.length == buyOrders.length && sellOrderSignatures.length == buyOrderSignatures.length && sellOrders.length == sellOrderSignatures.length ); profits = new uint256[](sellOrders.length); successes = new bool[](sellOrders.length); for (uint256 i = 0; i < sellOrders.length; i++) { bytes memory returnData; // Delegatecall `matchERC1155Orders` to catch reverts while // preserving execution context. (successes[i], returnData) = _implementation.delegatecall( abi.encodeWithSelector( this.matchERC1155Orders.selector, sellOrders[i], buyOrders[i], sellOrderSignatures[i], buyOrderSignatures[i] ) ); if (successes[i]) { // If the matching succeeded, record the profit. (uint256 profit) = abi.decode(returnData, (uint256)); profits[i] = profit; } } } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; /// @dev Helpers for moving ERC1155 assets around. abstract contract FixinERC1155Spender { // Mask of the lower 20 bytes of a bytes32. uint256 constant private ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; /// @dev Transfers an ERC1155 asset from `owner` to `to`. /// @param token The address of the ERC1155 token contract. /// @param owner The owner of the asset. /// @param to The recipient of the asset. /// @param tokenId The token ID of the asset to transfer. /// @param amount The amount of the asset to transfer. function _transferERC1155AssetFrom( address token, address owner, address to, uint256 tokenId, uint256 amount ) internal { uint256 success; assembly { let ptr := mload(0x40) // free memory pointer // selector for safeTransferFrom(address,address,uint256,uint256,bytes) mstore(ptr, 0xf242432a00000000000000000000000000000000000000000000000000000000) mstore(add(ptr, 0x04), and(owner, ADDRESS_MASK)) mstore(add(ptr, 0x24), and(to, ADDRESS_MASK)) mstore(add(ptr, 0x44), tokenId) mstore(add(ptr, 0x64), amount) mstore(add(ptr, 0x84), 0xa0) mstore(add(ptr, 0xa4), 0) success := call( gas(), and(token, ADDRESS_MASK), 0, ptr, 0xc4, 0, 0 ) } require(success != 0, "_transferERC1155/TRANSFER_FAILED"); } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2022 Element.Market 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.8.13; import "./LibStorage.sol"; library LibCommonNftOrdersStorage { /// @dev Storage bucket for this feature. struct Storage { /* Track per-maker nonces that can be incremented by the maker to cancel orders in bulk. */ // The current nonce for the maker represents the only valid nonce that can be signed by the maker // If a signature was signed with a nonce that's different from the one stored in nonces, it // will fail validation. mapping(address => uint256) hashNonces; } /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { uint256 storageSlot = LibStorage.STORAGE_ID_COMMON_NFT_ORDERS; // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries assembly { stor.slot := storageSlot } } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "./LibStorage.sol"; /// @dev Storage helpers for `ERC1155OrdersFeature`. library LibERC1155OrdersStorage { struct OrderState { // The amount (denominated in the ERC1155 asset) // that the order has been filled by. uint128 filledAmount; // Whether the order has been pre-signed. uint128 preSigned; } /// @dev Storage bucket for this feature. struct Storage { // Mapping from order hash to order state: mapping(bytes32 => OrderState) orderState; // maker => nonce range => order cancellation bit vector mapping(address => mapping(uint248 => uint256)) orderCancellationByMaker; } /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { uint256 storageSlot = LibStorage.STORAGE_ID_ERC1155_ORDERS; // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries assembly { stor.slot := storageSlot } } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../libs/LibNFTOrder.sol"; import "../libs/LibSignature.sol"; import "./IERC1155OrdersEvent.sol"; /// @dev Feature for interacting with ERC1155 orders. interface IERC1155OrdersFeature is IERC1155OrdersEvent { /// @dev Sells an ERC1155 asset to fill the given order. /// @param buyOrder The ERC1155 buy order. /// @param signature The order signature from the maker. /// @param erc1155TokenId The ID of the ERC1155 asset being /// sold. If the given order specifies properties, /// the asset must satisfy those properties. Otherwise, /// it must equal the tokenId in the order. /// @param erc1155SellAmount The amount of the ERC1155 asset /// to sell. /// @param unwrapNativeToken If this parameter is true and the /// ERC20 token of the order is e.g. WETH, unwraps the /// token before transferring it to the taker. /// @param callbackData If this parameter is non-zero, invokes /// `zeroExERC1155OrderCallback` on `msg.sender` after /// the ERC20 tokens have been transferred to `msg.sender` /// but before transferring the ERC1155 asset to the buyer. function sellERC1155( LibNFTOrder.ERC1155BuyOrder calldata buyOrder, LibSignature.Signature calldata signature, uint256 erc1155TokenId, uint128 erc1155SellAmount, bool unwrapNativeToken, bytes calldata callbackData ) external; /// @dev Buys an ERC1155 asset by filling the given order. /// @param sellOrder The ERC1155 sell order. /// @param signature The order signature. /// @param erc1155BuyAmount The amount of the ERC1155 asset /// to buy. function buyERC1155( LibNFTOrder.ERC1155SellOrder calldata sellOrder, LibSignature.Signature calldata signature, uint128 erc1155BuyAmount ) external payable; /// @dev Buys an ERC1155 asset by filling the given order. /// @param sellOrder The ERC1155 sell order. /// @param signature The order signature. /// @param taker The address to receive ERC1155. If this parameter /// is zero, transfer ERC1155 to `msg.sender`. /// @param erc1155BuyAmount The amount of the ERC1155 asset /// to buy. /// @param callbackData If this parameter is non-zero, invokes /// `zeroExERC1155OrderCallback` on `msg.sender` after /// the ERC1155 asset has been transferred to `msg.sender` /// but before transferring the ERC20 tokens to the seller. /// Native tokens acquired during the callback can be used /// to fill the order. function buyERC1155Ex( LibNFTOrder.ERC1155SellOrder calldata sellOrder, LibSignature.Signature calldata signature, address taker, uint128 erc1155BuyAmount, bytes calldata callbackData ) external payable; /// @dev Cancel a single ERC1155 order by its nonce. The caller /// should be the maker of the order. Silently succeeds if /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonce The order nonce. function cancelERC1155Order(uint256 orderNonce) external; /// @dev Cancel multiple ERC1155 orders by their nonces. The caller /// should be the maker of the orders. Silently succeeds if /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonces The order nonces. function batchCancelERC1155Orders(uint256[] calldata orderNonces) external; /// @dev Buys multiple ERC1155 assets by filling the /// given orders. /// @param sellOrders The ERC1155 sell orders. /// @param signatures The order signatures. /// @param erc1155TokenAmounts The amounts of the ERC1155 assets /// to buy for each order. /// @param revertIfIncomplete If true, reverts if this /// function fails to fill any individual order. /// @return successes An array of booleans corresponding to whether /// each order in `orders` was successfully filled. function batchBuyERC1155s( LibNFTOrder.ERC1155SellOrder[] calldata sellOrders, LibSignature.Signature[] calldata signatures, uint128[] calldata erc1155TokenAmounts, bool revertIfIncomplete ) external payable returns (bool[] memory successes); /// @dev Buys multiple ERC1155 assets by filling the /// given orders. /// @param sellOrders The ERC1155 sell orders. /// @param signatures The order signatures. /// @param erc1155TokenAmounts The amounts of the ERC1155 assets /// to buy for each order. /// @param takers The address to receive ERC1155. /// @param callbackData The data (if any) to pass to the taker /// callback for each order. Refer to the `callbackData` /// parameter to for `buyERC1155`. /// @param revertIfIncomplete If true, reverts if this /// function fails to fill any individual order. /// @return successes An array of booleans corresponding to whether /// each order in `orders` was successfully filled. function batchBuyERC1155sEx( LibNFTOrder.ERC1155SellOrder[] calldata sellOrders, LibSignature.Signature[] calldata signatures, address[] calldata takers, uint128[] calldata erc1155TokenAmounts, bytes[] calldata callbackData, bool revertIfIncomplete ) external payable returns (bool[] memory successes); /// @dev Callback for the ERC1155 `safeTransferFrom` function. /// This callback can be used to sell an ERC1155 asset if /// a valid ERC1155 order, signature and `unwrapNativeToken` /// are encoded in `data`. This allows takers to sell their /// ERC1155 asset without first calling `setApprovalForAll`. /// @param operator The address which called `safeTransferFrom`. /// @param from The address which previously owned the token. /// @param tokenId The ID of the asset being transferred. /// @param value The amount being transferred. /// @param data Additional data with no specified format. If a /// valid ERC1155 order, signature and `unwrapNativeToken` /// are encoded in `data`, this function will try to fill /// the order using the received asset. /// @return success The selector of this function (0xf23a6e61), /// indicating that the callback succeeded. function onERC1155Received( address operator, address from, uint256 tokenId, uint256 value, bytes calldata data ) external returns (bytes4 success); /// @dev Approves an ERC1155 sell order on-chain. After pre-signing /// the order, the `PRESIGNED` signature type will become /// valid for that order and signer. /// @param order An ERC1155 sell order. function preSignERC1155SellOrder(LibNFTOrder.ERC1155SellOrder calldata order) external; /// @dev Approves an ERC1155 buy order on-chain. After pre-signing /// the order, the `PRESIGNED` signature type will become /// valid for that order and signer. /// @param order An ERC1155 buy order. function preSignERC1155BuyOrder(LibNFTOrder.ERC1155BuyOrder calldata order) external; /// @dev Checks whether the given signature is valid for the /// the given ERC1155 sell order. Reverts if not. /// @param order The ERC1155 sell order. /// @param signature The signature to validate. function validateERC1155SellOrderSignature( LibNFTOrder.ERC1155SellOrder calldata order, LibSignature.Signature calldata signature ) external view; /// @dev Checks whether the given signature is valid for the /// the given ERC1155 buy order. Reverts if not. /// @param order The ERC1155 buy order. /// @param signature The signature to validate. function validateERC1155BuyOrderSignature( LibNFTOrder.ERC1155BuyOrder calldata order, LibSignature.Signature calldata signature ) external view; /// @dev Get the order info for an ERC1155 sell order. /// @param order The ERC1155 sell order. /// @return orderInfo Infor about the order. function getERC1155SellOrderInfo(LibNFTOrder.ERC1155SellOrder calldata order) external view returns (LibNFTOrder.OrderInfo memory orderInfo); /// @dev Get the order info for an ERC1155 buy order. /// @param order The ERC1155 buy order. /// @return orderInfo Infor about the order. function getERC1155BuyOrderInfo(LibNFTOrder.ERC1155BuyOrder calldata order) external view returns (LibNFTOrder.OrderInfo memory orderInfo); /// @dev Get the EIP-712 hash of an ERC1155 sell order. /// @param order The ERC1155 sell order. /// @return orderHash The order hash. function getERC1155SellOrderHash(LibNFTOrder.ERC1155SellOrder calldata order) external view returns (bytes32 orderHash); /// @dev Get the EIP-712 hash of an ERC1155 buy order. /// @param order The ERC1155 buy order. /// @return orderHash The order hash. function getERC1155BuyOrderHash(LibNFTOrder.ERC1155BuyOrder calldata order) external view returns (bytes32 orderHash); /// @dev Get the order nonce status bit vector for the given /// maker address and nonce range. /// @param maker The maker of the order. /// @param nonceRange Order status bit vectors are indexed /// by maker address and the upper 248 bits of the /// order nonce. We define `nonceRange` to be these /// 248 bits. /// @return bitVector The order status bit vector for the /// given maker and nonce range. function getERC1155OrderNonceStatusBitVector(address maker, uint248 nonceRange) external view returns (uint256); /// @dev Matches a pair of complementary orders that have /// a non-negative spread. Each order is filled at /// their respective price, and the matcher receives /// a profit denominated in the ERC20 token. /// @param sellOrder Order selling an ERC1155 asset. /// @param buyOrder Order buying an ERC1155 asset. /// @param sellOrderSignature Signature for the sell order. /// @param buyOrderSignature Signature for the buy order. /// @return profit The amount of profit earned by the caller /// of this function (denominated in the ERC20 token /// of the matched orders). function matchERC1155Orders( LibNFTOrder.ERC1155SellOrder calldata sellOrder, LibNFTOrder.ERC1155BuyOrder calldata buyOrder, LibSignature.Signature calldata sellOrderSignature, LibSignature.Signature calldata buyOrderSignature ) external returns (uint256 profit); /// @dev Matches pairs of complementary orders that have /// non-negative spreads. Each order is filled at /// their respective price, and the matcher receives /// a profit denominated in the ERC20 token. /// @param sellOrders Orders selling ERC1155 assets. /// @param buyOrders Orders buying ERC1155 assets. /// @param sellOrderSignatures Signatures for the sell orders. /// @param buyOrderSignatures Signatures for the buy orders. /// @return profits The amount of profit earned by the caller /// of this function for each pair of matched orders /// (denominated in the ERC20 token of the order pair). /// @return successes An array of booleans corresponding to /// whether each pair of orders was successfully matched. function batchMatchERC1155Orders( LibNFTOrder.ERC1155SellOrder[] calldata sellOrders, LibNFTOrder.ERC1155BuyOrder[] calldata buyOrders, LibSignature.Signature[] calldata sellOrderSignatures, LibSignature.Signature[] calldata buyOrderSignatures ) external returns (uint256[] memory profits, bool[] memory successes); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../vendor/IPropertyValidator.sol"; /// @dev A library for common NFT order operations. library LibNFTOrder { enum OrderStatus { INVALID, FILLABLE, UNFILLABLE, EXPIRED } struct Property { IPropertyValidator propertyValidator; bytes propertyData; } struct Fee { address recipient; uint256 amount; bytes feeData; } struct NFTSellOrder { address maker; address taker; uint256 expiry; uint256 nonce; IERC20 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address nft; uint256 nftId; } // All fields except `nftProperties` align // with those of NFTSellOrder struct NFTBuyOrder { address maker; address taker; uint256 expiry; uint256 nonce; IERC20 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address nft; uint256 nftId; Property[] nftProperties; } // All fields except `erc1155TokenAmount` align // with those of NFTSellOrder struct ERC1155SellOrder { address maker; address taker; uint256 expiry; uint256 nonce; IERC20 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address erc1155Token; uint256 erc1155TokenId; // End of fields shared with NFTOrder uint128 erc1155TokenAmount; } // All fields except `erc1155TokenAmount` align // with those of NFTBuyOrder struct ERC1155BuyOrder { address maker; address taker; uint256 expiry; uint256 nonce; IERC20 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address erc1155Token; uint256 erc1155TokenId; Property[] erc1155TokenProperties; // End of fields shared with NFTOrder uint128 erc1155TokenAmount; } struct OrderInfo { bytes32 orderHash; OrderStatus status; // `orderAmount` is 1 for all ERC721Orders, and // `erc1155TokenAmount` for ERC1155Orders. uint128 orderAmount; // The remaining amount of the ERC721/ERC1155 asset // that can be filled for the order. uint128 remainingAmount; } // The type hash for sell orders, which is: // keccak256(abi.encodePacked( // "NFTSellOrder(", // "address maker,", // "address taker,", // "uint256 expiry,", // "uint256 nonce,", // "address erc20Token,", // "uint256 erc20TokenAmount,", // "Fee[] fees,", // "address nft,", // "uint256 nftId,", // "uint256 hashNonce", // ")", // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")" // )) uint256 private constant _NFT_SELL_ORDER_TYPE_HASH = 0xed676c7f3e8232a311454799b1cf26e75b4abc90c9bf06c9f7e8e79fcc7fe14d; // The type hash for buy orders, which is: // keccak256(abi.encodePacked( // "NFTBuyOrder(", // "address maker,", // "address taker,", // "uint256 expiry,", // "uint256 nonce,", // "address erc20Token,", // "uint256 erc20TokenAmount,", // "Fee[] fees,", // "address nft,", // "uint256 nftId,", // "Property[] nftProperties,", // "uint256 hashNonce", // ")", // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")", // "Property(", // "address propertyValidator,", // "bytes propertyData", // ")" // )) uint256 private constant _NFT_BUY_ORDER_TYPE_HASH = 0xa525d336300f566329800fcbe82fd263226dc27d6c109f060d9a4a364281521c; // The type hash for ERC1155 sell orders, which is: // keccak256(abi.encodePacked( // "ERC1155SellOrder(", // "address maker,", // "address taker,", // "uint256 expiry,", // "uint256 nonce,", // "address erc20Token,", // "uint256 erc20TokenAmount,", // "Fee[] fees,", // "address erc1155Token,", // "uint256 erc1155TokenId,", // "uint128 erc1155TokenAmount,", // "uint256 hashNonce", // ")", // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")" // )) uint256 private constant _ERC_1155_SELL_ORDER_TYPE_HASH = 0x3529b5920cc48ecbceb24e9c51dccb50fefd8db2cf05d36e356aeb1754e19eda; // The type hash for ERC1155 buy orders, which is: // keccak256(abi.encodePacked( // "ERC1155BuyOrder(", // "address maker,", // "address taker,", // "uint256 expiry,", // "uint256 nonce,", // "address erc20Token,", // "uint256 erc20TokenAmount,", // "Fee[] fees,", // "address erc1155Token,", // "uint256 erc1155TokenId,", // "Property[] erc1155TokenProperties,", // "uint128 erc1155TokenAmount,", // "uint256 hashNonce", // ")", // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")", // "Property(", // "address propertyValidator,", // "bytes propertyData", // ")" // )) uint256 private constant _ERC_1155_BUY_ORDER_TYPE_HASH = 0x1a6eaae1fbed341e0974212ec17f035a9d419cadc3bf5154841cbf7fd605ba48; // keccak256(abi.encodePacked( // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")" // )) uint256 private constant _FEE_TYPE_HASH = 0xe68c29f1b4e8cce0bbcac76eb1334bdc1dc1f293a517c90e9e532340e1e94115; // keccak256(abi.encodePacked( // "Property(", // "address propertyValidator,", // "bytes propertyData", // ")" // )) uint256 private constant _PROPERTY_TYPE_HASH = 0x6292cf854241cb36887e639065eca63b3af9f7f70270cebeda4c29b6d3bc65e8; // keccak256(""); bytes32 private constant _EMPTY_ARRAY_KECCAK256 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // keccak256(abi.encodePacked(keccak256(abi.encode( // _PROPERTY_TYPE_HASH, // address(0), // keccak256("") // )))); bytes32 private constant _NULL_PROPERTY_STRUCT_HASH = 0x720ee400a9024f6a49768142c339bf09d2dd9056ab52d20fbe7165faba6e142d; uint256 private constant ADDRESS_MASK = (1 << 160) - 1; function asNFTSellOrder(NFTBuyOrder memory nftBuyOrder) internal pure returns (NFTSellOrder memory order) { assembly { order := nftBuyOrder } } function asNFTSellOrder(ERC1155SellOrder memory erc1155SellOrder) internal pure returns (NFTSellOrder memory order) { assembly { order := erc1155SellOrder } } function asNFTBuyOrder(ERC1155BuyOrder memory erc1155BuyOrder) internal pure returns (NFTBuyOrder memory order) { assembly { order := erc1155BuyOrder } } function asERC1155SellOrder(NFTSellOrder memory nftSellOrder) internal pure returns (ERC1155SellOrder memory order) { assembly { order := nftSellOrder } } function asERC1155BuyOrder(NFTBuyOrder memory nftBuyOrder) internal pure returns (ERC1155BuyOrder memory order) { assembly { order := nftBuyOrder } } // @dev Get the struct hash of an sell order. /// @param order The sell order. /// @return structHash The struct hash of the order. function getNFTSellOrderStructHash(NFTSellOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) { bytes32 feesHash = _feesHash(order.fees); // Hash in place, equivalent to: // return keccak256(abi.encode( // _NFT_SELL_ORDER_TYPE_HASH, // order.maker, // order.taker, // order.expiry, // order.nonce, // order.erc20Token, // order.erc20TokenAmount, // feesHash, // order.nft, // order.nftId, // hashNonce // )); assembly { if lt(order, 32) { invalid() } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 192) // order + (32 * 6) let hashNoncePos := add(order, 288) // order + (32 * 9) let typeHashMemBefore := mload(typeHashPos) let feeHashMemBefore := mload(feesHashPos) let hashNonceMemBefore := mload(hashNoncePos) mstore(typeHashPos, _NFT_SELL_ORDER_TYPE_HASH) mstore(feesHashPos, feesHash) mstore(hashNoncePos, hashNonce) structHash := keccak256(typeHashPos, 352 /* 32 * 11 */ ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feeHashMemBefore) mstore(hashNoncePos, hashNonceMemBefore) } return structHash; } /// @dev Get the struct hash of an buy order. /// @param order The buy order. /// @return structHash The struct hash of the order. function getNFTBuyOrderStructHash(NFTBuyOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) { bytes32 propertiesHash = _propertiesHash(order.nftProperties); bytes32 feesHash = _feesHash(order.fees); // Hash in place, equivalent to: // return keccak256(abi.encode( // _NFT_BUY_ORDER_TYPE_HASH, // order.maker, // order.taker, // order.expiry, // order.nonce, // order.erc20Token, // order.erc20TokenAmount, // feesHash, // order.nft, // order.nftId, // propertiesHash, // hashNonce // )); assembly { if lt(order, 32) { invalid() } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 192) // order + (32 * 6) let propertiesHashPos := add(order, 288) // order + (32 * 9) let hashNoncePos := add(order, 320) // order + (32 * 10) let typeHashMemBefore := mload(typeHashPos) let feeHashMemBefore := mload(feesHashPos) let propertiesHashMemBefore := mload(propertiesHashPos) let hashNonceMemBefore := mload(hashNoncePos) mstore(typeHashPos, _NFT_BUY_ORDER_TYPE_HASH) mstore(feesHashPos, feesHash) mstore(propertiesHashPos, propertiesHash) mstore(hashNoncePos, hashNonce) structHash := keccak256(typeHashPos, 384 /* 32 * 12 */ ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feeHashMemBefore) mstore(propertiesHashPos, propertiesHashMemBefore) mstore(hashNoncePos, hashNonceMemBefore) } return structHash; } /// @dev Get the struct hash of an ERC1155 sell order. /// @param order The ERC1155 sell order. /// @return structHash The struct hash of the order. function getERC1155SellOrderStructHash(ERC1155SellOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) { bytes32 feesHash = _feesHash(order.fees); // Hash in place, equivalent to: // return keccak256(abi.encode( // _ERC_1155_SELL_ORDER_TYPE_HASH, // order.maker, // order.taker, // order.expiry, // order.nonce, // order.erc20Token, // order.erc20TokenAmount, // feesHash, // order.erc1155Token, // order.erc1155TokenId, // order.erc1155TokenAmount, // hashNonce // )); assembly { if lt(order, 32) { invalid() } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 192) // order + (32 * 6) let hashNoncePos := add(order, 320) // order + (32 * 10) let typeHashMemBefore := mload(typeHashPos) let feesHashMemBefore := mload(feesHashPos) let hashNonceMemBefore := mload(hashNoncePos) mstore(typeHashPos, _ERC_1155_SELL_ORDER_TYPE_HASH) mstore(feesHashPos, feesHash) mstore(hashNoncePos, hashNonce) structHash := keccak256(typeHashPos, 384 /* 32 * 12 */ ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feesHashMemBefore) mstore(hashNoncePos, hashNonceMemBefore) } return structHash; } /// @dev Get the struct hash of an ERC1155 buy order. /// @param order The ERC1155 buy order. /// @return structHash The struct hash of the order. function getERC1155BuyOrderStructHash(ERC1155BuyOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) { bytes32 propertiesHash = _propertiesHash(order.erc1155TokenProperties); bytes32 feesHash = _feesHash(order.fees); // Hash in place, equivalent to: // return keccak256(abi.encode( // _ERC_1155_BUY_ORDER_TYPE_HASH, // order.maker, // order.taker, // order.expiry, // order.nonce, // order.erc20Token, // order.erc20TokenAmount, // feesHash, // order.erc1155Token, // order.erc1155TokenId, // propertiesHash, // order.erc1155TokenAmount, // hashNonce // )); assembly { if lt(order, 32) { invalid() } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 192) // order + (32 * 6) let propertiesHashPos := add(order, 288) // order + (32 * 9) let hashNoncePos := add(order, 352) // order + (32 * 11) let typeHashMemBefore := mload(typeHashPos) let feesHashMemBefore := mload(feesHashPos) let propertiesHashMemBefore := mload(propertiesHashPos) let hashNonceMemBefore := mload(hashNoncePos) mstore(typeHashPos, _ERC_1155_BUY_ORDER_TYPE_HASH) mstore(feesHashPos, feesHash) mstore(propertiesHashPos, propertiesHash) mstore(hashNoncePos, hashNonce) structHash := keccak256(typeHashPos, 416 /* 32 * 13 */ ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feesHashMemBefore) mstore(propertiesHashPos, propertiesHashMemBefore) mstore(hashNoncePos, hashNonceMemBefore) } return structHash; } // Hashes the `properties` array as part of computing the // EIP-712 hash of an `ERC721Order` or `ERC1155Order`. function _propertiesHash(Property[] memory properties) private pure returns (bytes32 propertiesHash) { uint256 numProperties = properties.length; // We give `properties.length == 0` and `properties.length == 1` // special treatment because we expect these to be the most common. if (numProperties == 0) { propertiesHash = _EMPTY_ARRAY_KECCAK256; } else if (numProperties == 1) { Property memory property = properties[0]; if (address(property.propertyValidator) == address(0) && property.propertyData.length == 0) { propertiesHash = _NULL_PROPERTY_STRUCT_HASH; } else { // propertiesHash = keccak256(abi.encodePacked(keccak256(abi.encode( // _PROPERTY_TYPE_HASH, // properties[0].propertyValidator, // keccak256(properties[0].propertyData) // )))); bytes32 dataHash = keccak256(property.propertyData); assembly { // Load free memory pointer let mem := mload(64) mstore(mem, _PROPERTY_TYPE_HASH) // property.propertyValidator mstore(add(mem, 32), and(ADDRESS_MASK, mload(property))) // keccak256(property.propertyData) mstore(add(mem, 64), dataHash) mstore(mem, keccak256(mem, 96)) propertiesHash := keccak256(mem, 32) } } } else { bytes32[] memory propertyStructHashArray = new bytes32[](numProperties); for (uint256 i = 0; i < numProperties; i++) { propertyStructHashArray[i] = keccak256(abi.encode( _PROPERTY_TYPE_HASH, properties[i].propertyValidator, keccak256(properties[i].propertyData))); } assembly { propertiesHash := keccak256(add(propertyStructHashArray, 32), mul(numProperties, 32)) } } } // Hashes the `fees` array as part of computing the // EIP-712 hash of an `ERC721Order` or `ERC1155Order`. function _feesHash(Fee[] memory fees) private pure returns (bytes32 feesHash) { uint256 numFees = fees.length; // We give `fees.length == 0` and `fees.length == 1` // special treatment because we expect these to be the most common. if (numFees == 0) { feesHash = _EMPTY_ARRAY_KECCAK256; } else if (numFees == 1) { // feesHash = keccak256(abi.encodePacked(keccak256(abi.encode( // _FEE_TYPE_HASH, // fees[0].recipient, // fees[0].amount, // keccak256(fees[0].feeData) // )))); Fee memory fee = fees[0]; bytes32 dataHash = keccak256(fee.feeData); assembly { // Load free memory pointer let mem := mload(64) mstore(mem, _FEE_TYPE_HASH) // fee.recipient mstore(add(mem, 32), and(ADDRESS_MASK, mload(fee))) // fee.amount mstore(add(mem, 64), mload(add(fee, 32))) // keccak256(fee.feeData) mstore(add(mem, 96), dataHash) mstore(mem, keccak256(mem, 128)) feesHash := keccak256(mem, 32) } } else { bytes32[] memory feeStructHashArray = new bytes32[](numFees); for (uint256 i = 0; i < numFees; i++) { feeStructHashArray[i] = keccak256(abi.encode(_FEE_TYPE_HASH, fees[i].recipient, fees[i].amount, keccak256(fees[i].feeData))); } assembly { feesHash := keccak256(add(feeStructHashArray, 32), mul(numFees, 32)) } } } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; /// @dev A library for validating signatures. library LibSignature { /// @dev Allowed signature types. enum SignatureType { EIP712, PRESIGNED } /// @dev Encoded EC signature. struct Signature { // How to validate the signature. SignatureType signatureType; // EC Signature data. uint8 v; // EC Signature data. bytes32 r; // EC Signature data. bytes32 s; } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../fixins/FixinEIP712.sol"; import "../../fixins/FixinTokenSpender.sol"; import "../../vendor/IEtherToken.sol"; import "../../vendor/IFeeRecipient.sol"; import "../../vendor/ITakerCallback.sol"; import "../libs/LibSignature.sol"; import "../libs/LibNFTOrder.sol"; /// @dev Abstract base contract inherited by ERC721OrdersFeature and NFTOrders abstract contract NFTOrders is FixinEIP712, FixinTokenSpender { using LibNFTOrder for LibNFTOrder.NFTBuyOrder; /// @dev Native token pseudo-address. address constant internal NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev The WETH token contract. IEtherToken internal immutable WETH; /// @dev The implementation address of this feature. address internal immutable _implementation; /// @dev The magic return value indicating the success of a `receiveZeroExFeeCallback`. bytes4 private constant FEE_CALLBACK_MAGIC_BYTES = IFeeRecipient.receiveZeroExFeeCallback.selector; /// @dev The magic return value indicating the success of a `zeroExTakerCallback`. bytes4 private constant TAKER_CALLBACK_MAGIC_BYTES = ITakerCallback.zeroExTakerCallback.selector; constructor(IEtherToken weth) { require(address(weth) != address(0), "WETH_ADDRESS_ERROR"); WETH = weth; // Remember this feature's original address. _implementation = address(this); } struct SellParams { uint128 sellAmount; uint256 tokenId; bool unwrapNativeToken; address taker; address currentNftOwner; bytes takerCallbackData; } struct BuyParams { uint128 buyAmount; uint256 ethAvailable; address taker; bytes takerCallbackData; } // Core settlement logic for selling an NFT asset. function _sellNFT( LibNFTOrder.NFTBuyOrder memory buyOrder, LibSignature.Signature memory signature, SellParams memory params ) internal returns (uint256 erc20FillAmount, bytes32 orderHash) { LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(buyOrder); orderHash = orderInfo.orderHash; // Check that the order can be filled. _validateBuyOrder(buyOrder, signature, orderInfo, params.taker, params.tokenId); // Check amount. if (params.sellAmount > orderInfo.remainingAmount) { revert("_sellNFT/EXCEEDS_REMAINING_AMOUNT"); } // Update the order state. _updateOrderState(buyOrder.asNFTSellOrder(), orderInfo.orderHash, params.sellAmount); // Calculate erc20 pay amount. erc20FillAmount = (params.sellAmount == orderInfo.orderAmount) ? buyOrder.erc20TokenAmount : buyOrder.erc20TokenAmount * params.sellAmount / orderInfo.orderAmount; if (params.unwrapNativeToken) { // The ERC20 token must be WETH for it to be unwrapped. require(buyOrder.erc20Token == WETH, "_sellNFT/ERC20_TOKEN_MISMATCH_ERROR"); // Transfer the WETH from the maker to the Exchange Proxy // so we can unwrap it before sending it to the seller. // TODO: Probably safe to just use WETH.transferFrom for some // small gas savings _transferERC20TokensFrom(WETH, buyOrder.maker, address(this), erc20FillAmount); // Unwrap WETH into ETH. WETH.withdraw(erc20FillAmount); // Send ETH to the seller. _transferEth(payable(params.taker), erc20FillAmount); } else { // Transfer the ERC20 token from the buyer to the seller. _transferERC20TokensFrom(buyOrder.erc20Token, buyOrder.maker, params.taker, erc20FillAmount); } if (params.takerCallbackData.length > 0) { require(params.taker != address(this), "_sellNFT/CANNOT_CALLBACK_SELF"); // Invoke the callback bytes4 callbackResult = ITakerCallback(params.taker).zeroExTakerCallback(orderInfo.orderHash, params.takerCallbackData); // Check for the magic success bytes require(callbackResult == TAKER_CALLBACK_MAGIC_BYTES, "_sellNFT/CALLBACK_FAILED"); } // Transfer the NFT asset to the buyer. // If this function is called from the // `onNFTReceived` callback the Exchange Proxy // holds the asset. Otherwise, transfer it from // the seller. _transferNFTAssetFrom(buyOrder.nft, params.currentNftOwner, buyOrder.maker, params.tokenId, params.sellAmount); // The buyer pays the order fees. _payFees(buyOrder.asNFTSellOrder(), buyOrder.maker, params.sellAmount, orderInfo.orderAmount, false); } // Core settlement logic for buying an NFT asset. function _buyNFT( LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature, uint128 buyAmount ) internal returns (uint256 erc20FillAmount, bytes32 orderHash) { LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(sellOrder); orderHash = orderInfo.orderHash; // Check that the order can be filled. _validateSellOrder(sellOrder, signature, orderInfo, msg.sender); // Check amount. if (buyAmount > orderInfo.remainingAmount) { revert("_buyNFT/EXCEEDS_REMAINING_AMOUNT"); } // Update the order state. _updateOrderState(sellOrder, orderInfo.orderHash, buyAmount); // Calculate erc20 pay amount. erc20FillAmount = (buyAmount == orderInfo.orderAmount) ? sellOrder.erc20TokenAmount : _ceilDiv(sellOrder.erc20TokenAmount * buyAmount, orderInfo.orderAmount); // Transfer the NFT asset to the buyer (`msg.sender`). _transferNFTAssetFrom(sellOrder.nft, sellOrder.maker, msg.sender, sellOrder.nftId, buyAmount); if (address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS) { // Transfer ETH to the seller. _transferEth(payable(sellOrder.maker), erc20FillAmount); // Fees are paid from the EP's current balance of ETH. _payFees(sellOrder, address(this), buyAmount, orderInfo.orderAmount, true); } else { // Transfer ERC20 token from the buyer to the seller. _transferERC20TokensFrom(sellOrder.erc20Token, msg.sender, sellOrder.maker, erc20FillAmount); // The buyer pays fees. _payFees(sellOrder, msg.sender, buyAmount, orderInfo.orderAmount, false); } } function _buyNFTEx( LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature, BuyParams memory params ) internal returns (uint256 erc20FillAmount, bytes32 orderHash) { LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(sellOrder); orderHash = orderInfo.orderHash; // Check that the order can be filled. _validateSellOrder(sellOrder, signature, orderInfo, params.taker); // Check amount. if (params.buyAmount > orderInfo.remainingAmount) { revert("_buyNFTEx/EXCEEDS_REMAINING_AMOUNT"); } // Update the order state. _updateOrderState(sellOrder, orderInfo.orderHash, params.buyAmount); // Dutch Auction if (sellOrder.expiry >> 252 == 1) { uint256 count = (sellOrder.expiry >> 64) & 0xffffffff; if (count > 0) { _resetDutchAuctionTokenAmountAndFees(sellOrder, count); } } // Calculate erc20 pay amount. erc20FillAmount = (params.buyAmount == orderInfo.orderAmount) ? sellOrder.erc20TokenAmount : _ceilDiv(sellOrder.erc20TokenAmount * params.buyAmount, orderInfo.orderAmount); // Transfer the NFT asset to the buyer. _transferNFTAssetFrom(sellOrder.nft, sellOrder.maker, params.taker, sellOrder.nftId, params.buyAmount); uint256 ethAvailable = params.ethAvailable; if (params.takerCallbackData.length > 0) { require(params.taker != address(this), "_buyNFTEx/CANNOT_CALLBACK_SELF"); uint256 ethBalanceBeforeCallback = address(this).balance; // Invoke the callback bytes4 callbackResult = ITakerCallback(params.taker).zeroExTakerCallback(orderInfo.orderHash, params.takerCallbackData); // Update `ethAvailable` with amount acquired during // the callback ethAvailable += address(this).balance - ethBalanceBeforeCallback; // Check for the magic success bytes require(callbackResult == TAKER_CALLBACK_MAGIC_BYTES, "_buyNFTEx/CALLBACK_FAILED"); } if (address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS) { uint256 totalPaid = erc20FillAmount + _calcTotalFeesPaid(sellOrder.fees, params.buyAmount, orderInfo.orderAmount); if (ethAvailable < totalPaid) { // Transfer WETH from the buyer to this contract. uint256 withDrawAmount = totalPaid - ethAvailable; _transferERC20TokensFrom(WETH, msg.sender, address(this), withDrawAmount); // Unwrap WETH into ETH. WETH.withdraw(withDrawAmount); } // Transfer ETH to the seller. _transferEth(payable(sellOrder.maker), erc20FillAmount); // Fees are paid from the EP's current balance of ETH. _payFees(sellOrder, address(this), params.buyAmount, orderInfo.orderAmount, true); } else if (sellOrder.erc20Token == WETH) { uint256 totalFeesPaid = _calcTotalFeesPaid(sellOrder.fees, params.buyAmount, orderInfo.orderAmount); if (ethAvailable > totalFeesPaid) { uint256 depositAmount = ethAvailable - totalFeesPaid; if (depositAmount < erc20FillAmount) { // Transfer WETH from the buyer to this contract. _transferERC20TokensFrom(WETH, msg.sender, address(this), (erc20FillAmount - depositAmount)); } else { depositAmount = erc20FillAmount; } // Wrap ETH. WETH.deposit{value: depositAmount}(); // Transfer WETH to the seller. _transferERC20Tokens(WETH, sellOrder.maker, erc20FillAmount); // Fees are paid from the EP's current balance of ETH. _payFees(sellOrder, address(this), params.buyAmount, orderInfo.orderAmount, true); } else { // Transfer WETH from the buyer to the seller. _transferERC20TokensFrom(WETH, msg.sender, sellOrder.maker, erc20FillAmount); if (ethAvailable > 0) { if (ethAvailable < totalFeesPaid) { // Transfer WETH from the buyer to this contract. uint256 value = totalFeesPaid - ethAvailable; _transferERC20TokensFrom(WETH, msg.sender, address(this), value); // Unwrap WETH into ETH. WETH.withdraw(value); } // Fees are paid from the EP's current balance of ETH. _payFees(sellOrder, address(this), params.buyAmount, orderInfo.orderAmount, true); } else { // The buyer pays fees using WETH. _payFees(sellOrder, msg.sender, params.buyAmount, orderInfo.orderAmount, false); } } } else { // Transfer ERC20 token from the buyer to the seller. _transferERC20TokensFrom(sellOrder.erc20Token, msg.sender, sellOrder.maker, erc20FillAmount); // The buyer pays fees. _payFees(sellOrder, msg.sender, params.buyAmount, orderInfo.orderAmount, false); } } function _validateSellOrder( LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature, LibNFTOrder.OrderInfo memory orderInfo, address taker ) internal view { // Taker must match the order taker, if one is specified. require(sellOrder.taker == address(0) || sellOrder.taker == taker, "_validateOrder/ONLY_TAKER"); // Check that the order is valid and has not expired, been cancelled, // or been filled. require(orderInfo.status == LibNFTOrder.OrderStatus.FILLABLE, "_validateOrder/ORDER_NOT_FILL"); // Check the signature. _validateOrderSignature(orderInfo.orderHash, signature, sellOrder.maker); } function _validateBuyOrder( LibNFTOrder.NFTBuyOrder memory buyOrder, LibSignature.Signature memory signature, LibNFTOrder.OrderInfo memory orderInfo, address taker, uint256 tokenId ) internal view { // The ERC20 token cannot be ETH. require(address(buyOrder.erc20Token) != NATIVE_TOKEN_ADDRESS, "_validateBuyOrder/TOKEN_MISMATCH"); // Taker must match the order taker, if one is specified. require(buyOrder.taker == address(0) || buyOrder.taker == taker, "_validateBuyOrder/ONLY_TAKER"); // Check that the order is valid and has not expired, been cancelled, // or been filled. require(orderInfo.status == LibNFTOrder.OrderStatus.FILLABLE, "_validateOrder/ORDER_NOT_FILL"); // Check that the asset with the given token ID satisfies the properties // specified by the order. _validateOrderProperties(buyOrder, tokenId); // Check the signature. _validateOrderSignature(orderInfo.orderHash, signature, buyOrder.maker); } function _resetDutchAuctionTokenAmountAndFees(LibNFTOrder.NFTSellOrder memory order, uint256 count) internal view { require(count <= 100000000, "COUNT_OUT_OF_SIDE"); uint256 listingTime = (order.expiry >> 32) & 0xffffffff; uint256 denominator = ((order.expiry & 0xffffffff) - listingTime) * 100000000; uint256 multiplier = (block.timestamp - listingTime) * count; // Reset erc20TokenAmount uint256 amount = order.erc20TokenAmount; order.erc20TokenAmount = amount - amount * multiplier / denominator; // Reset fees for (uint256 i = 0; i < order.fees.length; i++) { amount = order.fees[i].amount; order.fees[i].amount = amount - amount * multiplier / denominator; } } function _resetEnglishAuctionTokenAmountAndFees( LibNFTOrder.NFTSellOrder memory sellOrder, uint256 buyERC20Amount, uint256 fillAmount, uint256 orderAmount ) internal pure { uint256 sellOrderFees = _calcTotalFeesPaid(sellOrder.fees, fillAmount, orderAmount); uint256 sellTotalAmount = sellOrderFees + sellOrder.erc20TokenAmount; if (buyERC20Amount != sellTotalAmount) { uint256 spread = buyERC20Amount - sellTotalAmount; uint256 sum; // Reset fees if (sellTotalAmount > 0) { for (uint256 i = 0; i < sellOrder.fees.length; i++) { uint256 diff = spread * sellOrder.fees[i].amount / sellTotalAmount; sellOrder.fees[i].amount += diff; sum += diff; } } // Reset erc20TokenAmount sellOrder.erc20TokenAmount += spread - sum; } } function _ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // ceil(a / b) = floor((a + b - 1) / b) return (a + b - 1) / b; } function _calcTotalFeesPaid(LibNFTOrder.Fee[] memory fees, uint256 fillAmount, uint256 orderAmount) private pure returns (uint256 totalFeesPaid) { if (fillAmount == orderAmount) { for (uint256 i = 0; i < fees.length; i++) { totalFeesPaid += fees[i].amount; } } else { for (uint256 i = 0; i < fees.length; i++) { totalFeesPaid += fees[i].amount * fillAmount / orderAmount; } } return totalFeesPaid; } function _payFees( LibNFTOrder.NFTSellOrder memory order, address payer, uint128 fillAmount, uint128 orderAmount, bool useNativeToken ) internal returns (uint256 totalFeesPaid) { for (uint256 i = 0; i < order.fees.length; i++) { LibNFTOrder.Fee memory fee = order.fees[i]; uint256 feeFillAmount = (fillAmount == orderAmount) ? fee.amount : fee.amount * fillAmount / orderAmount; if (useNativeToken) { // Transfer ETH to the fee recipient. _transferEth(payable(fee.recipient), feeFillAmount); } else { if (feeFillAmount > 0) { // Transfer ERC20 token from payer to recipient. _transferERC20TokensFrom(order.erc20Token, payer, fee.recipient, feeFillAmount); } } // Note that the fee callback is _not_ called if zero // `feeData` is provided. If `feeData` is provided, we assume // the fee recipient is a contract that implements the // `IFeeRecipient` interface. if (fee.feeData.length > 0) { // Invoke the callback bytes4 callbackResult = IFeeRecipient(fee.recipient).receiveZeroExFeeCallback( useNativeToken ? NATIVE_TOKEN_ADDRESS : address(order.erc20Token), feeFillAmount, fee.feeData ); // Check for the magic success bytes require(callbackResult == FEE_CALLBACK_MAGIC_BYTES, "_payFees/CALLBACK_FAILED"); } // Sum the fees paid totalFeesPaid += feeFillAmount; } return totalFeesPaid; } function _validateOrderProperties(LibNFTOrder.NFTBuyOrder memory order, uint256 tokenId) internal view { // If no properties are specified, check that the given // `tokenId` matches the one specified in the order. if (order.nftProperties.length == 0) { require(tokenId == order.nftId, "_validateProperties/TOKEN_ID_ERR"); } else { // Validate each property for (uint256 i = 0; i < order.nftProperties.length; i++) { LibNFTOrder.Property memory property = order.nftProperties[i]; // `address(0)` is interpreted as a no-op. Any token ID // will satisfy a property with `propertyValidator == address(0)`. if (address(property.propertyValidator) != address(0)) { // Call the property validator and throw a descriptive error // if the call reverts. try property.propertyValidator.validateProperty(order.nft, tokenId, property.propertyData) { } catch (bytes memory /* reason */) { revert("PROPERTY_VALIDATION_FAILED"); } } } } } /// @dev Validates that the given signature is valid for the /// given maker and order hash. Reverts if the signature /// is not valid. /// @param orderHash The hash of the order that was signed. /// @param signature The signature to check. /// @param maker The maker of the order. function _validateOrderSignature(bytes32 orderHash, LibSignature.Signature memory signature, address maker) internal virtual view; /// @dev Transfers an NFT asset. /// @param token The address of the NFT contract. /// @param from The address currently holding the asset. /// @param to The address to transfer the asset to. /// @param tokenId The ID of the asset to transfer. /// @param amount The amount of the asset to transfer. Always /// 1 for ERC721 assets. function _transferNFTAssetFrom(address token, address from, address to, uint256 tokenId, uint256 amount) internal virtual; /// @dev Updates storage to indicate that the given order /// has been filled by the given amount. /// @param order The order that has been filled. /// @param orderHash The hash of `order`. /// @param fillAmount The amount (denominated in the NFT asset) /// that the order has been filled by. function _updateOrderState(LibNFTOrder.NFTSellOrder memory order, bytes32 orderHash, uint128 fillAmount) internal virtual; /// @dev Get the order info for an NFT sell order. /// @param nftSellOrder The NFT sell order. /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTSellOrder memory nftSellOrder) internal virtual view returns (LibNFTOrder.OrderInfo memory); /// @dev Get the order info for an NFT buy order. /// @param nftBuyOrder The NFT buy order. /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTBuyOrder memory nftBuyOrder) internal virtual view returns (LibNFTOrder.OrderInfo memory); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; /// @dev Common storage helpers library LibStorage { /// @dev What to bit-shift a storage ID by to get its slot. /// This gives us a maximum of 2**128 inline fields in each bucket. uint256 constant STORAGE_ID_PROXY = 1 << 128; uint256 constant STORAGE_ID_SIMPLE_FUNCTION_REGISTRY = 2 << 128; uint256 constant STORAGE_ID_OWNABLE = 3 << 128; uint256 constant STORAGE_ID_COMMON_NFT_ORDERS = 4 << 128; uint256 constant STORAGE_ID_ERC721_ORDERS = 5 << 128; uint256 constant STORAGE_ID_ERC1155_ORDERS = 6 << 128; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../libs/LibNFTOrder.sol"; interface IERC1155OrdersEvent { /// @dev Emitted whenever an `ERC1155SellOrder` is filled. /// @param maker The maker of the order. /// @param taker The taker of the order. /// @param erc20Token (96bit ERC20FillAmount + 160bit ERC20TokenAddress). /// @param erc1155Token (96bit ERC1155TokenId + 160bit ERC1155TokenAddress). /// @param erc1155FillAmount The amount of ERC1155 asset filled. event ERC1155SellOrderFilled( address maker, address taker, uint256 erc20Token, uint256 erc1155Token, uint128 erc1155FillAmount, bytes32 orderHash ); /// @dev Emitted whenever an `ERC1155BuyOrder` is filled. /// @param maker The maker of the order. /// @param taker The taker of the order. /// @param erc20Token (96bit ERC20FillAmount + 160bit ERC20TokenAddress). /// @param erc1155Token (96bit ERC1155TokenId + 160bit ERC1155TokenAddress). /// @param erc1155FillAmount The amount of ERC1155 asset filled. event ERC1155BuyOrderFilled( address maker, address taker, uint256 erc20Token, uint256 erc1155Token, uint128 erc1155FillAmount, bytes32 orderHash ); /// @dev Emitted when an `ERC1155SellOrder` is pre-signed. /// Contains all the fields of the order. event ERC1155SellOrderPreSigned( address maker, address taker, uint256 expiry, uint256 nonce, IERC20 erc20Token, uint256 erc20TokenAmount, LibNFTOrder.Fee[] fees, address erc1155Token, uint256 erc1155TokenId, uint128 erc1155TokenAmount ); /// @dev Emitted when an `ERC1155BuyOrder` is pre-signed. /// Contains all the fields of the order. event ERC1155BuyOrderPreSigned( address maker, address taker, uint256 expiry, uint256 nonce, IERC20 erc20Token, uint256 erc20TokenAmount, LibNFTOrder.Fee[] fees, address erc1155Token, uint256 erc1155TokenId, LibNFTOrder.Property[] erc1155TokenProperties, uint128 erc1155TokenAmount ); /// @dev Emitted whenever an `ERC1155Order` is cancelled. /// @param maker The maker of the order. /// @param nonce The nonce of the order that was cancelled. event ERC1155OrderCancelled(address maker, uint256 nonce); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; interface IPropertyValidator { /// @dev Checks that the given ERC721/ERC1155 asset satisfies the properties encoded in `propertyData`. /// Should revert if the asset does not satisfy the specified properties. /// @param tokenAddress The ERC721/ERC1155 token contract address. /// @param tokenId The ERC721/ERC1155 tokenId of the asset to check. /// @param propertyData Encoded properties or auxiliary data needed to perform the check. function validateProperty(address tokenAddress, uint256 tokenId, bytes calldata propertyData) external view; } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; /// @dev EIP712 helpers for features. abstract contract FixinEIP712 { bytes32 private constant DOMAIN = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bytes32 private constant NAME = keccak256("ElementEx"); bytes32 private constant VERSION = keccak256("1.0.0"); uint256 private immutable CHAIN_ID; constructor() { uint256 chainId; assembly { chainId := chainid() } CHAIN_ID = chainId; } function _getEIP712Hash(bytes32 structHash) internal view returns (bytes32) { return keccak256(abi.encodePacked(hex"1901", keccak256(abi.encode(DOMAIN, NAME, VERSION, CHAIN_ID, address(this))), structHash)); } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; /// @dev Helpers for moving tokens around. abstract contract FixinTokenSpender { // Mask of the lower 20 bytes of a bytes32. uint256 constant private ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; /// @dev Transfers ERC20 tokens from `owner` to `to`. /// @param token The token to spend. /// @param owner The owner of the tokens. /// @param to The recipient of the tokens. /// @param amount The amount of `token` to transfer. function _transferERC20TokensFrom(IERC20 token, address owner, address to, uint256 amount) internal { uint256 success; assembly { let ptr := mload(0x40) // free memory pointer // selector for transferFrom(address,address,uint256) mstore(ptr, 0x23b872dd00000000000000000000000000000000000000000000000000000000) mstore(add(ptr, 0x04), and(owner, ADDRESS_MASK)) mstore(add(ptr, 0x24), and(to, ADDRESS_MASK)) mstore(add(ptr, 0x44), amount) success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0x64, ptr, 32) let rdsize := returndatasize() // Check for ERC20 success. ERC20 tokens should return a boolean, // but some don't. We accept 0-length return data as success, or at // least 32 bytes that starts with a 32-byte boolean true. success := and( success, // call itself succeeded or( iszero(rdsize), // no return data, or and( iszero(lt(rdsize, 32)), // at least 32 bytes eq(mload(ptr), 1) // starts with uint256(1) ) ) ) } require(success != 0, "_transferERC20/TRANSFER_FAILED"); } /// @dev Transfers ERC20 tokens from ourselves to `to`. /// @param token The token to spend. /// @param to The recipient of the tokens. /// @param amount The amount of `token` to transfer. function _transferERC20Tokens(IERC20 token, address to, uint256 amount) internal { uint256 success; assembly { let ptr := mload(0x40) // free memory pointer // selector for transfer(address,uint256) mstore(ptr, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) mstore(add(ptr, 0x04), and(to, ADDRESS_MASK)) mstore(add(ptr, 0x24), amount) success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0x44, ptr, 32) let rdsize := returndatasize() // Check for ERC20 success. ERC20 tokens should return a boolean, // but some don't. We accept 0-length return data as success, or at // least 32 bytes that starts with a 32-byte boolean true. success := and( success, // call itself succeeded or( iszero(rdsize), // no return data, or and( iszero(lt(rdsize, 32)), // at least 32 bytes eq(mload(ptr), 1) // starts with uint256(1) ) ) ) } require(success != 0, "_transferERC20/TRANSFER_FAILED"); } /// @dev Transfers some amount of ETH to the given recipient and /// reverts if the transfer fails. /// @param recipient The recipient of the ETH. /// @param amount The amount of ETH to transfer. function _transferEth(address payable recipient, uint256 amount) internal { if (amount > 0) { (bool success,) = recipient.call{value: amount}(""); require(success, "_transferEth/TRANSFER_FAILED"); } } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2022 Element.Market 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.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IEtherToken is IERC20 { /// @dev Wrap ether. function deposit() external payable; /// @dev Unwrap ether. function withdraw(uint256 amount) external; } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; interface IFeeRecipient { /// @dev A callback function invoked in the ERC721Feature for each ERC721 /// order fee that get paid. Integrators can make use of this callback /// to implement arbitrary fee-handling logic, e.g. splitting the fee /// between multiple parties. /// @param tokenAddress The address of the token in which the received fee is /// denominated. `0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE` indicates /// that the fee was paid in the native token (e.g. ETH). /// @param amount The amount of the given token received. /// @param feeData Arbitrary data encoded in the `Fee` used by this callback. /// @return success The selector of this function (0x0190805e), /// indicating that the callback succeeded. function receiveZeroExFeeCallback(address tokenAddress, uint256 amount, bytes calldata feeData) external returns (bytes4 success); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; interface ITakerCallback { /// @dev A taker callback function invoked in ERC721OrdersFeature and /// ERC1155OrdersFeature between the maker -> taker transfer and /// the taker -> maker transfer. /// @param orderHash The hash of the order being filled when this /// callback is invoked. /// @param data Arbitrary data used by this callback. /// @return success The selector of this function, /// indicating that the callback succeeded. function zeroExTakerCallback(bytes32 orderHash, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } }
Core settlement logic for buying an ERC1155 asset. Used by `buyERC1155` and `batchBuyERC1155s`.
function _buyERC1155( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, uint128 buyAmount ) internal { (uint256 erc20FillAmount, bytes32 orderHash) = _buyNFT( sellOrder.asNFTSellOrder(), signature, buyAmount ); emit ERC1155SellOrderFilled( sellOrder.maker, msg.sender, (erc20FillAmount << 160) | uint160(address(sellOrder.erc20Token)), (sellOrder.erc1155TokenId << 160) | uint160(sellOrder.erc1155Token), buyAmount, orderHash ); }
1,499,014
./full_match/11155111/0xF3B8ea87e9783CbA0609372161FD6067f579f191/sources/myTokenContract.sol
Setter function to change the contractWebPage. Only callable by the owner.
function setDigitalTwin(string memory newDigitalTwin) public onlyOwner { _digitalTwin = newDigitalTwin; }
3,814,534
pragma solidity ^0.4.24; // File: contracts\utils\SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } } // File: contracts\CKingCal.sol library CKingCal { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth total ether received. * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { // sqrt((eth*1 eth* 312500000000000000000000000)+5624988281256103515625000000000000000000000000000000000000000000) - 74999921875000000000000000000000) / 15625000 return ((((((_eth).mul(1000000000000000000)).mul(31250000000000000000000000)).add(56249882812561035156250000000000000000000000000000000000000000)).sqrt()).sub(7499992187500000000000000000000)) / (15625000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { // (149999843750000*keys*1 eth) + 78125000 * keys * keys) /2 /(sq(1 ether)) return ((7812500).mul(_keys.sq()).add(((14999984375000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } // File: contracts\utils\Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts\TowerCKing.sol contract CKing is Ownable { using SafeMath for *; using CKingCal for uint256; string constant public name = "Cryptower"; string constant public symbol = "CT"; // time constants; uint256 constant private timeInit = 1 weeks; // 600; //1 week uint256 constant private timeInc = 30 seconds; //60 /////// uint256 constant private timeMax = 30 minutes; // 300 // profit distribution parameters uint256 constant private fixRet = 46; uint256 constant private extraRet = 10; uint256 constant private affRet = 10; uint256 constant private gamePrize = 12; uint256 constant private groupPrize = 12; uint256 constant private devTeam = 10; // player data struct Player { address addr; // player address string name; // playerName uint256 aff; // affliliate vault uint256 affId; // affiliate id, who referered u uint256 hretKeys; // number of high return keys uint256 mretKeys; // number of medium return keys uint256 lretKeys; // number of low return keys uint256 eth; // total eth spend for the keys uint256 ethWithdraw; // earning withdrawed by user } mapping(uint256 => Player) public players; // player data mapping(address => uint) public addrXpId; // player address => pId uint public playerNum = 0; // game info uint256 public totalEther; // total key sale revenue uint256 public totalKeys; // total number of keys. uint256 private constant minPay = 1000000000; // minimum pay to buy keys or deposit in game; uint256 public totalCommPot; // total ether going to be distributed uint256 private keysForGame; // keys belongs to the game for profit distribution uint256 private gamePot; // ether need to be distributed based on the side chain game uint256 public teamWithdrawed; // eth withdrawed by dev team. uint256 public gameWithdrawed; // ether already been withdrawn from game pot uint256 public endTime; // main game end time address public CFO; address public COO; address public fundCenter; address public playerBook; uint private stageId = 1; // stageId start 1 uint private constant groupPrizeStartAt = 2000000000000000000000000; // 1000000000000000000000; uint private constant groupPrizeStageGap = 100000000000000000000000; // 100000000000000000000 mapping(uint => mapping(uint => uint)) public stageInfo; // stageId => pID => keys purchased in this stage // admin params uint256 public startTime; // admin set start uint256 constant private coolDownTime = 2 days; // team is able to withdraw fund 2 days after game end. modifier isGameActive() { uint _now = now; require(_now > startTime && _now < endTime); _; } modifier onlyCOO() { require(COO == msg.sender, "Only COO can operate."); _; } // events event BuyKey(uint indexed _pID, uint _affId, uint _keyType, uint _keyAmount); event EarningWithdraw(uint indexed _pID, address _addr, uint _amount); constructor(address _CFO, address _COO, address _fundCenter, address _playerBook) public { CFO = _CFO; COO = _COO; fundCenter = _fundCenter; playerBook = _playerBook; } function setCFO(address _CFO) onlyOwner public { CFO = _CFO; } function setCOO(address _COO) onlyOwner public { COO = _COO; } function setContractAddress(address _fundCenter, address _playerBook) onlyCOO public { fundCenter = _fundCenter; playerBook = _playerBook; } function startGame(uint _startTime) onlyCOO public { require(_startTime > now); startTime = _startTime; endTime = startTime.add(timeInit); } function gameWithdraw(uint _amount) onlyCOO public { // users may choose to withdraw eth from cryptower game, allow dev team to withdraw eth from this contract to fund center. uint _total = getTotalGamePot(); uint _remainingBalance = _total.sub(gameWithdrawed); if(_amount > 0) { require(_amount <= _remainingBalance); } else{ _amount = _remainingBalance; } fundCenter.transfer(_amount); gameWithdrawed = gameWithdrawed.add(_amount); } function teamWithdraw(uint _amount) onlyCOO public { uint256 _now = now; if(_now > endTime.add(coolDownTime)) { // dev team have rights to withdraw all remaining balance 2 days after game end. // if users does not claim their ETH within coolDown period, the team may withdraw their remaining balance. Users can go to crytower game to get their ETH back. CFO.transfer(_amount); teamWithdrawed = teamWithdrawed.add(_amount); } else { uint _total = totalEther.mul(devTeam).div(100); uint _remainingBalance = _total.sub(teamWithdrawed); if(_amount > 0) { require(_amount <= _remainingBalance); } else{ _amount = _remainingBalance; } CFO.transfer(_amount); teamWithdrawed = teamWithdrawed.add(_amount); } } function updateTimer(uint256 _keys) private { uint256 _now = now; uint256 _newTime; if(endTime.sub(_now) < timeMax) { _newTime = ((_keys) / (1000000000000000000)).mul(timeInc).add(endTime); if(_newTime.sub(_now) > timeMax) { _newTime = _now.add(timeMax); } endTime = _newTime; } } function receivePlayerInfo(address _addr, string _name) external { require(msg.sender == playerBook, "must be from playerbook address"); uint _pID = addrXpId[_addr]; if(_pID == 0) { // player not exist yet. create one playerNum = playerNum + 1; Player memory p; p.addr = _addr; p.name = _name; players[playerNum] = p; _pID = playerNum; addrXpId[_addr] = _pID; } else { players[_pID].name = _name; } } function buyByAddress(uint256 _affId, uint _keyType) payable isGameActive public { uint _pID = addrXpId[msg.sender]; if(_pID == 0) { // player not exist yet. create one playerNum = playerNum + 1; Player memory p; p.addr = msg.sender; p.affId = _affId; players[playerNum] = p; _pID = playerNum; addrXpId[msg.sender] = _pID; } buy(_pID, msg.value, _affId, _keyType); } function buyFromVault(uint _amount, uint256 _affId, uint _keyType) public isGameActive { uint _pID = addrXpId[msg.sender]; uint _earning = getPlayerEarning(_pID); uint _newEthWithdraw = _amount.add(players[_pID].ethWithdraw); require(_newEthWithdraw < _earning); // withdraw amount cannot bigger than earning players[_pID].ethWithdraw = _newEthWithdraw; // update player withdraw buy(_pID, _amount, _affId, _keyType); } function getKeyPrice(uint _keyAmount) public view returns(uint256) { if(now > startTime) { return totalKeys.add(_keyAmount).ethRec(_keyAmount); } else { // copy fomo init price return (7500000000000); } } function buy(uint256 _pID, uint256 _eth, uint256 _affId, uint _keyType) private { if (_eth > minPay) { // bigger than minimum pay players[_pID].eth = _eth.add(players[_pID].eth); uint _keys = totalEther.keysRec(_eth); //bought at least 1 whole key if(_keys >= 1000000000000000000) { updateTimer(_keys); } //update total ether and total keys totalEther = totalEther.add(_eth); totalKeys = totalKeys.add(_keys); // update game portion uint256 _game = _eth.mul(gamePrize).div(100); gamePot = _game.add(gamePot); // update player keys and keysForGame if(_keyType == 1) { // high return key players[_pID].hretKeys = _keys.add(players[_pID].hretKeys); } else if (_keyType == 2) { players[_pID].mretKeys = _keys.add(players[_pID].mretKeys); keysForGame = keysForGame.add(_keys.mul(extraRet).div(fixRet+extraRet)); } else if (_keyType == 3) { players[_pID].lretKeys = _keys.add(players[_pID].lretKeys); keysForGame = keysForGame.add(_keys); } else { // keytype unknown. revert(); } //update affliliate gain if(_affId != 0 && _affId != _pID && _affId <= playerNum) { // udate players uint256 _aff = _eth.mul(affRet).div(100); players[_affId].aff = _aff.add(players[_affId].aff); totalCommPot = (_eth.mul(fixRet+extraRet).div(100)).add(totalCommPot); } else { // addId == 0 or _affId is self, put the fund into earnings per key totalCommPot = (_eth.mul(fixRet+extraRet+affRet).div(100)).add(totalCommPot); } // update stage info if(totalKeys > groupPrizeStartAt) { updateStageInfo(_pID, _keys); } emit BuyKey(_pID, _affId, _keyType, _keys); } else { // if contribute less than the minimum conntribution return to player aff vault players[_pID].aff = _eth.add(players[_pID].aff); } } function updateStageInfo(uint _pID, uint _keyAmount) private { uint _stageL = groupPrizeStartAt.add(groupPrizeStageGap.mul(stageId - 1)); uint _stageH = groupPrizeStartAt.add(groupPrizeStageGap.mul(stageId)); if(totalKeys > _stageH) { // game has been pushed to next stage stageId = (totalKeys.sub(groupPrizeStartAt)).div(groupPrizeStageGap) + 1; _keyAmount = (totalKeys.sub(groupPrizeStartAt)) % groupPrizeStageGap; stageInfo[stageId][_pID] = stageInfo[stageId][_pID].add(_keyAmount); } else { if(_keyAmount < totalKeys.sub(_stageL)) { stageInfo[stageId][_pID] = stageInfo[stageId][_pID].add(_keyAmount); } else { _keyAmount = totalKeys.sub(_stageL); stageInfo[stageId][_pID] = stageInfo[stageId][_pID].add(_keyAmount); } } } function withdrawEarning(uint256 _amount) public { address _addr = msg.sender; uint256 _pID = addrXpId[_addr]; require(_pID != 0); // player must exist uint _earning = getPlayerEarning(_pID); uint _remainingBalance = _earning.sub(players[_pID].ethWithdraw); if(_amount > 0) { require(_amount <= _remainingBalance); }else{ _amount = _remainingBalance; } _addr.transfer(_amount); // transfer remaining balance to players[_pID].ethWithdraw = players[_pID].ethWithdraw.add(_amount); } function getPlayerEarning(uint256 _pID) view public returns (uint256) { Player memory p = players[_pID]; uint _gain = totalCommPot.mul(p.hretKeys.add(p.mretKeys.mul(fixRet).div(fixRet+extraRet))).div(totalKeys); uint _total = _gain.add(p.aff); _total = getWinnerPrize(_pID).add(_total); return _total; } function getPlayerWithdrawEarning(uint _pid) public view returns(uint){ uint _earning = getPlayerEarning(_pid); return _earning.sub(players[_pid].ethWithdraw); } function getWinnerPrize(uint256 _pID) view public returns (uint256) { uint _keys; uint _pKeys; if(now < endTime) { return 0; } else if(totalKeys > groupPrizeStartAt) { // keys in the winner stage share the group prize _keys = totalKeys.sub(groupPrizeStartAt.add(groupPrizeStageGap.mul(stageId - 1))); _pKeys = stageInfo[stageId][_pID]; return totalEther.mul(groupPrize).div(100).mul(_pKeys).div(_keys); } else { // totalkeys does not meet the minimum group prize criteria, all keys share the group prize Player memory p = players[_pID]; _pKeys = p.hretKeys.add(p.mretKeys).add(p.lretKeys); return totalEther.mul(groupPrize).div(100).mul(_pKeys).div(totalKeys); } } function getWinningStageInfo() view public returns (uint256 _stageId, uint256 _keys, uint256 _amount) { _amount = totalEther.mul(groupPrize).div(100); if(totalKeys < groupPrizeStartAt) { // group prize is not activate yet return (0, totalKeys, _amount); } else { _stageId = stageId; _keys = totalKeys.sub(groupPrizeStartAt.add(groupPrizeStageGap.mul(stageId - 1))); return (_stageId, _keys, _amount); } } function getPlayerStageKeys() view public returns (uint256 _stageId, uint _keys, uint _pKeys) { uint _pID = addrXpId[msg.sender]; if(totalKeys < groupPrizeStartAt) { Player memory p = players[_pID]; _pKeys = p.hretKeys.add(p.mretKeys).add(p.lretKeys); return (0, totalKeys, _pKeys); } else { _stageId = stageId; _keys = totalKeys.sub(groupPrizeStartAt.add(groupPrizeStageGap.mul(stageId - 1))); _pKeys = stageInfo[_stageId][_pID]; return (_stageId, _keys, _pKeys); } } function getTotalGamePot() view public returns (uint256) { uint _gain = totalCommPot.mul(keysForGame).div(totalKeys); uint _total = _gain.add(gamePot); return _total; } }
users may choose to withdraw eth from cryptower game, allow dev team to withdraw eth from this contract to fund center.
function gameWithdraw(uint _amount) onlyCOO public { uint _total = getTotalGamePot(); uint _remainingBalance = _total.sub(gameWithdrawed); if(_amount > 0) { require(_amount <= _remainingBalance); _amount = _remainingBalance; } fundCenter.transfer(_amount); gameWithdrawed = gameWithdrawed.add(_amount); }
6,511,476
./full_match/1/0x4637EAef1d9488955cBf08376bb3BE0F2371A58F/sources/BancorArbitrage/contracts/token/TokenLibrary.sol
compares between a token and another raw ERC20 token/
function isEqual(Token token, IERC20 erc20Token) internal pure returns (bool) { return toIERC20(token) == erc20Token; }
16,488,632
./full_match/97/0x9FeDf352f6D8a198CE0a9C72635c19A83ba4F739/sources/project_/contracts/FundingPool.sol
Returns the installment amount to be paid at the called timestamp. Returned value is type uint256. _poolId The Id of the pool. _ERC20Address The address of the erc20 funds. _bidId The Id of the bid. _lender The lender address. return installment amount in uint256./
function viewInstallmentAmount( uint256 _poolId, address _ERC20Address, uint256 _bidId, address _lender ) external view returns(uint256){ FundDetail storage fundDetail = lenderPoolFundDetails[_lender][_poolId][ _ERC20Address ][_bidId]; uint32 LastRepaidTimestamp = fundDetail.lastRepaidTimestamp; uint256 lastPaymentCycle = BPBDTL.diffMonths( fundDetail.acceptBidTimestamp, LastRepaidTimestamp ); uint256 monthsSinceStart = BPBDTL.diffMonths( fundDetail.acceptBidTimestamp, block.timestamp ); if(monthsSinceStart > lastPaymentCycle) { return fundDetail.paymentCycleAmount; } else { return 0; } }
3,280,545
pragma solidity ^0.4.18; /** * @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; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title KOIOS * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator. * Note they can later distribute these tokens as they wish using `transfer` and other * `StandardToken` functions. */ contract KOIOSToken is StandardToken, Ownable { using SafeMath for uint256; string public name = "KOIOS"; string public symbol = "KOI"; uint256 public decimals = 5; uint256 public totalSupply = 1000000000 * (10 ** uint256(decimals)); /** * @dev Constructor that gives msg.sender all of existing tokens. */ function KOIOSToken(string _name, string _symbol, uint256 _decimals, uint256 _totalSupply) public { name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _totalSupply; totalSupply_ = _totalSupply; balances[msg.sender] = totalSupply; } /** * @dev if ether is sent to this address, send it back. */ function () public payable { revert(); } } /** * @title KOIOSTokenSale * @dev ICO Contract */ contract KOIOSTokenSale is Ownable { using SafeMath for uint256; // The token being sold, this holds reference to main token contract KOIOSToken public token; // timestamp when sale starts uint256 public startingTimestamp = 1518696000; // timestamp when sale ends uint256 public endingTimestamp = 1521115200; // how many token units a buyer gets per ether uint256 public tokenPriceInEth = 0.0001 ether; // amount of token to be sold on sale uint256 public tokensForSale = 400000000 * 1E5; // amount of token sold so far uint256 public totalTokenSold; // amount of ether raised in sale uint256 public totalEtherRaised; // ether raised per wallet mapping(address => uint256) public etherRaisedPerWallet; // wallet which will receive the ether funding address public wallet; // is contract close and ended bool internal isClose = false; // wallet changed event WalletChange(address _wallet, uint256 _timestamp); // token purchase event event TokenPurchase(address indexed _purchaser, address indexed _beneficiary, uint256 _value, uint256 _amount, uint256 _timestamp); // manual transfer by owner for external purchase event TransferManual(address indexed _from, address indexed _to, uint256 _value, string _message); /** * @dev Constructor that initializes token contract with token address in parameter * * @param _token Address of Token Contract * @param _startingTimestamp Start time of Sale in Timestamp. * @param _endingTimestamp End time of Sale in Timestamp. * @param _tokensPerEth Number of Tokens to convert per 1 ETH. * @param _tokensForSale Number of Tokens available for sale. * @param _wallet Backup Wallet Address where funds should be transfered when contract is closed or Owner wants to Withdraw. * */ function KOIOSTokenSale(address _token, uint256 _startingTimestamp, uint256 _endingTimestamp, uint256 _tokensPerEth, uint256 _tokensForSale, address _wallet) public { // set token token = KOIOSToken(_token); startingTimestamp = _startingTimestamp; endingTimestamp = _endingTimestamp; tokenPriceInEth = 1E18 / _tokensPerEth; // Calculating Price of 1 Token in ETH tokensForSale = _tokensForSale; // set wallet wallet = _wallet; } /** * @dev Function that validates if the purchase is valid by verifying the parameters * * @param value Amount of ethers sent * @param amount Total number of tokens user is trying to buy. * * @return checks various conditions and returns the bool result indicating validity. */ function isValidPurchase(uint256 value, uint256 amount) internal constant returns (bool) { // check if timestamp is falling in the range bool validTimestamp = startingTimestamp <= block.timestamp && endingTimestamp >= block.timestamp; // check if value of the ether is valid bool validValue = value != 0; // check if rate of the token is clearly defined bool validRate = tokenPriceInEth > 0; // check if the tokens available in contract for sale bool validAmount = tokensForSale.sub(totalTokenSold) >= amount && amount > 0; // validate if all conditions are met return validTimestamp && validValue && validRate && validAmount && !isClose; } /** * @dev Function that accepts ether value and returns the token amount * * @param value Amount of ethers sent * * @return checks various conditions and returns the bool result indicating validity. */ function calculate(uint256 value) public constant returns (uint256) { uint256 tokenDecimals = token.decimals(); uint256 tokens = value.mul(10 ** tokenDecimals).div(tokenPriceInEth); return tokens; } /** * @dev Default fallback method which will be called when any ethers are sent to contract */ function() public payable { buyTokens(msg.sender); } /** * @dev Function that is called either externally or by default payable method * * @param beneficiary who should receive tokens */ function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); // amount of ethers sent uint256 value = msg.value; // calculate token amount from the ethers sent uint256 tokens = calculate(value); // validate the purchase require(isValidPurchase(value , tokens)); // update the state to log the sold tokens and raised ethers. totalTokenSold = totalTokenSold.add(tokens); totalEtherRaised = totalEtherRaised.add(value); etherRaisedPerWallet[msg.sender] = etherRaisedPerWallet[msg.sender].add(value); // transfer tokens from contract balance to beneficiary account. calling ERC223 method token.transfer(beneficiary, tokens); // log event for token purchase TokenPurchase(msg.sender, beneficiary, value, tokens, now); } /** * @dev transmit token for a specified address. * This is owner only method and should be called using web3.js if someone is trying to buy token using bitcoin or any other altcoin. * * @param _to The address to transmit to. * @param _value The amount to be transferred. * @param _message message to log after transfer. */ function transferManual(address _to, uint256 _value, string _message) onlyOwner public returns (bool) { require(_to != address(0)); // transfer tokens manually from contract balance token.transfer(_to , _value); TransferManual(msg.sender, _to, _value, _message); return true; } /** * @dev withdraw funds * This will set the withdrawal wallet * * @param _wallet The address to transmit to. */ function setWallet(address _wallet) onlyOwner public returns(bool) { // set wallet wallet = _wallet; WalletChange(_wallet , now); return true; } /** * @dev Method called by owner of contract to withdraw funds */ function withdraw() onlyOwner public { wallet.transfer(this.balance); } /** * @dev close contract * This will send remaining token balance to owner * This will distribute available funds across team members */ function close() onlyOwner public { // send remaining tokens back to owner. uint256 tokens = token.balanceOf(this); token.transfer(owner , tokens); // withdraw funds withdraw(); // mark the flag to indicate closure of the contract isClose = true; } } /** * @title KOIOSTokenPreSale * @dev Pre-Sale Contract */ contract KOIOSTokenPreSale is Ownable { using SafeMath for uint256; // The token being sold, this holds reference to main token contract KOIOSToken public token; // timestamp when sale starts uint256 public startingTimestamp = 1527811200; // timestamp when sale ends uint256 public endingTimestamp = 1528156799; // how many token units a buyer gets per ether uint256 public tokenPriceInEth = 0.00005 ether; // amount of token to be sold on sale uint256 public tokensForSale = 400000000 * 1E5; // amount of token sold so far uint256 public totalTokenSold; // amount of ether raised in sale uint256 public totalEtherRaised; // ether raised per wallet mapping(address => uint256) public etherRaisedPerWallet; // wallet which will receive the ether funding address public wallet; // is contract close and ended bool internal isClose = false; // wallet changed event WalletChange(address _wallet, uint256 _timestamp); // token purchase event event TokenPurchase(address indexed _purchaser, address indexed _beneficiary, uint256 _value, uint256 _amount, uint256 _timestamp); // manual transfer by owner for external purchase event TransferManual(address indexed _from, address indexed _to, uint256 _value, string _message); // Bonus Tokens lockeup for Phase 1 mapping(address => uint256) public lockupPhase1; uint256 public phase1Duration = 90 * 86400; // Bonus Tokens lockeup for Phase 2 mapping(address => uint256) public lockupPhase2; uint256 public phase2Duration = 120 * 86400; // Bonus Tokens lockeup for Phase 3 mapping(address => uint256) public lockupPhase3; uint256 public phase3Duration = 150 * 86400; // Bonus Tokens lockeup for Phase 4 mapping(address => uint256) public lockupPhase4; uint256 public phase4Duration = 180 * 86400; uint256 public totalLockedBonus; /** * @dev Constructor that initializes token contract with token address in parameter * * @param _token Address of Token Contract * @param _startingTimestamp Start time of Sale in Timestamp. * @param _endingTimestamp End time of Sale in Timestamp. * @param _tokensPerEth Number of Tokens to convert per 1 ETH. * @param _tokensForSale Number of Tokens available for sale. * @param _wallet Backup Wallet Address where funds should be transfered when contract is closed or Owner wants to Withdraw. * */ function KOIOSTokenPreSale(address _token, uint256 _startingTimestamp, uint256 _endingTimestamp, uint256 _tokensPerEth, uint256 _tokensForSale, address _wallet) public { // set token token = KOIOSToken(_token); startingTimestamp = _startingTimestamp; endingTimestamp = _endingTimestamp; tokenPriceInEth = 1E18 / _tokensPerEth; // Calculating Price of 1 Token in ETH tokensForSale = _tokensForSale; // set wallet wallet = _wallet; } /** * @dev Function that validates if the purchase is valid by verifying the parameters * * @param value Amount of ethers sent * @param amount Total number of tokens user is trying to buy. * * @return checks various conditions and returns the bool result indicating validity. */ function isValidPurchase(uint256 value, uint256 amount) internal constant returns (bool) { // check if timestamp is falling in the range bool validTimestamp = startingTimestamp <= block.timestamp && endingTimestamp >= block.timestamp; // check if value of the ether is valid bool validValue = value != 0; // check if rate of the token is clearly defined bool validRate = tokenPriceInEth > 0; // check if the tokens available in contract for sale bool validAmount = tokensForSale.sub(totalTokenSold) >= amount && amount > 0; // validate if all conditions are met return validTimestamp && validValue && validRate && validAmount && !isClose; } function getBonus(uint256 _value) internal pure returns (uint256) { uint256 bonus = 0; if(_value >= 1E18) { bonus = _value.mul(50).div(1000); }if(_value >= 5E18) { bonus = _value.mul(75).div(1000); }if(_value >= 10E18) { bonus = _value.mul(100).div(1000); }if(_value >= 20E18) { bonus = _value.mul(150).div(1000); }if(_value >= 30E18) { bonus = _value.mul(200).div(1000); } return bonus; } /** * @dev Function that accepts ether value and returns the token amount * * @param value Amount of ethers sent * * @return checks various conditions and returns the bool result indicating validity. */ function calculate(uint256 value) public constant returns (uint256) { uint256 tokenDecimals = token.decimals(); uint256 tokens = value.mul(10 ** tokenDecimals).div(tokenPriceInEth); return tokens; } function lockBonus(address _sender, uint bonusTokens) internal returns (bool) { uint256 lockedBonus = bonusTokens.div(4); lockupPhase1[_sender] = lockupPhase1[_sender].add(lockedBonus); lockupPhase2[_sender] = lockupPhase2[_sender].add(lockedBonus); lockupPhase3[_sender] = lockupPhase3[_sender].add(lockedBonus); lockupPhase4[_sender] = lockupPhase4[_sender].add(lockedBonus); totalLockedBonus = totalLockedBonus.add(bonusTokens); return true; } /** * @dev Default fallback method which will be called when any ethers are sent to contract */ function() public payable { buyTokens(msg.sender); } /** * @dev Function that is called either externally or by default payable method * * @param beneficiary who should receive tokens */ function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); // amount of ethers sent uint256 _value = msg.value; // calculate token amount from the ethers sent uint256 tokens = calculate(_value); // calculate bonus token amount from the ethers sent uint256 bonusTokens = calculate(getBonus(_value)); lockBonus(beneficiary, bonusTokens); uint256 _totalTokens = tokens.add(bonusTokens); // validate the purchase require(isValidPurchase(_value , _totalTokens)); // update the state to log the sold tokens and raised ethers. totalTokenSold = totalTokenSold.add(_totalTokens); totalEtherRaised = totalEtherRaised.add(_value); etherRaisedPerWallet[msg.sender] = etherRaisedPerWallet[msg.sender].add(_value); // transfer tokens from contract balance to beneficiary account. calling ERC20 method token.transfer(beneficiary, tokens); // log event for token purchase TokenPurchase(msg.sender, beneficiary, _value, tokens, now); } function isValidRelease(uint256 amount) internal constant returns (bool) { // check if the tokens available in contract for sale bool validAmount = amount > 0; // validate if all conditions are met return validAmount; } function releaseBonus() public { uint256 releaseTokens = 0; if(block.timestamp > (startingTimestamp.add(phase1Duration))) { releaseTokens = releaseTokens.add(lockupPhase1[msg.sender]); lockupPhase1[msg.sender] = 0; } if(block.timestamp > (startingTimestamp.add(phase2Duration))) { releaseTokens = releaseTokens.add(lockupPhase2[msg.sender]); lockupPhase2[msg.sender] = 0; } if(block.timestamp > (startingTimestamp.add(phase3Duration))) { releaseTokens = releaseTokens.add(lockupPhase3[msg.sender]); lockupPhase3[msg.sender] = 0; } if(block.timestamp > (startingTimestamp.add(phase4Duration))) { releaseTokens = releaseTokens.add(lockupPhase4[msg.sender]); lockupPhase4[msg.sender] = 0; } // require(isValidRelease(releaseTokens)); totalLockedBonus = totalLockedBonus.sub(releaseTokens); token.transfer(msg.sender, releaseTokens); } function releasableBonus(address _owner) public constant returns (uint256) { uint256 releaseTokens = 0; if(block.timestamp > (startingTimestamp.add(phase1Duration))) { releaseTokens = releaseTokens.add(lockupPhase1[_owner]); } if(block.timestamp > (startingTimestamp.add(phase2Duration))) { releaseTokens = releaseTokens.add(lockupPhase2[_owner]); } if(block.timestamp > (startingTimestamp.add(phase3Duration))) { releaseTokens = releaseTokens.add(lockupPhase3[_owner]); } if(block.timestamp > (startingTimestamp.add(phase4Duration))) { releaseTokens = releaseTokens.add(lockupPhase4[_owner]); } return releaseTokens; } /** * @dev transmit token for a specified address. * This is owner only method and should be called using web3.js if someone is trying to buy token using bitcoin or any other altcoin. * * @param _to The address to transmit to. * @param _value The amount to be transferred. * @param _message message to log after transfer. */ function transferManual(address _to, uint256 _value, string _message) onlyOwner public returns (bool) { require(_to != address(0)); // transfer tokens manually from contract balance token.transfer(_to , _value); TransferManual(msg.sender, _to, _value, _message); return true; } /** * @dev withdraw funds * This will set the withdrawal wallet * * @param _wallet The address to transmit to. */ function setWallet(address _wallet) onlyOwner public returns(bool) { // set wallet wallet = _wallet; WalletChange(_wallet , now); return true; } /** * @dev Method called by owner of contract to withdraw funds */ function withdraw() onlyOwner public { wallet.transfer(this.balance); } /** * @dev close contract * This will send remaining token balance to owner * This will distribute available funds across team members */ function close() onlyOwner public { // send remaining tokens back to owner. uint256 tokens = token.balanceOf(this).sub(totalLockedBonus); token.transfer(owner , tokens); // withdraw funds withdraw(); // mark the flag to indicate closure of the contract isClose = true; } }
transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./ SafeMath.sub will throw if there is not enough balance.
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; }
167,319
./partial_match/1/0xD59BcAbd00721B754aCB79FE668faE4B6A063fF8/sources/contracts/token/Token.sol
returns whether the provided token represents an ERC20 or the native token reserve/
function isNative(Token token) pure returns (bool) { return token == NATIVE_TOKEN; }
2,647,119
./partial_match/8453/0x21fed85E54507164FD6c9Eb76870AFF41098106b/sources/contracts/mint/MintManager.sol
Verify, and update the state of a gated mint claim claim Claim signature Signed + encoded claim msgSender Expected claimer/
function _verifyAndUpdateClaim( Claim calldata claim, bytes calldata signature, address msgSender ) private { address signer = _claimSigner(claim, signature); if (msgSender != claim.claimer) { _revert(SenderNotClaimer.selector); } claim.numTokensToMint; uint256 expectedNumClaimedByUser = offchainVectorsClaimState[claim.offchainVectorId].numClaimedPerUser[ msgSender ] + claim.numTokensToMint; if ( !_isPlatformExecutor(signer) || _offchainVectorsToNoncesUsed[claim.offchainVectorId].contains(claim.claimNonce) || block.timestamp > claim.claimExpiryTimestamp || (expectedNumClaimedViaVector > claim.maxClaimableViaVector && claim.maxClaimableViaVector != 0) || (expectedNumClaimedByUser > claim.maxClaimablePerUser && claim.maxClaimablePerUser != 0) ) { _revert(InvalidClaim.selector); } offchainVectorsClaimState[claim.offchainVectorId].numClaimedPerUser[msgSender] = expectedNumClaimedByUser; }
16,779,428
/* ⚠⚠⚠ WARNING WARNING WARNING ⚠⚠⚠ This is a TARGET contract - DO NOT CONNECT TO IT DIRECTLY IN YOUR CONTRACTS or DAPPS! This contract has an associated PROXY that MUST be used for all integrations - this TARGET will be REPLACED in an upcoming Synthetix release! The proxy can be found by looking up the PROXY property on this contract. *//* ____ __ __ __ _ / __/__ __ ___ / /_ / / ___ / /_ (_)__ __ _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ / /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\ /___/ * Synthetix: Synth.sol * * Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/Synth.sol * Docs: https://docs.synthetix.io/contracts/Synth * * Contract Dependencies: * - ExternStateToken * - IAddressResolver * - IERC20 * - ISynth * - MixinResolver * - Owned * - Proxyable * - State * Libraries: * - SafeDecimalMath * - SafeMath * * MIT License * =========== * * Copyright (c) 2021 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 */ pragma solidity ^0.5.16; // https://docs.synthetix.io/contracts/source/contracts/owned contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/proxy contract Proxy is Owned { Proxyable public target; constructor(address _owner) public Owned(_owner) {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } function _emit( bytes calldata callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4 ) external onlyTarget { uint size = callData.length; bytes memory _callData = callData; assembly { /* The first 32 bytes of callData contain its length (as specified by the abi). * Length is assumed to be a uint256 and therefore maximum of 32 bytes * in length. It is also leftpadded to be a multiple of 32 bytes. * This means moving call_data across 32 bytes guarantees we correctly access * the data itself. */ switch numTopics case 0 { log0(add(_callData, 32), size) } case 1 { log1(add(_callData, 32), size, topic1) } case 2 { log2(add(_callData, 32), size, topic1, topic2) } case 3 { log3(add(_callData, 32), size, topic1, topic2, topic3) } case 4 { log4(add(_callData, 32), size, topic1, topic2, topic3, topic4) } } } // solhint-disable no-complex-fallback function() external payable { // Mutable call setting Proxyable.messageSender as this is using call not delegatecall target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* We must explicitly forward ether to the underlying contract as well. */ let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } modifier onlyTarget { require(Proxyable(msg.sender) == target, "Must be proxy target"); _; } event TargetUpdated(Proxyable newTarget); } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/proxyable contract Proxyable is Owned { // This contract should be treated like an abstract contract /* The proxy this contract exists behind. */ Proxy public proxy; Proxy public integrationProxy; /* The caller of the proxy, passed through to this contract. * Note that every function using this member must apply the onlyProxy or * optionalProxy modifiers, otherwise their invocations can use stale values. */ address public messageSender; constructor(address payable _proxy) internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setProxy(address payable _proxy) external onlyOwner { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setIntegrationProxy(address payable _integrationProxy) external onlyOwner { integrationProxy = Proxy(_integrationProxy); } function setMessageSender(address sender) external onlyProxy { messageSender = sender; } modifier onlyProxy { _onlyProxy(); _; } function _onlyProxy() private view { require(Proxy(msg.sender) == proxy || Proxy(msg.sender) == integrationProxy, "Only the proxy can call"); } modifier optionalProxy { _optionalProxy(); _; } function _optionalProxy() private { if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) { messageSender = msg.sender; } } modifier optionalProxy_onlyOwner { _optionalProxy_onlyOwner(); _; } // solhint-disable-next-line func-name-mixedcase function _optionalProxy_onlyOwner() private { if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) { messageSender = msg.sender; } require(messageSender == owner, "Owner only function"); } event ProxyUpdated(address proxyAddress); } /** * @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; } } // Libraries // https://docs.synthetix.io/contracts/source/libraries/safedecimalmath library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10**uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { 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(uint x, uint y) internal pure returns (uint) { /* 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( uint x, uint y, uint precisionUnit ) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint 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(uint x, uint y) internal pure returns (uint) { 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(uint x, uint y) internal pure returns (uint) { 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(uint x, uint y) internal pure returns (uint) { /* 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( uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint 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(uint x, uint y) internal pure returns (uint) { 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(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } // Inheritance // https://docs.synthetix.io/contracts/source/contracts/state contract State is Owned { // the address of the contract that can modify variables // this can only be changed by the owner of this contract address public associatedContract; constructor(address _associatedContract) internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== SETTERS ========== */ // Change the associated contract to a new address function setAssociatedContract(address _associatedContract) external onlyOwner { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== MODIFIERS ========== */ modifier onlyAssociatedContract { require(msg.sender == associatedContract, "Only the associated contract can perform this action"); _; } /* ========== EVENTS ========== */ event AssociatedContractUpdated(address associatedContract); } // Inheritance // https://docs.synthetix.io/contracts/source/contracts/tokenstate contract TokenState is Owned, State { /* ERC20 fields. */ mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; constructor(address _owner, address _associatedContract) public Owned(_owner) State(_associatedContract) {} /* ========== SETTERS ========== */ /** * @notice Set ERC20 allowance. * @dev Only the associated contract may call this. * @param tokenOwner The authorising party. * @param spender The authorised party. * @param value The total value the authorised party may spend on the * authorising party's behalf. */ function setAllowance( address tokenOwner, address spender, uint value ) external onlyAssociatedContract { allowance[tokenOwner][spender] = value; } /** * @notice Set the balance in a given account * @dev Only the associated contract may call this. * @param account The account whose value to set. * @param value The new balance of the given account. */ function setBalanceOf(address account, uint value) external onlyAssociatedContract { balanceOf[account] = value; } } // Inheritance // Libraries // Internal references // https://docs.synthetix.io/contracts/source/contracts/externstatetoken contract ExternStateToken is Owned, Proxyable { using SafeMath for uint; using SafeDecimalMath for uint; /* ========== STATE VARIABLES ========== */ /* Stores balances and allowances. */ TokenState public tokenState; /* Other ERC20 fields. */ string public name; string public symbol; uint public totalSupply; uint8 public decimals; constructor( address payable _proxy, TokenState _tokenState, string memory _name, string memory _symbol, uint _totalSupply, uint8 _decimals, address _owner ) public Owned(_owner) Proxyable(_proxy) { tokenState = _tokenState; name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; } /* ========== VIEWS ========== */ /** * @notice Returns the ERC20 allowance of one party to spend on behalf of another. * @param owner The party authorising spending of their funds. * @param spender The party spending tokenOwner's funds. */ function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } /** * @notice Returns the ERC20 token balance of a given account. */ function balanceOf(address account) external view returns (uint) { return tokenState.balanceOf(account); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Set the address of the TokenState contract. * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000.. * as balances would be unreachable. */ function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(address(_tokenState)); } function _internalTransfer( address from, address to, uint value ) internal returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0) && to != address(this) && to != address(proxy), "Cannot transfer to this address"); // Insufficient balance will be handled by the safe subtraction. tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value)); tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value)); // Emit a standard ERC20 transfer event emitTransfer(from, to, value); return true; } /** * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing * the onlyProxy or optionalProxy modifiers. */ function _transferByProxy( address from, address to, uint value ) internal returns (bool) { return _internalTransfer(from, to, value); } /* * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions * possessing the optionalProxy or optionalProxy modifiers. */ function _transferFromByProxy( address sender, address from, address to, uint value ) internal returns (bool) { /* Insufficient allowance will be handled by the safe subtraction. */ tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value)); return _internalTransfer(from, to, value); } /** * @notice Approves spender to transfer on the message sender's behalf. */ function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } /* ========== EVENTS ========== */ function addressToBytes32(address input) internal pure returns (bytes32) { return bytes32(uint256(uint160(input))); } event Transfer(address indexed from, address indexed to, uint value); bytes32 internal constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer( address from, address to, uint value ) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, addressToBytes32(from), addressToBytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 internal constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval( address owner, address spender, uint value ) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, addressToBytes32(owner), addressToBytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 internal constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } } // https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getSynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } // https://docs.synthetix.io/contracts/source/interfaces/isynth interface ISynth { // Views function currencyKey() external view returns (bytes32); function transferableSynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to Synthetix function burn(address account, uint amount) external; function issue(address account, uint amount) external; } // https://docs.synthetix.io/contracts/source/interfaces/iissuer interface IIssuer { // Views function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function canBurnSynths(address account) external view returns (bool); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function collateralisationRatioAndAnyRatesInvalid(address _issuer) external view returns (uint cratio, bool anyRateIsInvalid); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance); function issuanceRatio() external view returns (uint); function lastIssueEvent(address account) external view returns (uint); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function minimumStakeTime() external view returns (uint); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint); function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance) external view returns (uint transferable, bool anyRateIsInvalid); // Restricted: used internally to Synthetix function issueSynths(address from, uint amount) external; function issueSynthsOnBehalf( address issueFor, address from, uint amount ) external; function issueMaxSynths(address from) external; function issueMaxSynthsOnBehalf(address issueFor, address from) external; function burnSynths(address from, uint amount) external; function burnSynthsOnBehalf( address burnForAddress, address from, uint amount ) external; function burnSynthsToTarget(address from) external; function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external; function liquidateDelinquentAccount( address account, uint susdAmount, address liquidator ) external returns (uint totalRedeemed, uint amountToLiquidate); } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/addressresolver contract AddressResolver is Owned, IAddressResolver { mapping(bytes32 => address) public repository; constructor(address _owner) public Owned(_owner) {} /* ========== RESTRICTED FUNCTIONS ========== */ function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner { require(names.length == destinations.length, "Input lengths must match"); for (uint i = 0; i < names.length; i++) { bytes32 name = names[i]; address destination = destinations[i]; repository[name] = destination; emit AddressImported(name, destination); } } /* ========= PUBLIC FUNCTIONS ========== */ function rebuildCaches(MixinResolver[] calldata destinations) external { for (uint i = 0; i < destinations.length; i++) { destinations[i].rebuildCache(); } } /* ========== VIEWS ========== */ function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) { for (uint i = 0; i < names.length; i++) { if (repository[names[i]] != destinations[i]) { return false; } } return true; } function getAddress(bytes32 name) external view returns (address) { return repository[name]; } function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) { address _foundAddress = repository[name]; require(_foundAddress != address(0), reason); return _foundAddress; } function getSynth(bytes32 key) external view returns (address) { IIssuer issuer = IIssuer(repository["Issuer"]); require(address(issuer) != address(0), "Cannot find Issuer address"); return address(issuer.synths(key)); } /* ========== EVENTS ========== */ event AddressImported(bytes32 name, address destination); } // solhint-disable payable-fallback // https://docs.synthetix.io/contracts/source/contracts/readproxy contract ReadProxy is Owned { address public target; constructor(address _owner) public Owned(_owner) {} function setTarget(address _target) external onlyOwner { target = _target; emit TargetUpdated(target); } function() external { // The basics of a proxy read call // Note that msg.sender in the underlying will always be the address of this contract. assembly { calldatacopy(0, 0, calldatasize) // Use of staticcall - this will revert if the underlying function mutates state let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0) returndatacopy(0, 0, returndatasize) if iszero(result) { revert(0, returndatasize) } return(0, returndatasize) } } event TargetUpdated(address newTarget); } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/mixinresolver contract MixinResolver { AddressResolver public resolver; mapping(bytes32 => address) private addressCache; constructor(address _resolver) internal { resolver = AddressResolver(_resolver); } /* ========== INTERNAL FUNCTIONS ========== */ function combineArrays(bytes32[] memory first, bytes32[] memory second) internal pure returns (bytes32[] memory combination) { combination = new bytes32[](first.length + second.length); for (uint i = 0; i < first.length; i++) { combination[i] = first[i]; } for (uint j = 0; j < second.length; j++) { combination[first.length + j] = second[j]; } } /* ========== PUBLIC FUNCTIONS ========== */ // Note: this function is public not external in order for it to be overridden and invoked via super in subclasses function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {} function rebuildCache() public { bytes32[] memory requiredAddresses = resolverAddressesRequired(); // The resolver must call this function whenver it updates its state for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // Note: can only be invoked once the resolver has all the targets needed added address destination = resolver.requireAndGetAddress( name, string(abi.encodePacked("Resolver missing target: ", name)) ); addressCache[name] = destination; emit CacheUpdated(name, destination); } } /* ========== VIEWS ========== */ function isResolverCached() external view returns (bool) { bytes32[] memory requiredAddresses = resolverAddressesRequired(); for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // false if our cache is invalid or if the resolver doesn't have the required address if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; } } return true; } /* ========== INTERNAL FUNCTIONS ========== */ function requireAndGetAddress(bytes32 name) internal view returns (address) { address _foundAddress = addressCache[name]; require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name))); return _foundAddress; } /* ========== EVENTS ========== */ event CacheUpdated(bytes32 name, address destination); } // https://docs.synthetix.io/contracts/source/interfaces/ierc20 interface IERC20 { // ERC20 Optional Views function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); // Views function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); // Mutative functions function transfer(address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function transferFrom( address from, address to, uint value ) external returns (bool); // Events event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } // https://docs.synthetix.io/contracts/source/interfaces/isystemstatus interface ISystemStatus { struct Status { bool canSuspend; bool canResume; } struct Suspension { bool suspended; // reason is an integer code, // 0 => no reason, 1 => upgrading, 2+ => defined by system usage uint248 reason; } // Views function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume); function requireSystemActive() external view; function requireIssuanceActive() external view; function requireExchangeActive() external view; function requireExchangeBetweenSynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function requireSynthActive(bytes32 currencyKey) external view; function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function systemSuspension() external view returns (bool suspended, uint248 reason); function issuanceSuspension() external view returns (bool suspended, uint248 reason); function exchangeSuspension() external view returns (bool suspended, uint248 reason); function synthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function synthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function getSynthExchangeSuspensions(bytes32[] calldata synths) external view returns (bool[] memory exchangeSuspensions, uint256[] memory reasons); function getSynthSuspensions(bytes32[] calldata synths) external view returns (bool[] memory suspensions, uint256[] memory reasons); // Restricted functions function suspendSynth(bytes32 currencyKey, uint256 reason) external; function updateAccessControl( bytes32 section, address account, bool canSuspend, bool canResume ) external; } // https://docs.synthetix.io/contracts/source/interfaces/ifeepool interface IFeePool { // Views // solhint-disable-next-line func-name-mixedcase function FEE_ADDRESS() external view returns (address); function feesAvailable(address account) external view returns (uint, uint); function feePeriodDuration() external view returns (uint); function isFeesClaimable(address account) external view returns (bool); function targetThreshold() external view returns (uint); function totalFeesAvailable() external view returns (uint); function totalRewardsAvailable() external view returns (uint); // Mutative Functions function claimFees() external returns (bool); function claimOnBehalf(address claimingForAddress) external returns (bool); function closeCurrentFeePeriod() external; // Restricted: used internally to Synthetix function appendAccountIssuanceRecord( address account, uint lockedAmount, uint debtEntryIndex ) external; function recordFeePaid(uint sUSDAmount) external; function setRewardsToDistribute(uint amount) external; } interface IVirtualSynth { // Views function balanceOfUnderlying(address account) external view returns (uint); function rate() external view returns (uint); function readyToSettle() external view returns (bool); function secsLeftInWaitingPeriod() external view returns (uint); function settled() external view returns (bool); function synth() external view returns (ISynth); // Mutative functions function settle(address account) external; } // https://docs.synthetix.io/contracts/source/interfaces/iexchanger interface IExchanger { // Views function calculateAmountAfterSettlement( address from, bytes32 currencyKey, uint amount, uint refunded ) external view returns (uint amountAfterSettlement); function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool); function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint); function settlementOwing(address account, bytes32 currencyKey) external view returns ( uint reclaimAmount, uint rebateAmount, uint numEntries ); function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool); function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint exchangeFeeRate); function getAmountsForExchange( uint sourceAmount, bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey ) external view returns ( uint amountReceived, uint fee, uint exchangeFeeRate ); function priceDeviationThresholdFactor() external view returns (uint); function waitingPeriodSecs() external view returns (uint); // Mutative functions function exchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function settle(address from, bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); function setLastExchangeRateForSynth(bytes32 currencyKey, uint rate) external; function suspendSynthWithInvalidRate(bytes32 currencyKey) external; } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/synth contract Synth is Owned, IERC20, ExternStateToken, MixinResolver, ISynth { /* ========== STATE VARIABLES ========== */ // Currency key which identifies this Synth to the Synthetix system bytes32 public currencyKey; uint8 public constant DECIMALS = 18; // Where fees are pooled in sUSD address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_FEEPOOL = "FeePool"; /* ========== CONSTRUCTOR ========== */ constructor( address payable _proxy, TokenState _tokenState, string memory _tokenName, string memory _tokenSymbol, address _owner, bytes32 _currencyKey, uint _totalSupply, address _resolver ) public ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, _totalSupply, DECIMALS, _owner) MixinResolver(_resolver) { require(_proxy != address(0), "_proxy cannot be 0"); require(_owner != address(0), "_owner cannot be 0"); currencyKey = _currencyKey; } /* ========== MUTATIVE FUNCTIONS ========== */ function transfer(address to, uint value) public optionalProxy returns (bool) { _ensureCanTransfer(messageSender, value); // transfers to FEE_ADDRESS will be exchanged into sUSD and recorded as fee if (to == FEE_ADDRESS) { return _transferToFeeAddress(to, value); } // transfers to 0x address will be burned if (to == address(0)) { return _internalBurn(messageSender, value); } return super._internalTransfer(messageSender, to, value); } function transferAndSettle(address to, uint value) public optionalProxy returns (bool) { // Exchanger.settle ensures synth is active (, , uint numEntriesSettled) = exchanger().settle(messageSender, currencyKey); // Save gas instead of calling transferableSynths uint balanceAfter = value; if (numEntriesSettled > 0) { balanceAfter = tokenState.balanceOf(messageSender); } // Reduce the value to transfer if balance is insufficient after reclaimed value = value > balanceAfter ? balanceAfter : value; return super._internalTransfer(messageSender, to, value); } function transferFrom( address from, address to, uint value ) public optionalProxy returns (bool) { _ensureCanTransfer(from, value); return _internalTransferFrom(from, to, value); } function transferFromAndSettle( address from, address to, uint value ) public optionalProxy returns (bool) { // Exchanger.settle() ensures synth is active (, , uint numEntriesSettled) = exchanger().settle(from, currencyKey); // Save gas instead of calling transferableSynths uint balanceAfter = value; if (numEntriesSettled > 0) { balanceAfter = tokenState.balanceOf(from); } // Reduce the value to transfer if balance is insufficient after reclaimed value = value >= balanceAfter ? balanceAfter : value; return _internalTransferFrom(from, to, value); } /** * @notice _transferToFeeAddress function * non-sUSD synths are exchanged into sUSD via synthInitiatedExchange * notify feePool to record amount as fee paid to feePool */ function _transferToFeeAddress(address to, uint value) internal returns (bool) { uint amountInUSD; // sUSD can be transferred to FEE_ADDRESS directly if (currencyKey == "sUSD") { amountInUSD = value; super._internalTransfer(messageSender, to, value); } else { // else exchange synth into sUSD and send to FEE_ADDRESS amountInUSD = exchanger().exchange(messageSender, currencyKey, value, "sUSD", FEE_ADDRESS); } // Notify feePool to record sUSD to distribute as fees feePool().recordFeePaid(amountInUSD); return true; } function issue(address account, uint amount) external onlyInternalContracts { _internalIssue(account, amount); } function burn(address account, uint amount) external onlyInternalContracts { _internalBurn(account, amount); } function _internalIssue(address account, uint amount) internal { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); totalSupply = totalSupply.add(amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } function _internalBurn(address account, uint amount) internal returns (bool) { tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount)); totalSupply = totalSupply.sub(amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); return true; } // Allow owner to set the total supply on import. function setTotalSupply(uint amount) external optionalProxy_onlyOwner { totalSupply = amount; } /* ========== VIEWS ========== */ // Note: use public visibility so that it can be invoked in a subclass function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](4); addresses[0] = CONTRACT_SYSTEMSTATUS; addresses[1] = CONTRACT_EXCHANGER; addresses[2] = CONTRACT_ISSUER; addresses[3] = CONTRACT_FEEPOOL; } function systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function feePool() internal view returns (IFeePool) { return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL)); } function exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function _ensureCanTransfer(address from, uint value) internal view { require(exchanger().maxSecsLeftInWaitingPeriod(from, currencyKey) == 0, "Cannot transfer during waiting period"); require(transferableSynths(from) >= value, "Insufficient balance after any settlement owing"); systemStatus().requireSynthActive(currencyKey); } function transferableSynths(address account) public view returns (uint) { (uint reclaimAmount, , ) = exchanger().settlementOwing(account, currencyKey); // Note: ignoring rebate amount here because a settle() is required in order to // allow the transfer to actually work uint balance = tokenState.balanceOf(account); if (reclaimAmount > balance) { return 0; } else { return balance.sub(reclaimAmount); } } /* ========== INTERNAL FUNCTIONS ========== */ function _internalTransferFrom( address from, address to, uint value ) internal returns (bool) { // Skip allowance update in case of infinite allowance if (tokenState.allowance(from, messageSender) != uint(-1)) { // Reduce the allowance by the amount we're transferring. // The safeSub call will handle an insufficient allowance. tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); } return super._internalTransfer(from, to, value); } /* ========== MODIFIERS ========== */ modifier onlyInternalContracts() { bool isFeePool = msg.sender == address(feePool()); bool isExchanger = msg.sender == address(exchanger()); bool isIssuer = msg.sender == address(issuer()); require(isFeePool || isExchanger || isIssuer, "Only FeePool, Exchanger or Issuer contracts allowed"); _; } /* ========== EVENTS ========== */ event Issued(address indexed account, uint value); bytes32 private constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint value) internal { proxy._emit(abi.encode(value), 2, ISSUED_SIG, addressToBytes32(account), 0, 0); } event Burned(address indexed account, uint value); bytes32 private constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint value) internal { proxy._emit(abi.encode(value), 2, BURNED_SIG, addressToBytes32(account), 0, 0); } }
transfers to FEE_ADDRESS will be exchanged into sUSD and recorded as fee transfers to 0x address will be burned
function transfer(address to, uint value) public optionalProxy returns (bool) { _ensureCanTransfer(messageSender, value); if (to == FEE_ADDRESS) { return _transferToFeeAddress(to, value); } if (to == address(0)) { return _internalBurn(messageSender, value); } return super._internalTransfer(messageSender, to, value); }
84,657
./full_match/80001/0x56EBA30A7Aa8655215C20ffA1983910B9F5a8a77/sources/contracts/Tasks/Tasks.sol
@inheritdoc ITasks Task is open or deadline past Task is taken and deadline has not past
function cancelTask( uint256 _taskId, string calldata _explanation ) external returns (uint8 cancelTaskRequestId) { Task storage task = _getTask(_taskId); _ensureSenderIsManager(task); _ensureTaskNotClosed(task); if (task.state == TaskState.Open || task.deadline <= uint64(block.timestamp)) { _refundCreator(task); if (task.state == TaskState.Open) { unchecked { --openTasks; } unchecked { --takenTasks; } } emit TaskCancelled(_taskId, _msgSender(), task.state == TaskState.Open ? address(0) : task.applications[task.executorApplication].applicant); } else { CancelTaskRequest storage request = task.cancelTaskRequests[task.cancelTaskRequestCount]; request.explanation = _explanation; cancelTaskRequestId = task.cancelTaskRequestCount++; emit CancelTaskRequested(_taskId, cancelTaskRequestId, _explanation, _msgSender(), task.applications[task.executorApplication].applicant); } }
5,582,000
// SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_ErrorUtils } from "../utils/Lib_ErrorUtils.sol"; import { Lib_PredeployAddresses } from "../constants/Lib_PredeployAddresses.sol"; /** * @title Lib_ExecutionManagerWrapper * @dev This library acts as a utility for easily calling the OVM_ExecutionManagerWrapper, the * predeployed contract which exposes the `kall` builtin. Effectively, this contract allows the * user to trigger OVM opcodes by directly calling the OVM_ExecutionManger. * * Compiler used: solc * Runtime target: OVM */ library Lib_ExecutionManagerWrapper { /********************** * Internal Functions * **********************/ /** * Performs a safe ovmCREATE call. * @param _bytecode Code for the new contract. * @return Address of the created contract. */ function ovmCREATE( bytes memory _bytecode ) internal returns ( address, bytes memory ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCREATE(bytes)", _bytecode ) ); return abi.decode(returndata, (address, bytes)); } /** * Performs a safe ovmGETNONCE call. * @return Result of calling ovmGETNONCE. */ function ovmGETNONCE() internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmGETNONCE()" ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmINCREMENTNONCE call. */ function ovmINCREMENTNONCE() internal { _callWrapperContract( abi.encodeWithSignature( "ovmINCREMENTNONCE()" ) ); } /** * Performs a safe ovmCREATEEOA call. * @param _messageHash Message hash which was signed by EOA * @param _v v value of signature (0 or 1) * @param _r r value of signature * @param _s s value of signature */ function ovmCREATEEOA( bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s ) internal { _callWrapperContract( abi.encodeWithSignature( "ovmCREATEEOA(bytes32,uint8,bytes32,bytes32)", _messageHash, _v, _r, _s ) ); } /** * Calls the ovmL1TXORIGIN opcode. * @return Address that sent this message from L1. */ function ovmL1TXORIGIN() internal returns ( address ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmL1TXORIGIN()" ) ); return abi.decode(returndata, (address)); } /** * Calls the ovmCHAINID opcode. * @return Chain ID of the current network. */ function ovmCHAINID() internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCHAINID()" ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmADDRESS call. * @return Result of calling ovmADDRESS. */ function ovmADDRESS() internal returns ( address ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmADDRESS()" ) ); return abi.decode(returndata, (address)); } /** * Calls the value-enabled ovmCALL opcode. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _value ETH value to pass with the call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmCALL( uint256 _gasLimit, address _address, uint256 _value, bytes memory _calldata ) internal returns ( bool, bytes memory ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCALL(uint256,address,uint256,bytes)", _gasLimit, _address, _value, _calldata ) ); return abi.decode(returndata, (bool, bytes)); } /** * Calls the ovmBALANCE opcode. * @param _address OVM account to query the balance of. * @return Balance of the account. */ function ovmBALANCE( address _address ) internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmBALANCE(address)", _address ) ); return abi.decode(returndata, (uint256)); } /** * Calls the ovmCALLVALUE opcode. * @return Value of the current call frame. */ function ovmCALLVALUE() internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCALLVALUE()" ) ); return abi.decode(returndata, (uint256)); } /********************* * Private Functions * *********************/ /** * Performs an ovm interaction and the necessary safety checks. * @param _calldata Data to send to the OVM_ExecutionManager (encoded with sighash). * @return Data sent back by the OVM_ExecutionManager. */ function _callWrapperContract( bytes memory _calldata ) private returns ( bytes memory ) { (bool success, bytes memory returndata) = Lib_PredeployAddresses.EXECUTION_MANAGER_WRAPPER.delegatecall(_calldata); if (success == true) { return returndata; } else { assembly { revert(add(returndata, 0x20), mload(returndata)) } } } }
Performs a safe ovmINCREMENTNONCE call./
function ovmINCREMENTNONCE() internal { _callWrapperContract( abi.encodeWithSignature( "ovmINCREMENTNONCE()" ) ); }
5,370,249
pragma solidity ^0.5.2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../uniswap/interfaces/IUniswapFactory.sol"; import "../../uniswap/interfaces/IUniswapExchange.sol"; import "./IExchangeAdapter.sol"; import "./UniswapPriceGetter.sol"; contract UniswapWithExcessOutput is IExchangeAdapter, UniswapPriceGetter { using SafeMath for uint; event TokenToTokenSwapExecuted(IERC20 tokenIn, IERC20 tokenOut, uint tokenInAmount, uint tokenOutAmount, uint excessTokenOut); event EthToTokenSwapExecuted(IERC20 token, uint ethAmount, uint tokenAmount, uint excessToken); event TokenToEthSwapExecuted(IERC20 token, uint tokenAmount, uint ethAmount, uint excessEth); address payable public _excessRecipient; constructor(IUniswapFactory uniswapFactory, address payable excessRecipient) UniswapPriceGetter(uniswapFactory) public { _excessRecipient = excessRecipient; } function tokenToTokenSwapExcess(IERC20 tokenIn, IERC20 tokenOut, uint tokenInAmount, uint tokenOutAmount) external view returns (int excessTokenIn, int excessTokenOut) { excessTokenIn = 0; excessTokenOut = int(tokenToTokenInputPrice(tokenIn, tokenOut, tokenInAmount) - tokenOutAmount); } function ethToTokenSwapExcess(IERC20 token, uint ethAmount, uint tokenAmount) external view returns (int excessEth, int excessToken) { excessEth = 0; excessToken = int(ethToTokenInputPrice(token, ethAmount) - tokenAmount); } function tokenToEthSwapExcess(IERC20 token, uint tokenAmount, uint ethAmount) external view returns (int excessToken, int excessEth) { excessToken = 0; excessEth = int(tokenToEthInputPrice(token, tokenAmount) - ethAmount); } function tokenToTokenSwap(IERC20 tokenIn, IERC20 tokenOut, uint tokenInAmount, uint tokenOutAmount) external { IUniswapExchange uniswapExchange = IUniswapExchange(_uniswapFactory.getExchange(address(tokenIn))); // approve token to be spent by Uniswap exchange tokenIn.approve(address(uniswapExchange), tokenInAmount); // execute swap on Uniswap exchange contract for tokenOut // set minEthBought to 1 uint tokenOutBought = uniswapExchange.tokenToTokenSwapInput(tokenInAmount, tokenOutAmount, 1, now, address(tokenOut)); // transfer tokenOut amount to msg.sender tokenOut.transfer(msg.sender, tokenOutAmount); // transfer excess tokenOut to excessRecipient uint excessTokenOut = tokenOutBought.sub(tokenOutAmount); if (excessTokenOut > 0) { tokenOut.transfer(_excessRecipient, excessTokenOut); } emit TokenToTokenSwapExecuted(tokenIn, tokenOut, tokenInAmount, tokenOutAmount, excessTokenOut); } function ethToTokenSwap(IERC20 token, uint tokenAmount) external payable { IUniswapExchange uniswapExchange = IUniswapExchange(_uniswapFactory.getExchange(address(token))); // execute swap on Uniswap exchange contract for token uint tokensBought = uniswapExchange.ethToTokenSwapInput.value(msg.value)(tokenAmount, now); // transfer token amount to msg.sender token.transfer(msg.sender, tokenAmount); // transfer excess token to excessRecipient uint excessToken = tokensBought.sub(tokenAmount); if (excessToken > 0) { token.transfer(_excessRecipient, excessToken); } emit EthToTokenSwapExecuted(token, msg.value, tokenAmount, excessToken); } function tokenToEthSwap(IERC20 token, uint tokenAmount, uint ethAmount) external { IUniswapExchange uniswapExchange = IUniswapExchange(_uniswapFactory.getExchange(address(token))); // approve token to be spent by Uniswap exchange token.approve(address(uniswapExchange), tokenAmount); // execute swap on Uniswap exchange contract for token uint ethBought = uniswapExchange.tokenToEthSwapInput(tokenAmount, ethAmount, now); (bool success, ) = address(msg.sender).call.value(ethAmount)(""); require(success, "UniswapWithExcessInput: ethToTokenSwap failed to send ether to msg.sender"); // transfer excess ETH to excessRecipient uint excessEth = ethBought.sub(ethAmount); if (excessEth > 0) { (success, ) = _excessRecipient.call.value(excessEth)(""); require(success, "UniswapWithExcessOutput: tokenToEthSwap failed to send excess ether"); } emit TokenToEthSwapExecuted(token, tokenAmount, ethAmount, excessEth); } function () external payable {} }
execute swap on Uniswap exchange contract for token transfer token amount to msg.sender transfer excess token to excessRecipient
function ethToTokenSwap(IERC20 token, uint tokenAmount) external payable { IUniswapExchange uniswapExchange = IUniswapExchange(_uniswapFactory.getExchange(address(token))); uint tokensBought = uniswapExchange.ethToTokenSwapInput.value(msg.value)(tokenAmount, now); token.transfer(msg.sender, tokenAmount); uint excessToken = tokensBought.sub(tokenAmount); if (excessToken > 0) { token.transfer(_excessRecipient, excessToken); } emit EthToTokenSwapExecuted(token, msg.value, tokenAmount, excessToken); }
6,462,733
// 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 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; } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [////IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * ////IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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); } /** * @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); } /** * @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); } abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; string private _name; string private _symbol; // Mapping from token ID to owner address address[] internal _owners; mapping(uint256 => address) private _tokenApprovals; 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"); uint256 count; for (uint256 i; i < _owners.length; ++i) { if (owner == _owners[i]) ++count; } return count; } /** * @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 {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all"); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return tokenId < _owners.length && _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _owners.push(to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _owners[tokenId] = address(0); 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); _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } 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); } /** * @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 but rips out the core of the gas-wasting processing that comes from OpenZeppelin. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { /** * @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-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _owners.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < _owners.length, "ERC721Enumerable: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256 tokenId) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); uint256 count; for (uint256 i; i < _owners.length; i++) { if (owner == _owners[i]) { if (count == index) return i; else count++; } } revert("ERC721Enumerable: owner index out of bounds"); } } interface IIllogics { function isAdmin(address addr) external view returns (bool); function mintGoop(address _addr, uint256 _goop) external; function burnGoop(address _addr, uint256 _goop) external; function spendGoop(uint256 _item, uint256 _count) external; function mintGoopBatch(address[] calldata _addr, uint256 _goop) external; function burnGoopBatch(address[] calldata _addr, uint256 _goop) external; } /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for ////important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 private constant USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface internal immutable LINK; address private immutable vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 => uint256) /* keyHash */ /* nonce */ private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * ////IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } interface ILab { function getIllogical(uint256 _tokenId) external view returns (uint256); } contract illogics is IIllogics, ERC721Enumerable, Ownable, VRFConsumerBase { /************************** * * DATA STRUCTURES & ENUM * **************************/ // Data structure that defines the elements of stakedToken struct StakedToken { address ownerOfNFT; uint256 timestamp; uint256 lastRerollPeriod; } // Data structure that defines the elements of a saleId struct Sale { string description; bool saleStatus; uint256 price; uint256 supply; uint256 maxPurchase; } /************************** * * State Variables * **************************/ // ***** constants and assignments ***** uint256 public maxMint = 2; // ill-list max per minter address uint256 public constant REROLL_COST = 50; // Goop required to reroll a token uint256 public constant GOOP_INTERVAL = 12 hours; // The interval upon which Goop is calcualated uint256 public goopPerInterval = 5; // Goop awarded per interval address public teamWallet = 0xB3D1b19202423EcD55ACF1E635ea1Bded11a5c9f; // address of the team wallet // ***** ill-list minting ***** bool public mintingState; // enable/disable minting bytes32 public merkleRoot; // ill-list Merkle Root // ***** Chainlink VRF & tokenID ***** IERC20 public link; // address of Chainlink token contract uint256 public VRF_fee; // Chainlink VRF fee uint256 public periodCounter; // current VRF period bytes32 public VRF_keyHash; // Chainlink VRF random number keyhash string public baseURI; // URI to illogics metadata // ***** Goop ecosystem & Sales ***** uint256 public totalGoopSupply; // total Goop in circulation uint256 public totalGoopSpent; // total Goop spent in the ecosystem uint256 public saleId; // last saleID applied to a saleItem // ***** feature state management ***** bool public spendState; // Goop spending state bool public rerollState; // reroll function state bool public stakingState; // staking state bool public transferState; // Goop P2P transfer state bool public claimStatus; // Goop claim status bool public verifyVRF; // can only be set once, used to validate the Chainlink config prior to mint // ***** OpenSea ***** address public proxyRegistryAddress; // proxyRegistry address // ***** TheLab ***** address public labAddress; // the address of TheLab ;) /************************** * * Mappings * **************************/ mapping(uint256 => Sale) public saleItems; // mapping of saleId to the Sale data scructure mapping(uint256 => StakedToken) public stakedToken; // mapping of tokenId to the StakedToken data structure mapping(address => uint256) public goop; // mapping of address to a Goop balance mapping(address => uint256[]) public staker; // mapping of address to owned tokens staked mapping(uint256 => uint256) public collectionDNA; // mapping of VRF period to seed DNA for said period mapping(uint256 => uint256[]) public rollTracker; // mapping reroll period (periodCounter) entered to tokenIds mapping(address => bool) private admins; // mapping of address to an administrative status mapping(address => bool) public projectProxy; // mapping of address to projectProxy status mapping(address => bool) public addressToMinted; // mapping of address to minted status mapping(address => mapping(uint256 => uint256)) public addressPurchases; // mapping of an address to an saleItemId to number of units purchased /********************************************************** * * Events * **********************************************************/ event RequestedRandomNumber(bytes32 indexed requestId); // emitted when the ChainLink VRF is requested event RecievedRandomNumber(bytes32 indexed requestId, uint256 periodCounter, uint256 randomNumber); // emitted when a random number is recieved by the Chainlink VRF callback() event spentGoop(address indexed purchaser, uint256 indexed item, uint256 indexed count); //emitted when an item is purchased with Goop /********************************************************** * * Constructor * **********************************************************/ /** * @dev Initializes the contract by: * - setting a `name` and a `symbol` in the ERC721 constructor * - setting the Chainlnk VRFConsumerBase constructor * - setting collection dependant assignments */ constructor( bytes32 _VRF_keyHash, uint256 _VRF_Fee, address _vrfCoordinator, address _linkToken ) ERC721("illogics", "ill") VRFConsumerBase(_vrfCoordinator, _linkToken) { VRF_keyHash = _VRF_keyHash; VRF_fee = _VRF_Fee; link = IERC20(address(_linkToken)); admins[_msgSender()] = true; proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; } /********************************************************** * * Modifiers * **********************************************************/ /** * @dev Ensures only contract admins can execute privileged functions */ modifier onlyAdmin() { require(isAdmin(_msgSender()), "admins only"); _; } /********************************************************** * * Contract Management * **********************************************************/ /** * @dev Check is an address is an admin */ function isAdmin(address _addr) public view override returns (bool) { return owner() == _addr || admins[_addr]; } /** * @dev Grant administrative control to an address */ function addAdmin(address _addr) external onlyAdmin { admins[_addr] = true; } /** * @dev Revoke administrative control for an address */ function removeAdmin(address _addr) external onlyAdmin { admins[_addr] = false; } /********************************************************** * * Admin and Contract setters * **********************************************************/ /** * @dev running this after the constructor adds the deployed address * of this contract to the admins */ function init() external onlyAdmin { admins[address(this)] = true; } /** * @dev enables//disables minting state */ function setMintingState(bool _state) external onlyAdmin { mintingState = _state; } /** * @dev enable/disable staking, this does not impact unstaking */ function setStakingState(bool _state) external onlyAdmin { stakingState = _state; } /** * @dev enable/disable reroll, this must be in a disabled state * prior to calling the final VRF */ function setRerollState(bool _state) external onlyAdmin { rerollState = _state; } /** * @dev enable/disable P2P transfer of Goop */ function setTransferState(bool _state) external onlyAdmin { transferState = _state; } /** * @dev enable/disable the ability to spend Goop */ function setSpendState(bool _state) external onlyAdmin { spendState = _state; } /** * @dev set TheLab address (likely some future Alpha here) */ function setLabAddress(address _labAddress) external onlyAdmin { labAddress = _labAddress; } /** * @dev set the baseURI. */ function setBaseURI(string memory _baseURI) public onlyAdmin { baseURI = _baseURI; } /** * @dev Set the maxMint */ function setMaxMint(uint256 _maxMint) external onlyAdmin { maxMint = _maxMint; } /** * @dev set the amount of Goop earned per interval */ function setGoopPerInterval(uint256 _goopPerInterval) external onlyAdmin { goopPerInterval = _goopPerInterval; } /** * @dev enable/disable Goop claiming */ function setClaim(bool _claimStatus) external onlyAdmin { claimStatus = _claimStatus; } /********************************************************** * * The illest ill-list * **********************************************************/ /** * @dev set the merkleTree root */ function setMerkleRoot(bytes32 _merkleRoot) public onlyAdmin { merkleRoot = _merkleRoot; } /** * @dev calculates the leaf hash */ function leaf(string memory payload) internal pure returns (bytes32) { return keccak256(abi.encodePacked(payload)); } /** * @dev verifies the inclusion of the leaf hash in the merkleTree */ function verify(bytes32 leaf, bytes32[] memory proof) internal view returns (bool) { return MerkleProof.verify(proof, merkleRoot, leaf); } /********************************************************** * * TheLab * **********************************************************/ /** * @notice expect big things from this... */ function multiHelix(uint256 _tokenId) public view returns (uint256) { require(labAddress != address(0x0), "The Lab is being setup."); return ILab(labAddress).getIllogical(_tokenId); } /********************************************************** * * Token management * **********************************************************/ /** * @dev ill-list leverages merkleTree for the mint, there is no public sale. * * The first token in the collection is 0 and the last token is 8887, which * equates to a collection size of 8888. Gas optimization uses an index based * model that returns an array size of 8888. As another gas optimization, we * refrained from <= or >= and as a result we must +1, hence the < 8889. */ function illListMint(bytes32[] calldata proof) public payable { string memory payload = string(abi.encodePacked(_msgSender())); uint256 totalSupply = _owners.length; require(mintingState, "Ill-list not active"); require(verify(leaf(payload), proof), "Invalid Merkle Tree proof supplied"); require(addressToMinted[_msgSender()] == false, "can not mint twice"); require(totalSupply + maxMint < 8889, "project fully minted"); addressToMinted[_msgSender()] = true; for (uint256 i; i < maxMint; i++) { _mint(_msgSender(), totalSupply + i); } } /** * @dev mints 'tId' to 'address' */ function _mint(address to, uint256 tId) internal virtual override { _owners.push(to); emit Transfer(address(0), to, tId); } /********************************************************** * * TOKEN * **********************************************************/ /** * @dev Returns the Uniform Resource Identifier (URI) for the `tokenId` token. */ function tokenURI(uint256 _tId) public view override returns (string memory) { require(_exists(_tId), "Token does not exist."); return string(abi.encodePacked(baseURI, Strings.toString(_tId))); } /** * @dev transfer an array of tokens from '_from' address to '_to' address */ function batchTransferFrom( address _from, address _to, uint256[] memory _tIds ) public { for (uint256 i = 0; i < _tIds.length; i++) { transferFrom(_from, _to, _tIds[i]); } } /** * @dev safe transfer an array of tokens from '_from' address to '_to' address */ function batchSafeTransferFrom( address _from, address _to, uint256[] memory _tIds, bytes memory data_ ) public { for (uint256 i = 0; i < _tIds.length; i++) { safeTransferFrom(_from, _to, _tIds[i], data_); } } /** * @dev returns a confirmation that 'tIds' are owned by 'account' */ function isOwnerOf(address account, uint256[] calldata _tIds) external view returns (bool) { for (uint256 i; i < _tIds.length; ++i) { if (_owners[_tIds[i]] != account) return false; } return true; } /** * @dev Retunrs the tokenIds of 'owner' */ function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) return new uint256[](0); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } /********************************************************** * * GENEROSITY + ETH FUNDING * **********************************************************/ /** * @dev Just in case someone sends ETH to the contract */ function withdraw() public { (bool success, ) = teamWallet.call{value: address(this).balance}(""); require(success, "Failed to send."); } receive() external payable {} /********************************************************** * * CHAINLINK VRF & TOKEN DNA * **********************************************************/ /** * @dev Requests a random number from the Chainlink VRF */ function requestRandomNumber() external onlyAdmin returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) >= VRF_fee, "Not enough LINK"); requestId = requestRandomness(VRF_keyHash, VRF_fee); emit RequestedRandomNumber(requestId); } /** * @dev Receives the random number from the Chainlink VRF callback */ function fulfillRandomness(bytes32 _requestId, uint256 _randomNumber) internal override { periodCounter++; collectionDNA[periodCounter] = _randomNumber; emit RecievedRandomNumber(_requestId, periodCounter, _randomNumber); } /** * @dev this allows you to test the VRF call to ensure it works as expected prior to mint * It resets the collectionDNA and period counter to defaults prior to minting. */ function setVerifyVRF() external onlyAdmin { require(!verifyVRF, "this is a one way function it can not be called twice"); collectionDNA[1] = 0; periodCounter = 0; verifyVRF = true; } /** * @notice A reroll is an opportunity to change your tokenDNA and only available when reroll is enabled. * A token that is rerolled gets brand new tokenDNA that is generated in the next reroll period * with the result of the Chainlink VRF requestRandomNumber(). Its impossible to know the result * of your reroll in advance of the Chainlink call and as a result you may end up with a rarer * or less rare tokenDNA. */ function reroll(uint256[] calldata _tokenIds) external { uint256 amount = REROLL_COST * _tokenIds.length; require(rerollState, "reroll not enabled"); require(goop[_msgSender()] >= amount, "not enough goop for reroll"); for (uint256 i = 0; i < _tokenIds.length; i++) { require(stakedToken[_tokenIds[i]].ownerOfNFT == _msgSender(), "you dont own this token or its not staked"); rollTracker[periodCounter + 1].push(_tokenIds[i]); stakedToken[_tokenIds[i]].lastRerollPeriod = periodCounter; } _burnGoop(_msgSender(), amount); } /** * @dev Set/change the Chainlink VRF keyHash */ function setVRFKeyHash(bytes32 _keyHash) external onlyAdmin { VRF_keyHash = _keyHash; } /** * @dev Set/change the Chainlink VRF fee */ function setVRFFee(uint256 _fee) external onlyAdmin { VRF_fee = _fee; } /** * @notice * - tokenDNA is generated dynamically based on the relevant Chainlink VRF seed. If a token is never * rerolled, it will be constructed based on period 1 (initial VRF) seed. if a token is rerolled in * period 5, its DNA will be based on the VRF seed for period 6. This ensures that no one can * predict or manipulate tokenDNA * - tokenDNA is generated on the fly and not maintained as state on-chain or off-chain. * - tokenDNA is used to construct the unique metadata for each NFT * * - Some people may not like this function as its based on nested loops, so here is the logic * 1. this is an external function and is never called by this contract or future contract * 2. the maximum depth of i will ever be 20, after which all tokenDNA is permanent * 3. it ensures tokenDNA is always correct under all circumstances * 4. it has 0 gas implications */ function getTokenDNA(uint256 _tId) external view returns (uint256) { require(_tId < _owners.length, "tokenId out of range"); for (uint256 i = periodCounter; i > 0; i--) { if (i == 1) { return uint256(keccak256(abi.encode(collectionDNA[i], _tId))); } else { for (uint256 j = 0; j < rollTracker[i].length; j++) { if (rollTracker[i][j] == _tId) { return uint256(keccak256(abi.encode(collectionDNA[i], _tId))); } } } } } /** * @notice To maintain transparency with awarding the "1/1" tokens we are leveraging * ChainlinkVRF. To accomplish this we are calling requestRandomNumber() after the reveal * and will use the next periodCounter to derive a fair one of one giveaway. */ function get1of1() external view returns (uint256[] memory) { uint256[] memory oneOfOnes = new uint256[](20); uint256 counter; uint256 addCounter; bool matchStatus; while (addCounter < 20) { uint256 result = (uint256(keccak256(abi.encode(collectionDNA[2], counter))) % 8887); for (uint256 i = 0; i < oneOfOnes.length; i++) { if (result == oneOfOnes[i]) { matchStatus = true; break; } } if (!matchStatus) { oneOfOnes[addCounter] = result; addCounter++; } else { matchStatus = false; } counter++; } return oneOfOnes; } /********************************************************** * * STAKING & UNSTAKING * **********************************************************/ /** * @notice Staking your NFT transfers ownership to (this) contract until you unstake it. * When an NFT is staked you will earn Goop, which can be used within the illogics * ecosystem to procure items we have for sale. */ function stakeNFT(uint256[] calldata _tokenIds) external { require(stakingState, "staking not enabled"); for (uint256 i = 0; i < _tokenIds.length; i++) { require(ownerOf(_tokenIds[i]) == _msgSender(), "you are not the owner"); safeTransferFrom(_msgSender(), address(this), _tokenIds[i]); stakedToken[_tokenIds[i]].ownerOfNFT = _msgSender(); stakedToken[_tokenIds[i]].timestamp = block.timestamp; staker[_msgSender()].push(_tokenIds[i]); } } /** * @notice unstaking a token that has unrealized Goop forfeits the Goop associated * with the token(s) being unstaked. This was done intentionally as a holder may * not to pay the gas costs associated with claiming Goop. Please see unstakeAndClaim * to also claim Goop. * * Unstaking your NFT transfers ownership back to the address that staked it. * When an NFT is unstaked, you will no longer be earning Goop. */ function unstakeNFT(uint256[] calldata _tokenIds) public { for (uint256 i = 0; i < _tokenIds.length; i++) { require(stakedToken[_tokenIds[i]].ownerOfNFT == _msgSender(), "you are not the owner"); require(canBeUnstaked(_tokenIds[i]), "token in reroll or cool down period"); _transfer(address(this), _msgSender(), _tokenIds[i]); delete stakedToken[_tokenIds[i]].ownerOfNFT; delete stakedToken[_tokenIds[i]].timestamp; delete stakedToken[_tokenIds[i]].lastRerollPeriod; /** * @dev - iterates the array of tokens staked and pops the one being unstaked */ for (uint256 j = 0; j < staker[_msgSender()].length; j++) { if (staker[_msgSender()][j] == _tokenIds[i]) { staker[_msgSender()][j] = staker[_msgSender()][staker[_msgSender()].length - 1]; staker[_msgSender()].pop(); } } } } /** * @dev unstakeAndClaim will unstake the token and realize the Goop that it has earned. * If you are not interested in earning Goop you can call unstaske and save the gas. * Unstaking your NFT transfers ownership back to the address that staked it. * When an NFT is unstaked you will no longer be earning Goop. */ function unstakeAndClaim(uint256[] calldata _tokenIds) external { claimGoop(); unstakeNFT(_tokenIds); } /** * @notice * - An address requests a reroll for a tokenId, the tokenDNA is updated after the subsequent VRF request. * - To prevent the sale of a token prior to the tokenDNA and metadata being refreshed in the marketplace, * we have implemented a cool-down period. The cool down period will allow a token to be unstaked when * it is not in the previous period */ function canBeUnstaked(uint256 _tokenId) public view returns (bool) { // token has never been rerolled and can be unstaked if (stakedToken[_tokenId].lastRerollPeriod == 0) { return true; } // token waiting for next VRF and can not be unstaked if (stakedToken[_tokenId].lastRerollPeriod == periodCounter) { return false; } // token in cooldown period after the reroll and can not be unstaked if (periodCounter - stakedToken[_tokenId].lastRerollPeriod == 1) { return false; } return true; } /** * @dev returns an array of tokens that an address has staked */ function ownerStaked(address _addr) public view returns (uint256[] memory) { return staker[_addr]; } // enables safeTransferFrom function to send ERC721 tokens to this contract (used in staking) function onERC721Received( address operator, address from, uint256 tId, bytes calldata data ) external pure returns (bytes4) { return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); } /********************************************************** * * GOOP ECOSYSTEM * **********************************************************/ /** * @notice * - Goop is an internal point system, there are no goop tokenomics as it * is minted when claimed and burned when spent. As such the amount of goop * in circulation is constantly changing. * - Goop may resemble an ERC20, it can be transferred or donated P2P, however * it cannot be traded on an exchange and has no monetary value, further it * can only be used in the illogics ecosystem. * - Goop exists in 2 forms, claimed and unclaimed, in order to spend goop * it must be claimed. */ /** * @dev Goop earned as a result of staking but not yet claimed/realized */ function unclaimedGoop() external view returns (uint256) { address addr = _msgSender(); uint256 stakedTime; for (uint256 i = 0; i < staker[addr].length; i++) { stakedTime += block.timestamp - stakedToken[staker[addr][i]].timestamp; } return (stakedTime / GOOP_INTERVAL) * goopPerInterval; } /** * @dev claim earned Goop without unstaking */ function claimGoop() public { require(claimStatus, "GOOP: claim not enabled"); address addr = _msgSender(); uint256 stakedTime; for (uint256 i = 0; i < staker[addr].length; i++) { stakedTime += block.timestamp - stakedToken[staker[addr][i]].timestamp; stakedToken[staker[addr][i]].timestamp = block.timestamp; } _mintGoop(addr, (stakedTime / GOOP_INTERVAL) * goopPerInterval); } /** * * @dev Moves `amount` Goop from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * */ function transferGoop(address _to, uint256 _amount) public returns (bool) { address owner = _msgSender(); _transferGoop(owner, _to, _amount); return true; } /** * @dev Moves `amount` of Goop from `sender` to `recipient`. */ function _transferGoop( address from, address to, uint256 _amount ) internal { require(transferState, "GOOP: transfer not enabled"); require(from != address(0), "GOOP: transfer from the zero address"); require(to != address(0), "GOOP: transfer to the zero address"); uint256 fromBalance = goop[from]; require(goop[from] >= _amount, "GOOP: insufficient balance "); unchecked { goop[from] = fromBalance - _amount; } goop[to] += _amount; } /** * @dev admin function to mint Goop to a single address */ function mintGoop(address _addr, uint256 _goop) external override onlyAdmin { _mintGoop(_addr, _goop); } /** * @dev admin function to mint Goop to multiple addresses */ function mintGoopBatch(address[] calldata _addr, uint256 _goop) external override onlyAdmin { for (uint256 i = 0; i < _addr.length; i++) { _mintGoop(_addr[i], _goop); } } /** * @dev Creates `amount` Goop and assigns them to `account` */ function _mintGoop(address account, uint256 amount) internal { require(account != address(0), "GOOP: mint to the zero address"); totalGoopSupply += amount; goop[account] += amount; } /** * @dev admin function to burn Goop from a single address */ function burnGoop(address _addr, uint256 _goop) external override onlyAdmin { _burnGoop(_addr, _goop); } /** * @dev admin function to burn Goop from multiple addresses */ function burnGoopBatch(address[] calldata _addr, uint256 _goop) external override onlyAdmin { for (uint256 i = 0; i < _addr.length; i++) { _burnGoop(_addr[i], _goop); } } /** * @dev permits Goop to be spent within the illogics ecosystem */ function spendGoop(uint256 _item, uint256 _count) public override { addressPurchases[_msgSender()][_item] += _count; require(spendState, "GOOP: spending not enabled"); require(saleItems[_item].saleStatus, "Item not currently for sale"); require(saleItems[_item].supply >= _count, "Item sold out."); require(addressPurchases[_msgSender()][_item] <= saleItems[_item].maxPurchase, "Exceeded allowed purchase quantity"); uint256 cost = _count * saleItems[_item].price; require(goop[_msgSender()] >= cost, "Insufficient goop."); _burnGoop(_msgSender(), cost); saleItems[_item].supply -= _count; totalGoopSpent += _count * saleItems[_item].price; emit spentGoop(_msgSender(), _item, _count); } /** * @dev Destroys `amount` Goop from `account` */ function _burnGoop(address account, uint256 amount) internal { require(account != address(0), "GOOP: burn from the zero address"); uint256 accountBalance = goop[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { goop[account] = accountBalance - amount; } totalGoopSupply -= amount; } /********************************************************** * * GOOP SALE * **********************************************************/ /** * @dev creates a new sale item and sets the sale elements */ function createNewSale( string memory _description, bool _saleState, uint256 _price, uint256 _supply, uint256 _maxPurchase ) external onlyAdmin { saleId++; saleItems[saleId] = Sale(_description, _saleState, _price, _supply, _maxPurchase); } /** * @dev changes the description of the selected item */ function setSaleDescription(uint256 _item, string memory _description) external onlyAdmin { saleItems[_item].description = _description; } /** * @dev enable/disable the sale of the selected item */ function setSaleStatus(uint256 _item, bool _saleStatus) external onlyAdmin { saleItems[_item].saleStatus = _saleStatus; } /** * @dev changes the sale price of the selected item */ function setSalePrice(uint256 _item, uint256 _price) external onlyAdmin { saleItems[_item].price = _price; } /** * @dev changes supply of the selected item */ function setSaleSupply(uint256 _item, uint256 _supply) external onlyAdmin { saleItems[_item].supply = _supply; } /** * @dev changes the max amount an address can purchase of the selected item */ function setMaxPurchase(uint256 _item, uint256 _maxPurchase) external onlyAdmin { saleItems[_item].maxPurchase = _maxPurchase; } /********************************************************** * * OPENSEA * **********************************************************/ function setProxyRegistryAddress(address _proxyRegistryAddress) external onlyAdmin { proxyRegistryAddress = _proxyRegistryAddress; } function flipProxyState(address proxyAddress) public onlyOwner { projectProxy[proxyAddress] = !projectProxy[proxyAddress]; } function isApprovedForAll(address _owner, address operator) public view override returns (bool) { OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == operator || projectProxy[operator]) return true; return super.isApprovedForAll(_owner, operator); } } contract OwnableDelegateProxy {} contract OpenSeaProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; }
permits Goop to be spent within the illogics ecosystem/
function spendGoop(uint256 _item, uint256 _count) public override { addressPurchases[_msgSender()][_item] += _count; require(spendState, "GOOP: spending not enabled"); require(saleItems[_item].saleStatus, "Item not currently for sale"); require(saleItems[_item].supply >= _count, "Item sold out."); require(addressPurchases[_msgSender()][_item] <= saleItems[_item].maxPurchase, "Exceeded allowed purchase quantity"); uint256 cost = _count * saleItems[_item].price; require(goop[_msgSender()] >= cost, "Insufficient goop."); _burnGoop(_msgSender(), cost); saleItems[_item].supply -= _count; totalGoopSpent += _count * saleItems[_item].price; emit spentGoop(_msgSender(), _item, _count); }
13,679,499
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // 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: contracts/spec_interfaces/IMigratableFeesWallet.sol pragma solidity 0.6.12; /// @title An interface for Fee wallets that support bucket migration. interface IMigratableFeesWallet { /// Accepts a bucket fees from a old fees wallet as part of a migration /// @dev Called by the old FeesWallet contract. /// @dev Part of the IMigratableFeesWallet interface. /// @dev assumes the caller approved the transfer of the amount prior to calling /// @param bucketStartTime is the start time of the bucket to migration, must be a bucket's valid start time /// @param amount is the amount to migrate (transfer) to the bucket function acceptBucketMigration(uint256 bucketStartTime, uint256 amount) external; } // File: contracts/spec_interfaces/IFeesWallet.sol pragma solidity 0.6.12; /// @title Fees Wallet contract interface, manages the fee buckets interface IFeesWallet { event FeesWithdrawnFromBucket(uint256 bucketId, uint256 withdrawn, uint256 total); event FeesAddedToBucket(uint256 bucketId, uint256 added, uint256 total); /* * External methods */ /// Top-ups the fee pool with the given amount at the given rate /// @dev Called by: subscriptions contract. (not enforced) /// @dev fills the rewards in 30 days buckets based on the monthlyRate /// @param amount is the amount to fill /// @param monthlyRate is the monthly rate /// @param fromTimestamp is the to start fill the buckets, determines the first bucket to fill and the amount filled in the first bucket. function fillFeeBuckets(uint256 amount, uint256 monthlyRate, uint256 fromTimestamp) external; /// Collect fees from the buckets since the last call and transfers the amount back. /// @dev Called by: only FeesAndBootstrapRewards contract /// @dev The amount to collect may be queried before collect by calling getOutstandingFees /// @return collectedFees the amount of fees collected and transferred function collectFees() external returns (uint256 collectedFees) /* onlyRewardsContract */; /// Returns the amount of fees that are currently available for withdrawal /// @param currentTime is the time to check the pending fees for /// @return outstandingFees is the amount of pending fees to collect at time currentTime function getOutstandingFees(uint256 currentTime) external view returns (uint256 outstandingFees); /* * General governance */ event EmergencyWithdrawal(address addr, address token); /// Migrates the fees of a bucket starting at startTimestamp. /// @dev governance function called only by the migration manager /// @dev Calls acceptBucketMigration in the destination contract. /// @param destination is the address of the new FeesWallet contract /// @param bucketStartTime is the start time of the bucket to migration, must be a bucket's valid start time function migrateBucket(IMigratableFeesWallet destination, uint256 bucketStartTime) external /* onlyMigrationManager */; /// Accepts a fees bucket balance from a old fees wallet as part of the fees wallet migration /// @dev Called by the old FeesWallet contract. /// @dev Part of the IMigratableFeesWallet interface. /// @dev assumes the caller approved the amount prior to calling /// @param bucketStartTime is the start time of the bucket to migration, must be a bucket's valid start time /// @param amount is the amount to migrate (transfer) to the bucket function acceptBucketMigration(uint256 bucketStartTime, uint256 amount) external; /// Emergency withdraw the contract funds /// @dev governance function called only by the migration manager /// @dev used in emergencies only, where migrateBucket is not a suitable solution /// @param erc20 is the erc20 address of the token to withdraw function emergencyWithdraw(address erc20) external /* onlyMigrationManager */; } // File: contracts/spec_interfaces/IManagedContract.sol pragma solidity 0.6.12; /// @title managed contract interface, used by the contracts registry to notify the contract on updates interface IManagedContract /* is ILockable, IContractRegistryAccessor, Initializable */ { /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external; } // File: contracts/spec_interfaces/IContractRegistry.sol pragma solidity 0.6.12; /// @title Contract registry contract interface /// @dev The contract registry holds Orbs PoS contracts and managers lists /// @dev The contract registry updates the managed contracts on changes in the contract list /// @dev Governance functions restricted to managers access the registry to retrieve the manager address /// @dev The contract registry represents the source of truth for Orbs Ethereum contracts /// @dev By tracking the registry events or query before interaction, one can access the up to date contracts interface IContractRegistry { event ContractAddressUpdated(string contractName, address addr, bool managedContract); event ManagerChanged(string role, address newManager); event ContractRegistryUpdated(address newContractRegistry); /* * External functions */ /// Updates the contracts address and emits a corresponding event /// @dev governance function called only by the migrationManager or registryAdmin /// @param contractName is the contract name, used to identify it /// @param addr is the contract updated address /// @param managedContract indicates whether the contract is managed by the registry and notified on changes function setContract(string calldata contractName, address addr, bool managedContract) external /* onlyAdminOrMigrationManager */; /// Returns the current address of the given contracts /// @param contractName is the contract name, used to identify it /// @return addr is the contract updated address function getContract(string calldata contractName) external view returns (address); /// Returns the list of contract addresses managed by the registry /// @dev Managed contracts are updated on changes in the registry contracts addresses /// @return addrs is the list of managed contracts function getManagedContracts() external view returns (address[] memory); /// Locks all the managed contracts /// @dev governance function called only by the migrationManager or registryAdmin /// @dev When set all onlyWhenActive functions will revert function lockContracts() external /* onlyAdminOrMigrationManager */; /// Unlocks all the managed contracts /// @dev governance function called only by the migrationManager or registryAdmin function unlockContracts() external /* onlyAdminOrMigrationManager */; /// Updates a manager address and emits a corresponding event /// @dev governance function called only by the registryAdmin /// @dev the managers list is a flexible list of role to the manager's address /// @param role is the managers' role name, for example "functionalManager" /// @param manager is the manager updated address function setManager(string calldata role, address manager) external /* onlyAdmin */; /// Returns the current address of the given manager /// @param role is the manager name, used to identify it /// @return addr is the manager updated address function getManager(string calldata role) external view returns (address); /// Sets a new contract registry to migrate to /// @dev governance function called only by the registryAdmin /// @dev updates the registry address record in all the managed contracts /// @dev by tracking the emitted ContractRegistryUpdated, tools can track the up to date contracts /// @param newRegistry is the new registry contract function setNewContractRegistry(IContractRegistry newRegistry) external /* onlyAdmin */; /// Returns the previous contract registry address /// @dev used when the setting the contract as a new registry to assure a valid registry /// @return previousContractRegistry is the previous contract registry function getPreviousContractRegistry() external view returns (address); } // File: contracts/spec_interfaces/IContractRegistryAccessor.sol pragma solidity 0.6.12; interface IContractRegistryAccessor { /// Sets the contract registry address /// @dev governance function called only by an admin /// @param newRegistry is the new registry contract function setContractRegistry(IContractRegistry newRegistry) external /* onlyAdmin */; /// Returns the contract registry address /// @return contractRegistry is the contract registry address function getContractRegistry() external view returns (IContractRegistry contractRegistry); function setRegistryAdmin(address _registryAdmin) external /* onlyInitializationAdmin */; } // 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: contracts/WithClaimableRegistryManagement.sol pragma solidity 0.6.12; /** * @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 WithClaimableRegistryManagement is Context { address private _registryAdmin; address private _pendingRegistryAdmin; event RegistryManagementTransferred(address indexed previousRegistryAdmin, address indexed newRegistryAdmin); /** * @dev Initializes the contract setting the deployer as the initial registryRegistryAdmin. */ constructor () internal { address msgSender = _msgSender(); _registryAdmin = msgSender; emit RegistryManagementTransferred(address(0), msgSender); } /** * @dev Returns the address of the current registryAdmin. */ function registryAdmin() public view returns (address) { return _registryAdmin; } /** * @dev Throws if called by any account other than the registryAdmin. */ modifier onlyRegistryAdmin() { require(isRegistryAdmin(), "WithClaimableRegistryManagement: caller is not the registryAdmin"); _; } /** * @dev Returns true if the caller is the current registryAdmin. */ function isRegistryAdmin() public view returns (bool) { return _msgSender() == _registryAdmin; } /** * @dev Leaves the contract without registryAdmin. It will not be possible to call * `onlyManager` functions anymore. Can only be called by the current registryAdmin. * * NOTE: Renouncing registryManagement will leave the contract without an registryAdmin, * thereby removing any functionality that is only available to the registryAdmin. */ function renounceRegistryManagement() public onlyRegistryAdmin { emit RegistryManagementTransferred(_registryAdmin, address(0)); _registryAdmin = address(0); } /** * @dev Transfers registryManagement of the contract to a new account (`newManager`). */ function _transferRegistryManagement(address newRegistryAdmin) internal { require(newRegistryAdmin != address(0), "RegistryAdmin: new registryAdmin is the zero address"); emit RegistryManagementTransferred(_registryAdmin, newRegistryAdmin); _registryAdmin = newRegistryAdmin; } /** * @dev Modifier throws if called by any account other than the pendingManager. */ modifier onlyPendingRegistryAdmin() { require(msg.sender == _pendingRegistryAdmin, "Caller is not the pending registryAdmin"); _; } /** * @dev Allows the current registryAdmin to set the pendingManager address. * @param newRegistryAdmin The address to transfer registryManagement to. */ function transferRegistryManagement(address newRegistryAdmin) public onlyRegistryAdmin { _pendingRegistryAdmin = newRegistryAdmin; } /** * @dev Allows the _pendingRegistryAdmin address to finalize the transfer. */ function claimRegistryManagement() external onlyPendingRegistryAdmin { _transferRegistryManagement(_pendingRegistryAdmin); _pendingRegistryAdmin = address(0); } /** * @dev Returns the current pendingRegistryAdmin */ function pendingRegistryAdmin() public view returns (address) { return _pendingRegistryAdmin; } } // File: contracts/Initializable.sol pragma solidity 0.6.12; contract Initializable { address private _initializationAdmin; event InitializationComplete(); /// Constructor /// Sets the initializationAdmin to the contract deployer /// The initialization admin may call any manager only function until initializationComplete constructor() public{ _initializationAdmin = msg.sender; } modifier onlyInitializationAdmin() { require(msg.sender == initializationAdmin(), "sender is not the initialization admin"); _; } /* * External functions */ /// Returns the initializationAdmin address function initializationAdmin() public view returns (address) { return _initializationAdmin; } /// Finalizes the initialization and revokes the initializationAdmin role function initializationComplete() external onlyInitializationAdmin { _initializationAdmin = address(0); emit InitializationComplete(); } /// Checks if the initialization was completed function isInitializationComplete() public view returns (bool) { return _initializationAdmin == address(0); } } // File: contracts/ContractRegistryAccessor.sol pragma solidity 0.6.12; contract ContractRegistryAccessor is IContractRegistryAccessor, WithClaimableRegistryManagement, Initializable { IContractRegistry private contractRegistry; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address constructor(IContractRegistry _contractRegistry, address _registryAdmin) public { require(address(_contractRegistry) != address(0), "_contractRegistry cannot be 0"); setContractRegistry(_contractRegistry); _transferRegistryManagement(_registryAdmin); } modifier onlyAdmin { require(isAdmin(), "sender is not an admin (registryManger or initializationAdmin)"); _; } modifier onlyMigrationManager { require(isMigrationManager(), "sender is not the migration manager"); _; } modifier onlyFunctionalManager { require(isFunctionalManager(), "sender is not the functional manager"); _; } /// Checks whether the caller is Admin: either the contract registry, the registry admin, or the initialization admin function isAdmin() internal view returns (bool) { return msg.sender == address(contractRegistry) || msg.sender == registryAdmin() || msg.sender == initializationAdmin(); } /// Checks whether the caller is a specific manager role or and Admin /// @dev queries the registry contract for the up to date manager assignment function isManager(string memory role) internal view returns (bool) { IContractRegistry _contractRegistry = contractRegistry; return isAdmin() || _contractRegistry != IContractRegistry(0) && contractRegistry.getManager(role) == msg.sender; } /// Checks whether the caller is the migration manager function isMigrationManager() internal view returns (bool) { return isManager('migrationManager'); } /// Checks whether the caller is the functional manager function isFunctionalManager() internal view returns (bool) { return isManager('functionalManager'); } /* * Contract getters, return the address of a contract by calling the contract registry */ function getProtocolContract() internal view returns (address) { return contractRegistry.getContract("protocol"); } function getStakingRewardsContract() internal view returns (address) { return contractRegistry.getContract("stakingRewards"); } function getFeesAndBootstrapRewardsContract() internal view returns (address) { return contractRegistry.getContract("feesAndBootstrapRewards"); } function getCommitteeContract() internal view returns (address) { return contractRegistry.getContract("committee"); } function getElectionsContract() internal view returns (address) { return contractRegistry.getContract("elections"); } function getDelegationsContract() internal view returns (address) { return contractRegistry.getContract("delegations"); } function getGuardiansRegistrationContract() internal view returns (address) { return contractRegistry.getContract("guardiansRegistration"); } function getCertificationContract() internal view returns (address) { return contractRegistry.getContract("certification"); } function getStakingContract() internal view returns (address) { return contractRegistry.getContract("staking"); } function getSubscriptionsContract() internal view returns (address) { return contractRegistry.getContract("subscriptions"); } function getStakingRewardsWallet() internal view returns (address) { return contractRegistry.getContract("stakingRewardsWallet"); } function getBootstrapRewardsWallet() internal view returns (address) { return contractRegistry.getContract("bootstrapRewardsWallet"); } function getGeneralFeesWallet() internal view returns (address) { return contractRegistry.getContract("generalFeesWallet"); } function getCertifiedFeesWallet() internal view returns (address) { return contractRegistry.getContract("certifiedFeesWallet"); } function getStakingContractHandler() internal view returns (address) { return contractRegistry.getContract("stakingContractHandler"); } /* * Governance functions */ event ContractRegistryAddressUpdated(address addr); /// Sets the contract registry address /// @dev governance function called only by an admin /// @param newContractRegistry is the new registry contract function setContractRegistry(IContractRegistry newContractRegistry) public override onlyAdmin { require(newContractRegistry.getPreviousContractRegistry() == address(contractRegistry), "new contract registry must provide the previous contract registry"); contractRegistry = newContractRegistry; emit ContractRegistryAddressUpdated(address(newContractRegistry)); } /// Returns the contract registry that the contract is set to use /// @return contractRegistry is the registry contract address function getContractRegistry() public override view returns (IContractRegistry) { return contractRegistry; } function setRegistryAdmin(address _registryAdmin) external override onlyInitializationAdmin { _transferRegistryManagement(_registryAdmin); } } // File: contracts/spec_interfaces/ILockable.sol pragma solidity 0.6.12; /// @title lockable contract interface, allows to lock a contract interface ILockable { event Locked(); event Unlocked(); /// Locks the contract to external non-governance function calls /// @dev governance function called only by the migration manager or an admin /// @dev typically called by the registry contract upon locking all managed contracts /// @dev getters and migration functions remain active also for locked contracts /// @dev checked by the onlyWhenActive modifier function lock() external /* onlyMigrationManager */; /// Unlocks the contract /// @dev governance function called only by the migration manager or an admin /// @dev typically called by the registry contract upon unlocking all managed contracts function unlock() external /* onlyMigrationManager */; /// Returns the contract locking status /// @return isLocked is a bool indicating the contract is locked function isLocked() view external returns (bool); } // File: contracts/Lockable.sol pragma solidity 0.6.12; /// @title lockable contract contract Lockable is ILockable, ContractRegistryAccessor { bool public locked; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address constructor(IContractRegistry _contractRegistry, address _registryAdmin) ContractRegistryAccessor(_contractRegistry, _registryAdmin) public {} /// Locks the contract to external non-governance function calls /// @dev governance function called only by the migration manager or an admin /// @dev typically called by the registry contract upon locking all managed contracts /// @dev getters and migration functions remain active also for locked contracts /// @dev checked by the onlyWhenActive modifier function lock() external override onlyMigrationManager { locked = true; emit Locked(); } /// Unlocks the contract /// @dev governance function called only by the migration manager or an admin /// @dev typically called by the registry contract upon unlocking all managed contracts function unlock() external override onlyMigrationManager { locked = false; emit Unlocked(); } /// Returns the contract locking status /// @return isLocked is a bool indicating the contract is locked function isLocked() external override view returns (bool) { return locked; } modifier onlyWhenActive() { require(!locked, "contract is locked for this operation"); _; } } // File: contracts/ManagedContract.sol pragma solidity 0.6.12; /// @title managed contract contract ManagedContract is IManagedContract, Lockable { /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address constructor(IContractRegistry _contractRegistry, address _registryAdmin) Lockable(_contractRegistry, _registryAdmin) public {} /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() virtual override external {} } // File: contracts/FeesWallet.sol pragma solidity 0.6.12; /// @title Fees Wallet contract interface, manages the fee buckets contract FeesWallet is IFeesWallet, ManagedContract { using SafeMath for uint256; uint256 constant BUCKET_TIME_PERIOD = 30 days; uint constant MAX_FEE_BUCKET_ITERATIONS = 24; IERC20 public token; mapping(uint256 => uint256) public buckets; uint256 public lastCollectedAt; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _token is the token used for virtual chains fees constructor(IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _token) ManagedContract(_contractRegistry, _registryAdmin) public { token = _token; lastCollectedAt = block.timestamp; } modifier onlyRewardsContract() { require(msg.sender == rewardsContract, "caller is not the rewards contract"); _; } /* * External methods */ /// Top-ups the fee pool with the given amount at the given rate /// @dev Called by: subscriptions contract. (not enforced) /// @dev fills the rewards in 30 days buckets based on the monthlyRate /// @param amount is the amount to fill /// @param monthlyRate is the monthly rate /// @param fromTimestamp is the to start fill the buckets, determines the first bucket to fill and the amount filled in the first bucket. function fillFeeBuckets(uint256 amount, uint256 monthlyRate, uint256 fromTimestamp) external override onlyWhenActive { uint256 bucket = _bucketTime(fromTimestamp); require(bucket >= _bucketTime(block.timestamp), "FeeWallet::cannot fill bucket from the past"); uint256 _amount = amount; // add the partial amount to the first bucket uint256 bucketAmount = Math.min(amount, monthlyRate.mul(BUCKET_TIME_PERIOD.sub(fromTimestamp % BUCKET_TIME_PERIOD)).div(BUCKET_TIME_PERIOD)); fillFeeBucket(bucket, bucketAmount); _amount = _amount.sub(bucketAmount); // following buckets are added with the monthly rate while (_amount > 0) { bucket = bucket.add(BUCKET_TIME_PERIOD); bucketAmount = Math.min(monthlyRate, _amount); fillFeeBucket(bucket, bucketAmount); _amount = _amount.sub(bucketAmount); } require(token.transferFrom(msg.sender, address(this), amount), "failed to transfer fees into fee wallet"); } /// Collect fees from the buckets since the last call and transfers the amount back. /// @dev Called by: only FeesAndBootstrapRewards contract /// @dev The amount to collect may be queried before collect by calling getOutstandingFees /// @return collectedFees the amount of fees collected and transferred function collectFees() external override onlyRewardsContract returns (uint256 collectedFees) { (uint256 _collectedFees, uint[] memory bucketsWithdrawn, uint[] memory amountsWithdrawn, uint[] memory newTotals) = _getOutstandingFees(block.timestamp); for (uint i = 0; i < bucketsWithdrawn.length; i++) { buckets[bucketsWithdrawn[i]] = newTotals[i]; emit FeesWithdrawnFromBucket(bucketsWithdrawn[i], amountsWithdrawn[i], newTotals[i]); } lastCollectedAt = block.timestamp; require(token.transfer(msg.sender, _collectedFees), "FeesWallet::failed to transfer collected fees to rewards"); return _collectedFees; } /// Returns the amount of fees that are currently available for withdrawal /// @param currentTime is the time to check the pending fees for /// @return outstandingFees is the amount of pending fees to collect at time currentTime function getOutstandingFees(uint256 currentTime) external override view returns (uint256 outstandingFees) { require(currentTime >= block.timestamp, "currentTime must not be in the past"); (outstandingFees,,,) = _getOutstandingFees(currentTime); } /* * Governance functions */ /// Migrates the fees of a bucket starting at startTimestamp. /// @dev governance function called only by the migration manager /// @dev Calls acceptBucketMigration in the destination contract. /// @param destination is the address of the new FeesWallet contract /// @param bucketStartTime is the start time of the bucket to migration, must be a bucket's valid start time function migrateBucket(IMigratableFeesWallet destination, uint256 bucketStartTime) external override onlyMigrationManager { require(_bucketTime(bucketStartTime) == bucketStartTime, "bucketStartTime must be the start time of a bucket"); uint bucketAmount = buckets[bucketStartTime]; if (bucketAmount == 0) return; buckets[bucketStartTime] = 0; emit FeesWithdrawnFromBucket(bucketStartTime, bucketAmount, 0); token.approve(address(destination), bucketAmount); destination.acceptBucketMigration(bucketStartTime, bucketAmount); } /// Accepts a fees bucket balance from a previous fees wallet as part of the fees wallet migration /// @dev Called by the old FeesWallet contract. /// @dev Part of the IMigratableFeesWallet interface. /// @dev assumes the caller approved the amount prior to calling /// @param bucketStartTime is the start time of the bucket to migration, must be a bucket's valid start time /// @param amount is the amount to migrate (transfer) to the bucket function acceptBucketMigration(uint256 bucketStartTime, uint256 amount) external override { require(_bucketTime(bucketStartTime) == bucketStartTime, "bucketStartTime must be the start time of a bucket"); fillFeeBucket(bucketStartTime, amount); require(token.transferFrom(msg.sender, address(this), amount), "failed to transfer fees into fee wallet on bucket migration"); } /// Emergency withdraw the contract funds /// @dev governance function called only by the migration manager /// @dev used in emergencies only, where migrateBucket is not a suitable solution /// @param erc20 is the erc20 address of the token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "FeesWallet::emergencyWithdraw - transfer failed"); } /* * Private methods */ /// Fills a bucket with the given amount and emits a corresponding event function fillFeeBucket(uint256 bucketId, uint256 amount) private { uint256 bucketTotal = buckets[bucketId].add(amount); buckets[bucketId] = bucketTotal; emit FeesAddedToBucket(bucketId, amount, bucketTotal); } /// Returns the amount of fees that are currently available for withdrawal /// Private function utilized by collectFees and getOutstandingFees /// @dev the buckets details returned by the function are used for the corresponding events generation /// @param currentTime is the time to check the pending fees for /// @return outstandingFees is the amount of pending fees to collect at time currentTime /// @return bucketsWithdrawn is the list of buckets that fees were withdrawn from /// @return withdrawnAmounts is the list of amounts withdrawn from the buckets /// @return newTotals is the updated total of the buckets function _getOutstandingFees(uint256 currentTime) private view returns (uint256 outstandingFees, uint[] memory bucketsWithdrawn, uint[] memory withdrawnAmounts, uint[] memory newTotals) { uint _lastCollectedAt = lastCollectedAt; uint nUpdatedBuckets = _bucketTime(currentTime).sub(_bucketTime(_lastCollectedAt)).div(BUCKET_TIME_PERIOD).add(1); bucketsWithdrawn = new uint[](nUpdatedBuckets); withdrawnAmounts = new uint[](nUpdatedBuckets); newTotals = new uint[](nUpdatedBuckets); uint bucketsPayed = 0; while (bucketsPayed < MAX_FEE_BUCKET_ITERATIONS && _lastCollectedAt < currentTime) { uint256 bucketStart = _bucketTime(_lastCollectedAt); uint256 bucketEnd = bucketStart.add(BUCKET_TIME_PERIOD); uint256 payUntil = Math.min(bucketEnd, currentTime); uint256 bucketDuration = payUntil.sub(_lastCollectedAt); uint256 remainingBucketTime = bucketEnd.sub(_lastCollectedAt); uint256 bucketTotal = buckets[bucketStart]; uint256 amount = bucketTotal.mul(bucketDuration).div(remainingBucketTime); outstandingFees = outstandingFees.add(amount); bucketTotal = bucketTotal.sub(amount); bucketsWithdrawn[bucketsPayed] = bucketStart; withdrawnAmounts[bucketsPayed] = amount; newTotals[bucketsPayed] = bucketTotal; _lastCollectedAt = payUntil; bucketsPayed++; } } /// Returns the start time of a bucket, used also to identify the bucket function _bucketTime(uint256 time) private pure returns (uint256) { return time.sub(time % BUCKET_TIME_PERIOD); } /* * Contracts topology / registry interface */ address rewardsContract; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { rewardsContract = getFeesAndBootstrapRewardsContract(); } }
Emergency withdraw the contract funds governance function called only by the migration manager used in emergencies only, where migrateBucket is not a suitable solution erc20 is the erc20 address of the token to withdraw
function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "FeesWallet::emergencyWithdraw - transfer failed"); }
5,910,440
// solhint-disable reason-string // solhint-disable contract-name-camelcase pragma solidity 0.4.16; /** * token contract functions */ contract Token { 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 approveAndCall( address spender, uint tokens, bytes data ) external returns (bool success); function transferFrom( address from, address to, uint256 value ) external returns (bool); } library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function ceil(uint256 a, uint256 m) internal constant returns (uint256) { uint256 c = add(a, m); uint256 d = sub(c, 1); return mul(div(d, m), m); } } 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 LockService is owned { using SafeMath for uint256; /* * deposit vars */ struct Items { address tokenAddress; address withdrawalAddress; uint256 tokenAmount; uint256 unlockTime; bool withdrawn; } uint256 public depositId; uint256[] public allDepositIds; mapping(address => uint256[]) public depositsByWithdrawalAddress; mapping(uint256 => Items) public lockedToken; mapping(address => mapping(address => uint256)) public walletTokenBalance; event LogWithdrawal(address SentToAddress, uint256 AmountTransferred); /** *lock tokens */ function lockTokens( address _tokenAddress, address _withdrawalAddress, uint256 _amount, uint256 _unlockTime ) public returns (uint256 _id) { require(_amount > 0); require(_unlockTime < 10000000000); //update balance in address walletTokenBalance[_tokenAddress][_withdrawalAddress] = walletTokenBalance[_tokenAddress][_withdrawalAddress].add( _amount ); _id = ++depositId; lockedToken[_id].tokenAddress = _tokenAddress; lockedToken[_id].withdrawalAddress = _withdrawalAddress; lockedToken[_id].tokenAmount = _amount; lockedToken[_id].unlockTime = _unlockTime; lockedToken[_id].withdrawn = false; allDepositIds.push(_id); depositsByWithdrawalAddress[_withdrawalAddress].push(_id); // transfer tokens into contract require(Token(_tokenAddress).transferFrom(msg.sender, this, _amount)); } /** *Create multiple locks */ function createMultipleLocks( address _tokenAddress, address _withdrawalAddress, uint256[] _amounts, uint256[] _unlockTimes ) public returns (uint256 _id) { require(_amounts.length > 0); require(_amounts.length == _unlockTimes.length); uint256 i; for (i = 0; i < _amounts.length; i++) { require(_amounts[i] > 0); require(_unlockTimes[i] < 10000000000); //update balance in address walletTokenBalance[_tokenAddress][_withdrawalAddress] = walletTokenBalance[_tokenAddress][_withdrawalAddress].add( _amounts[i] ); _id = ++depositId; lockedToken[_id].tokenAddress = _tokenAddress; lockedToken[_id].withdrawalAddress = _withdrawalAddress; lockedToken[_id].tokenAmount = _amounts[i]; lockedToken[_id].unlockTime = _unlockTimes[i]; lockedToken[_id].withdrawn = false; allDepositIds.push(_id); depositsByWithdrawalAddress[_withdrawalAddress].push(_id); //transfer tokens into contract require(Token(_tokenAddress).transferFrom(msg.sender, this, _amounts[i])); } } /** *Extend lock Duration */ function extendLockDuration(uint256 _id, uint256 _unlockTime) public { require(_unlockTime < 10000000000); require(_unlockTime > lockedToken[_id].unlockTime); require(!lockedToken[_id].withdrawn); require(msg.sender == lockedToken[_id].withdrawalAddress); //set new unlock time lockedToken[_id].unlockTime = _unlockTime; } /** *transfer locked tokens */ function transferLocks(uint256 _id, address _receiverAddress) public { require(!lockedToken[_id].withdrawn); require(msg.sender == lockedToken[_id].withdrawalAddress); //decrease sender's token balance walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = walletTokenBalance[lockedToken[_id].tokenAddress][ msg.sender ].sub(lockedToken[_id].tokenAmount); //increase receiver's token balance walletTokenBalance[lockedToken[_id].tokenAddress][_receiverAddress] = walletTokenBalance[ lockedToken[_id].tokenAddress ][_receiverAddress].add(lockedToken[_id].tokenAmount); //remove this id from sender address uint256 j; uint256 arrLength = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length; for (j = 0; j < arrLength; j++) { if (depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] == _id) { depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] = depositsByWithdrawalAddress[ lockedToken[_id].withdrawalAddress ][arrLength - 1]; depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length--; break; } } //Assign this id to receiver address lockedToken[_id].withdrawalAddress = _receiverAddress; depositsByWithdrawalAddress[_receiverAddress].push(_id); } /** *withdraw tokens */ function withdrawTokens(uint256 _id) public { require(block.timestamp >= lockedToken[_id].unlockTime); require(msg.sender == lockedToken[_id].withdrawalAddress); require(!lockedToken[_id].withdrawn); lockedToken[_id].withdrawn = true; //update balance in address walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = walletTokenBalance[lockedToken[_id].tokenAddress][ msg.sender ].sub(lockedToken[_id].tokenAmount); //remove this id from this address uint256 j; uint256 arrLength = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length; for (j = 0; j < arrLength; j++) { if (depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] == _id) { depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] = depositsByWithdrawalAddress[ lockedToken[_id].withdrawalAddress ][arrLength - 1]; depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length--; break; } } // transfer tokens to wallet address require(Token(lockedToken[_id].tokenAddress).transfer(msg.sender, lockedToken[_id].tokenAmount)); LogWithdrawal(msg.sender, lockedToken[_id].tokenAmount); } /*get total token balance in contract*/ function getTotalTokenBalance(address _tokenAddress) public view returns (uint256) { return Token(_tokenAddress).balanceOf(this); } /*get total token balance by address*/ function getTokenBalanceByAddress(address _tokenAddress, address _walletAddress) public view returns (uint256) { return walletTokenBalance[_tokenAddress][_walletAddress]; } /*get allDepositIds*/ function getAllDepositIds() public view returns (uint256[]) { return allDepositIds; } /*get getDepositDetails*/ function getDepositDetails(uint256 _id) public view returns ( address _tokenAddress, address _withdrawalAddress, uint256 _tokenAmount, uint256 _unlockTime, bool _withdrawn ) { return ( lockedToken[_id].tokenAddress, lockedToken[_id].withdrawalAddress, lockedToken[_id].tokenAmount, lockedToken[_id].unlockTime, lockedToken[_id].withdrawn ); } /*get DepositsByWithdrawalAddress*/ function getDepositsByWithdrawalAddress(address _withdrawalAddress) public view returns (uint256[]) { return depositsByWithdrawalAddress[_withdrawalAddress]; } }
Extend lock Duration/set new unlock time
function extendLockDuration(uint256 _id, uint256 _unlockTime) public { require(_unlockTime < 10000000000); require(_unlockTime > lockedToken[_id].unlockTime); require(!lockedToken[_id].withdrawn); require(msg.sender == lockedToken[_id].withdrawalAddress); lockedToken[_id].unlockTime = _unlockTime; }
2,138,543
pragma solidity >=0.5.0 <0.6.0; import '../libs/collections/AddressMap.sol'; import '../libs/lifecycle/LockableDestroyable.sol'; import '../libs/ownership/Ownable.sol'; import "../libs/strings/AddressToASCII.sol"; import "./IRegistry.sol"; /** * @title Registry */ contract Registry is IRegistry, Ownable, LockableDestroyable { using AddressMap for AddressMap.Data; using AddressToASCII for address; struct Account { address addr; uint8 kind; bool frozen; address parent; bytes32 hash; } // ------------------------------- Variables ------------------------------- // Number of data slots available per account uint8 constant MAX_DATA = 100; // Account variables // - indices: Mapping of address to index // - items: Mapping of index to account // - accounts: Count of items/accounts mapping(address => int256) private indices; mapping(int256 => Account) private items; int256 public accounts; // Account data // - mapping of: // MAX_DATA // (address => (index => data)) mapping(address => mapping(uint8 => bytes32)) public data; // Account hash mappings mapping(bytes32 => AddressMap.Data) public hashes; // Address write permissions // (kind => address) mapping(uint8 => AddressMap.Data) public permissions; // ------------------------------- Modifiers ------------------------------- /** * Ensures the `msg.sender` has permission for the given kind/type of account. * * - The `owner` account is always allowed * - Addresses/Contracts must have a corresponding entry, for the given kind */ modifier isAllowed(uint8 kind) { // Verify permission require(kind > 0, "Invalid, or missing permission"); if (msg.sender != owner) { require(permissions[kind].exists(msg.sender), "Missing permission"); } _; } // ------------------------------------------------------------------------- /** * Adds an account to storage * THROWS when `msg.sender` doesn't have permission * THROWS when the account already exists * @param addr The address of the account * @param kind The kind of account * @param isFrozen The frozen status of the account * @param parent The account parent/owner * @param hash The hash that uniquely identifies the account */ function addAccount(address addr, uint8 kind, bool isFrozen, address parent, bytes32 hash) isUnlocked isAllowed(kind) external { // Check if the account already exists int256 oneBasedIndex = indices[addr]; require(oneBasedIndex < 1 || oneBasedIndex > accounts, "Account already exists"); // Prevent cyclical lineage Account memory a = Account(addr, kind, isFrozen, parent, hash); (bool cyclical, address at) = hasCyclicalLineage(a); require(!cyclical, string(abi.encodePacked("Cyclical lineage at address: ", at.toString()))); // Append the account/index and update the count accounts++; indices[addr] = accounts; items[accounts] = a; hashes[hash].append(addr); } /** * Sets an account's frozen status * THROWS when the account doesn't exist * @param addr The address of the account * @param frozen The frozen status of the account */ function setAccountFrozen(address addr, bool frozen) isUnlocked isAllowed(get(addr).kind) external { // NOTE: Not bounds checking `index` here, as `isAllowed` ensures the address exists. // Indices are one-based internally, so we need to add one to compensate. int256 oneBasedIndex = indices[addr]; items[oneBasedIndex].frozen = frozen; } /** * Sets the account's parent * THROWS when the account doesn't exist or when the new parent would cause a cyclical lineage * @param addr The address of the account * @param parent The new parent of the account */ function setAccountParent(address addr, address parent) isUnlocked isAllowed(get(addr).kind) external { // NOTE: Not bounds checking `index` here, as `isAllowed` ensures the address exists. // Indices are one-based internally, so we need to add one to compensate. Account storage a = items[indices[addr]]; a.parent = parent; (bool cyclical, address at) = hasCyclicalLineage(a); require(!cyclical, string(abi.encodePacked("Cyclical lineage at address: ", at.toString()))); } /** * Sets the account's hash * THROWS when the account doesn't exist * @dev Removes the current hash from `hashes` and adds a new entry, using the new hash, to `hashes` * @param addr The address of the account * @param hash The new hash of the account */ function setAccountHash(address addr, bytes32 hash) isUnlocked isAllowed(get(addr).kind) external { // NOTE: Not bounds checking `index` here, as `isAllowed` ensures the address exists. // Indices are one-based internally, so we need to add one to compensate. Account storage a = items[indices[addr]]; hashes[a.hash].remove(addr); hashes[hash].append(addr); a.hash = hash; } /** * Removes an account from storage * THROWS when the account doesn't exist * @param addr The address of the account */ function removeAccount(address addr) isUnlocked isAllowed(get(addr).kind) external { // Remove data bytes32 ZERO_BYTES = bytes32(0); mapping(uint8 => bytes32) storage accountData = data[addr]; for (uint8 i = 0; i < MAX_DATA; i++) { if (accountData[i] != ZERO_BYTES) { delete accountData[i]; } } // Remove hash int256 oneBasedIndex = indices[addr]; bytes32 h = items[oneBasedIndex].hash; hashes[h].remove(addr); // Remove account // When the item being removed is not the last item in the collection, // replace that item with the last one, otherwise zero it out. // // If {2} is the item to be removed // [0, 1, 2, 3, 4] // The result would be: // [0, 1, 4, 3] // if (oneBasedIndex < accounts) { // Replace with last item Account storage last = items[accounts]; // Get the last item indices[last.addr] = oneBasedIndex; // Update last items index to current index items[oneBasedIndex] = last; // Update current index to last item delete items[accounts]; // Delete the last item, since it's moved } else { // Delete the account delete items[oneBasedIndex]; } delete indices[addr]; accounts--; } /** * Sets data for an address/caller * THROWS when the account doesn't exist * @param addr The address * @param index The index of the data * @param customData The data store set */ function setAccountData(address addr, uint8 index, bytes32 customData) isUnlocked isAllowed(get(addr).kind) external { require(index < MAX_DATA, "index outside of bounds"); data[addr][index] = customData; } /** * Adds/Removes permissions for the given address * THROWS when the permissions can't be granted/revoked * @param kind The kind of the permissions to grant * @param addr The address to add/remove permissions for * @param grant If permissions are being granted or revoked */ function setPermission(uint8 kind, address addr, bool grant) isUnlocked isAllowed(kind) external { if (grant) { require(permissions[kind].append(addr), "Address already has permission"); } else { require(permissions[kind].remove(addr), "Address permission don't exist"); } } // ---------------------------- Address Getters ---------------------------- /** * Gets the account at the given index * THROWS when the index is out-of-bounds * @param index The index of the item to retrieve * @return The address, kind, frozen status, and parent of the account at the given index */ function accountAt(int256 index) external view returns(address, uint8, bool, address, bytes32) { require(index >= 0 && index < accounts, "Index outside of bounds"); Account memory a = items[index + 1]; return (a.addr, a.kind, a.frozen, a.parent, a.hash); } /** * Gets the account of the hash at the given index * THROWS when the index is out-of-bounds * @param hash The hash of the item to retrieve * @param index The index of the item to retrieve * @return The address, kind, frozen status, and parent of the account at the given index */ function accountAtHash(bytes32 hash, int256 index) external view returns(address, uint8, bool, address, bytes32) { Account memory a = get(hashes[hash].at(index)); return (a.addr, a.kind, a.frozen, a.parent, a.hash); } /** * Gets the address of the hash at the given index * THROWS when the index is out-of-bounds * @param hash The hash of the item to retrieve * @param index The index of the item to retrieve * @return The address of the hash at the given index */ function addressAtHash(bytes32 hash, int256 index) external view returns(address) { return hashes[hash].at(index); } /** * Gets the account for the given address * THROWS when the account doesn't exist * @param addr The address of the item to retrieve * @return The address, kind, frozen status, parent, and hash of the account at the given index */ function accountGet(address addr) external view returns(uint8, bool, address, bytes32) { Account memory a = get(addr); return (a.kind, a.frozen, a.parent, a.hash); } /** * Gets the hash for the given account address * THROWS when the account doesn't exist * @param addr The address of the account * @return The hash * @return The hash of the address */ function accountHash(address addr) external view returns(bytes32) { return get(addr).hash; } /** * Gets the parent address for the given account address * THROWS when the account doesn't exist * @param addr The address of the account * @return The parent address */ function accountParent(address addr) external view returns(address) { return get(addr).parent; } /** * Gets the account kind, for the given account address * THROWS when the account doesn't exist * @param addr The address of the account * @return The kind of account */ function accountKind(address addr) external view returns(uint8) { return get(addr).kind; } /** * Gets the frozen status of the account * THROWS when the account doesn't exist * @param addr The address of the account * @return The frozen status of the account */ function accountFrozen(address addr) external view returns(bool) { return get(addr).frozen; } /** * Gets the kind and frozen status of the account * THROWS when the account doesn't exist * @param addr The address of the account * @return The kind and frozen status of the account */ function accountKindAndFrozen(address addr) external view returns(uint8, bool) { Account memory a = get(addr); return (a.kind, a.frozen); } /** * Returns the kind of the addr and the first lineage address that's frozen, or itself when frozen. * THROWS when the account doesn't exist * @dev It IS required to check ancestral existence, as this function doesn't use `lineageCount(address)` * @param addr The address of the account * @return The kind of the addr and whether any account in its lineage is frozen, or blocked by the callback */ function accountKindAndFrozenAddress(address addr) external view returns(uint8, address) { int256 oneBasedIndex = indices[addr]; require(oneBasedIndex > 0 && oneBasedIndex <= accounts, "Account doesn't exist"); Account memory a = items[oneBasedIndex]; if (a.frozen) { return (a.kind, a.addr); } uint8 kind = a.kind; address frozen; while(a.parent != ZERO_ADDRESS) { oneBasedIndex = indices[a.parent]; if (oneBasedIndex < 1 || oneBasedIndex > accounts) { break; // Parent doesn't exist } a = items[oneBasedIndex]; if (a.frozen) { frozen = a.addr; break; } } return (kind, frozen); } /** * Returns the kind of the addr, the first frozen address within the lineage, or the addr when it's frozen, and * an array of lineage addresses. * THROWS when the account doesn't exist * @dev It IS NOT required to check ancestral existence, as this is taken care of within `lineageCount(address)` * @param addr The address to get the kind, frozen address, and lineage for * @return The kind of the addr, frozen address, lineage addresses */ function accountKindAndFrozenAddressLineage(address addr) external view returns(uint8, address, address[] memory) { uint256 count = lineageCount(addr); address[] memory lineage = new address[](count); Account memory a = items[indices[addr]]; uint8 kind = a.kind; address frozen; if (a.frozen) { frozen = a.addr; } for (uint256 i = 0; i < count; i++) { a = items[indices[a.parent]]; lineage[i] = a.addr; // Set to the first frozen address if (a.frozen && frozen == ZERO_ADDRESS) { frozen = a.addr; } } return (kind, frozen, lineage); } /** * Returns the lineage addresses of the addr * THROWS when the account doesn't exist * @dev It IS NOT required to check ancestral existence, as this is taken care of within `lineageCount(address)` * @param addr The address to retrieve the lineage for * @return The lineage of the given addr */ function accountLineage(address addr) external view returns(address[] memory) { uint256 count = lineageCount(addr); address[] memory lineage = new address[](count); Account memory a = items[indices[addr]]; for (uint256 i = 0; i < count; i++) { a = items[indices[a.parent]]; lineage[i] = a.addr; } return lineage; } /** * Gets the index of the account * Returns -1 for missing accounts * @param addr The address of the account to get the index for * @return The index of the given account address */ function accountIndexOf(address addr) external view returns(int256) { if (addr == ZERO_ADDRESS) { return -1; } int256 index = indices[addr] - 1; if (index < 0 || index >= accounts) { return -1; } return index; } /** * Returns whether or not the given address exists * @param addr The account address * @return If the given address exists */ function accountExists(address addr) external view returns(bool) { int256 oneBasedIndex = indices[addr]; return oneBasedIndex > 0 && oneBasedIndex <= accounts; } /** * Returns whether or not the given address exists for the given kind * @param addr The account address * @param kind The kind of address * @return If the given address exists with the given kind */ function accountKindExists(address addr, uint8 kind) external view returns(bool) { int256 oneBasedIndex = indices[addr]; if (oneBasedIndex < 1 || oneBasedIndex > accounts) { return false; } return items[oneBasedIndex].kind == kind; } // -------------------------- Permission Getters --------------------------- /** * Retrieves the permission address at the index for the given type * THROWS when the index is out-of-bounds * @param kind The kind of permission * @param index The index of the item to retrieve * @return The permission address of the item at the given index */ function permissionAt(uint8 kind, int256 index) external view returns(address) { return permissions[kind].at(index); } /** * Gets the index of the permission address for the given type * Returns -1 for missing permission * @param kind The kind of permission * @param addr The address of the permission to get the index for * @return The index of the given permission address */ function permissionIndexOf(uint8 kind, address addr) external view returns(int256) { return permissions[kind].indexOf(addr); } /** * Returns whether or not the given permission address exists for the given type * @param kind The kind of permission * @param addr The address to check for permission * @return If the given address has permission or not */ function permissionExists(uint8 kind, address addr) external view returns(bool) { return permissions[kind].exists(addr); } // ------------------------------------------------------------------------- /** * Returns the lineage addresses of all the addresses * THROWS when any account doesn't exist * @dev Only contains existant ancestors, stopping at the first non-existent account * @param addresses The addresses to retrieve the lineage for * @return The lineage of the given addresses */ function accountLineage(address[] memory addresses) public view returns(address[] memory) { // Get the total lineage count for all addresses uint256 count; for (uint256 i = 0; i < addresses.length; i++) { count += lineageCount(addresses[i]); } // Get each lineage address for all addresses address[] memory lineage = new address[](count); uint256 i = 0; for (uint256 j = 0; j < addresses.length; j++) { Account memory a = items[indices[addresses[j]]]; int256 oneBasedIndex = indices[a.parent]; while (oneBasedIndex > 0 && oneBasedIndex <= accounts) { a = items[oneBasedIndex]; lineage[i++] = a.addr; oneBasedIndex = indices[a.parent]; } } return lineage; } /** * Gets the number of ancestors of the given addr * THROWS when the account doesn't exist * @dev Only counts existant ancestors, stopping at the first non-existent account * @param addr The address to retrieve ancestry count for * @return The number of ancestry addresses */ function lineageCount(address addr) public view returns(uint256) { int256 oneBasedIndex = indices[addr]; require(oneBasedIndex > 0 && oneBasedIndex <= accounts, "Account doesn't exist"); uint256 count; Account memory a = items[oneBasedIndex]; while(a.parent != ZERO_ADDRESS) { oneBasedIndex = indices[a.parent]; if (oneBasedIndex < 1 || oneBasedIndex > accounts) { break; // Parent doesn't exist } a = items[oneBasedIndex]; count++; } return count; } /** * Gets the account for the given address * THROWS when the account doesn't exist * @param addr The address of the item to retrieve * @return The address, kind, frozen status, and parent of the account at the given index */ function get(address addr) internal view returns(Account memory) { int256 oneBasedIndex = indices[addr]; require(oneBasedIndex > 0 && oneBasedIndex <= accounts, "Account doesn't exist"); return items[oneBasedIndex]; } /** * Checks if the given account has a cyclical kind lineage * @param account The account to check lineage for * @return If the lineage is non-cyclical */ function hasCyclicalLineage(Account memory account) internal view returns (bool, address) { // Account can't be its parent if (account.addr == account.parent) { return (true, account.parent); } // Ensure lineage kind uniqueness uint256 lineage; Account memory a = account; while(a.parent != ZERO_ADDRESS) { int256 oneBasedIndex = indices[a.parent]; if (oneBasedIndex < 1 || oneBasedIndex > accounts) { break; } uint256 l = lineage | (1 << uint256(a.kind)); if (lineage == l) { return (true, a.parent); } lineage = l; a = items[oneBasedIndex]; } return (false, ZERO_ADDRESS); } }
Returns the lineage addresses of all the addresses THROWS when any account doesn't exist Only contains existant ancestors, stopping at the first non-existent account addresses The addresses to retrieve the lineage for return The lineage of the given addresses/ Get the total lineage count for all addresses
function accountLineage(address[] memory addresses) public view returns(address[] memory) { uint256 count; for (uint256 i = 0; i < addresses.length; i++) { count += lineageCount(addresses[i]); } uint256 i = 0; for (uint256 j = 0; j < addresses.length; j++) { Account memory a = items[indices[addresses[j]]]; int256 oneBasedIndex = indices[a.parent]; while (oneBasedIndex > 0 && oneBasedIndex <= accounts) { a = items[oneBasedIndex]; lineage[i++] = a.addr; oneBasedIndex = indices[a.parent]; } } return lineage; }
12,591,973
./full_match/4/0x3ABc8aCa8163B53754741F52612C47a457db5D00/sources/contracts/conduit/ConduitController.sol
Retrieve the total number of open channels for a given conduit. conduit The conduit for which to retrieve the total channel count. return totalChannels The total number of open channels for the conduit./ Ensure that the conduit in question exists. Retrieve the total open channel count for the conduit in question.
function getTotalChannels(address conduit) external view override returns (uint256 totalChannels) { _assertConduitExists(conduit); totalChannels = _conduits[conduit].channels.length; }
660,904
./partial_match/1/0xf64752B870178085BC1d343a6136656D33598950/sources/ERC721A.sol
See {IERC721Metadata-tokenURI}./
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); return bytes(_baseURI).length > 0 ? string(abi.encodePacked(_baseURI, tokenId.toString())) : ""; }
4,378,969
//SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./XToken.sol"; import "./XTokenWrapper.sol"; import "../interfaces/IOperationsRegistry.sol"; import "../interfaces/IEurPriceFeed.sol"; /** * @title XTokenFactory * @author Protofire * @dev Contract module which provides the functionalities for deploying a registering new xToken contracts. * */ contract XTokenFactory is Ownable { /** * @dev Address of xToken Wrapper module. */ address public xTokenWrapper; /** * @dev Address of Operations Registry module. */ address public operationsRegistry; /** * @dev Address of EUR Price feed module. */ address public eurPriceFeed; /** * @dev Emitted when `xTokenWrapper` address is set. */ event XTokenWrapperSet(address indexed newXTokenWrapper); /** * @dev Emitted when `operationsRegistry` address is set. */ event OperationsRegistrySet(address indexed newOperationsRegistry); /** * @dev Emitted when `eurPriceFeed` address is set. */ event EurPriceFeedSet(address indexed newEurPriceFeed); /** * @dev Emitted when xToken is deployed. */ event XTokenDeployed(address indexed xToken); /** * @dev Sets the values for {xTokenWrapper}, {operationsRegistry} and {eurPriceFeed}. * * Sets ownership to the account that deploys the contract. * */ constructor( address _xTokenWrapper, address _operationsRegistry, address _eurPriceFeed ) { _setXTokenWrapper(_xTokenWrapper); _setOperationsRegistry(_operationsRegistry); _setEurPriceFeed(_eurPriceFeed); } /** * @dev Sets `_xTokenWrapper` as the new xToken Wrapper module. * * Requirements: * * - the caller must be the owner. * - `_xTokenWrapper` should not be the zero address. * * @param _xTokenWrapper The address of the new xToken Wrapper module. */ function setXTokenWrapper(address _xTokenWrapper) external onlyOwner { _setXTokenWrapper(_xTokenWrapper); } /** * @dev Sets `_operationsRegistry` as the new Operations Registry module. * * Requirements: * * - the caller must be the owner. * - `_operationsRegistry` should not be the zero address. * * @param _operationsRegistry The address of the new Operations Registry module. */ function setOperationsRegistry(address _operationsRegistry) external onlyOwner { _setOperationsRegistry(_operationsRegistry); } /** * @dev Sets `_eurPriceFeed` as the new EUR Price feed module. * * Requirements: * * - the caller must be the owner. * - `_eurPriceFeed` should not be the zero address. * * @param _eurPriceFeed The address of the new EUR Price feed module. */ function setEurPriceFeed(address _eurPriceFeed) external onlyOwner { _setEurPriceFeed(_eurPriceFeed); } /** * @dev Deploys a new xToken. * Register the new xToken in xTokenWrapper * Register the new xToken as allowed asset in OperationRagistry * Registrer the assetFeed for the new xToken in EurPriceFeed * * Requirements: * * - the caller must be the owner. * - xToken deployment requirement. * - xTokenWrapper registerToken function requirements. * - OperationsRegistry allowAsset function requirements. * - EurPriceFeed setAssetFeed function requirements. * * @param token_ The address of the ERC20 token the xToken represents. * @param name_ The name of the new xTokens. * @param symbol_ The symbol of the new xToken. * @param decimals_ The decimals of the new xToken. * @param kya_ The Know you asset of the new xToken. * @param authorization_ Address of the authorization module to be used by the new xToken. * @param assetFeed_ The address of the new assetFeed to be used in EurPriceFeed for the new xToken. */ function deployXToken( address token_, string memory name_, string memory symbol_, uint8 decimals_, string memory kya_, address authorization_, address assetFeed_ ) external onlyOwner returns (address) { XToken xToken = new XToken(name_, symbol_, decimals_, kya_, authorization_, operationsRegistry); xToken.setWrapper(xTokenWrapper); xToken.grantRole(xToken.DEFAULT_ADMIN_ROLE(), owner()); XTokenWrapper(xTokenWrapper).registerToken(token_, address(xToken)); IOperationsRegistry(operationsRegistry).allowAsset(address(xToken)); IEurPriceFeed(eurPriceFeed).setAssetFeed(address(xToken), assetFeed_); emit XTokenDeployed(address(xToken)); return address(xToken); } /** * @dev Sets `_eurPriceFeed` as the new EUR Price feed module. * * Requirements: * * - the caller must be the owner. * - `_xTokenWrapper` should not be the zero address. * * @param _xTokenWrapper The address of the new xToken Wrapper module. */ function _setXTokenWrapper(address _xTokenWrapper) internal { require(_xTokenWrapper != address(0), "xToken wrapper is the zero address"); emit XTokenWrapperSet(_xTokenWrapper); xTokenWrapper = _xTokenWrapper; } /** * @dev Sets `_eurPriceFeed` as the new EUR Price feed module. * * Requirements: * * - the caller must be the owner. * - `_operationsRegistry` should not be the zero address. * * @param _operationsRegistry The address of the new Operations Registry module. */ function _setOperationsRegistry(address _operationsRegistry) internal { require(_operationsRegistry != address(0), "operations registry feed is the zero address"); emit OperationsRegistrySet(_operationsRegistry); operationsRegistry = _operationsRegistry; } /** * @dev Sets `_eurPriceFeed` as the new EUR Price feed module. * * Requirements: * * - the caller must be the owner. * - `_eurPriceFeed` should not be the zero address. * * @param _eurPriceFeed The address of the new EUR Price feed module. */ function _setEurPriceFeed(address _eurPriceFeed) internal { require(_eurPriceFeed != address(0), "eur price feed is the zero address"); emit EurPriceFeedSet(_eurPriceFeed); eurPriceFeed = _eurPriceFeed; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } //SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../authorization/Authorizable.sol"; import "../interfaces/IAuthorization.sol"; import "../interfaces/IOperationsRegistry.sol"; /** * @title XToken * @author Protofire * @dev ERC20 token used for wrapping tokens with the purpose of applying an authorization layer. * */ contract XToken is ERC20Pausable, AccessControl, Authorizable { using Address for address; /// @dev OperationsRegistry address IOperationsRegistry public operationsRegistry; /// @dev Know Your Asset string public kya; bytes32 public constant WRAPPER_ROLE = keccak256("MINTER_ROLE"); /** * @dev Emitted when `operationsRegistry` address is set. */ event KyaSet(string newKya); /** * @dev Emitted when `operationsRegistry` address is set. */ event OperationsRegistrySet(address indexed newOperationsRegistry); /** * @dev Sets the values for {name}, {symbol}, {decimals}, {kya}, {authorization} and {operationsRegistry}. * * Grants the contract deployer the default admin role. * */ constructor( string memory name_, string memory symbol_, uint8 decimals_, string memory kya_, address authorization_, address operationsRegistry_ ) ERC20(name_, symbol_) { require(decimals_ > 0, "decimals is 0"); require(authorization_ != address(0), "authorization is the zero address"); require(operationsRegistry_ != address(0), "operationsRegistry is the zero address"); _setupDecimals(decimals_); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setKya(kya_); _setAuthorization(authorization_); operationsRegistry = IOperationsRegistry(operationsRegistry_); } /** * @dev Throws if called by any account with no admin role. */ modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "must have default admin role"); _; } /** * @dev Throws if called by any account with no wrapper role. */ modifier onlyWrapper() { require(hasRole(WRAPPER_ROLE, _msgSender()), "must have wrapper role"); _; } /** * @dev Grants WRAPPER role to `account`. * * Requirements: * * - the caller must have ``role``'s admin role. */ function setWrapper(address account) external { grantRole(WRAPPER_ROLE, account); } /** * @dev Triggers stopped state. * * Requirements: * * - the caller must have ``role``'s admin role. * - the contract must not be paused. */ function pause() external onlyAdmin { _pause(); } /** * @dev Returns to normal state. * * Requirements: * * - the caller must have ``role``'s admin role. * - the contract must be paused. */ function unpause() external onlyAdmin { _unpause(); } /** * @dev Sets authorization. * * Requirements: * * - the caller must have ``role``'s admin role. */ function setAuthorization(address authorization_) external onlyAdmin { _setAuthorization(authorization_); } /** * @dev Sets operationsRegistry. * * Requirements: * * - the caller must have ``role``'s admin role. */ function setOperationsRegistry(address operationsRegistry_) external onlyAdmin { require(operationsRegistry_ != address(0), "operationsRegistry is the zero address"); emit OperationsRegistrySet(operationsRegistry_); operationsRegistry = IOperationsRegistry(operationsRegistry_); } /** * @dev Sets kya. * * Requirements: * * - the caller must have ``role``'s admin role. */ function setKya(string memory kya_) external onlyAdmin { _setKya(kya_); } /** * @dev Sets kya. * */ function _setKya(string memory kya_) internal { emit KyaSet(kya_); kya = kya_; } /** * @dev See {IERC20-transfer}. * * Adds the `amount` being tranfered to the `sender`'s accumulated in * {bytes4(keccak256("transfer(address,uint256)"))} operation. * This is not required by the EIP. * * Requirements: * * - the operation should be authorized. * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override onlyAuthorized returns (bool) { super.transfer(recipient, amount); operationsRegistry.addTrade(msg.sender, msg.sig, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Adds the `amount` being tranfered to the `msg.sender`'s accumulated in * {bytes4(keccak256("transfer(address,uint256)"))} operation. * This is not required by the EIP. * * Requirements: * * - the operation should be authorized. * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public override onlyAuthorized returns (bool) { super.transferFrom(sender, recipient, amount); operationsRegistry.addTrade(sender, this.transfer.selector, amount); return true; } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Adds the `amount` being minted to the `account`'s accumulated in * {bytes4(keccak256("mint(address,uint256)"))} operation. * This is not required by the EIP. * * Requirements: * * - the caller must have WRAPPER_ROLE. * - the operation should be authorized. * - `to` cannot be the zero address. */ function mint(address account, uint256 amount) external onlyWrapper onlyAuthorized { _mint(account, amount); operationsRegistry.addTrade(account, msg.sig, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Adds the `amount` being burned to the `account`'s accumulated in * {bytes4(keccak256("burnFrom(address,uint256)"))} operation. * This is not required by the EIP. * * Requirements: * * - the caller must have WRAPPER_ROLE. * - the operation should be authorized. * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function burnFrom(address account, uint256 amount) external onlyWrapper onlyAuthorized { _burn(account, amount); operationsRegistry.addTrade(account, msg.sig, amount); } } //SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "../interfaces/IXToken.sol"; /** * @title XTokenWrapper * @author Protofire * @dev Contract module which provides the functionalities for wrapping tokens into the corresponding * XToken and unwrapping XTokens giving back the corresponding Token. * */ contract XTokenWrapper is AccessControl, ERC1155Holder { using SafeERC20 for IERC20; address public constant ETH_TOKEN_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE"); /** * @dev Token to xToken registry. */ mapping(address => address) public tokenToXToken; /** * @dev xToken to Token registry. */ mapping(address => address) public xTokenToToken; /** * @dev Emitted when `asset` is disallowed. */ event RegisterToken(address indexed token, address indexed xToken); /** * @dev Grants the contract deployer the default admin role. * */ constructor() { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** * @dev Grants REGISTRY_MANAGER_ROLE to `_registryManager`. * * Requirements: * * - the caller must have ``role``'s admin role. */ function setRegistryManager(address _registryManager) external { grantRole(REGISTRY_MANAGER_ROLE, _registryManager); } /** * @dev Registers a new xToken associated to the ERC20 which it will be wrapping. * * Requirements: * * - the caller must have REGISTRY_MANAGER_ROLE. * - `_token` cannot be the zero address. * - `_xToken` cannot be the zero address. * * @param _token The address of the ERC20 being wrapped. * @param _xToken The address of xToken. */ function registerToken(address _token, address _xToken) external { require(hasRole(REGISTRY_MANAGER_ROLE, _msgSender()), "must have registry manager role"); require(_token != address(0), "token is the zero address"); require(_xToken != address(0), "xToken is the zero address"); emit RegisterToken(_token, _xToken); tokenToXToken[_token] = _xToken; xTokenToToken[_xToken] = _token; } /** * @dev Wraps `_token` into its associated xToken. * * It requires prior approval. * * Requirements: * * - `_token` should be registered. * * @param _token The address of the ERC20 being wrapped. * {ETH_TOKEN_ADDRESS} in case of wrapping ETH * @param _amount The amount to wrap. */ function wrap(address _token, uint256 _amount) external payable returns (bool) { address xTokenAddress = tokenToXToken[_token]; require(xTokenAddress != address(0), "token is not registered"); if (_token != ETH_TOKEN_ADDRESS) { IERC20(_token).safeTransferFrom(_msgSender(), address(this), _amount); } uint256 amount = _token != ETH_TOKEN_ADDRESS ? _amount : msg.value; require(amount > 0, "amount to wrap should be positive"); IXToken(xTokenAddress).mint(_msgSender(), amount); return true; } /** * @dev Unwraps `_xToken`. * * Requirements: * * - `_xToken` should be registered. * - `_amonut` should be gt 0. * * @param _xToken The address of the ERC20 being wrapped. * @param _amount The amount to unwrap. */ function unwrap(address _xToken, uint256 _amount) external returns (bool) { address tokenAddress = xTokenToToken[_xToken]; require(tokenAddress != address(0), "xToken is not registered"); require(_amount > 0, "amount to wrap should be positive"); IXToken(_xToken).burnFrom(_msgSender(), _amount); if (tokenAddress != ETH_TOKEN_ADDRESS) { IERC20(tokenAddress).safeTransfer(_msgSender(), _amount); } else { // solhint-disable-next-line (bool sent, ) = msg.sender.call{ value: _amount }(""); require(sent, "Failed to send Ether"); } return true; } } //SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /** * @title IEurPriceFeed * @author Protofire * @dev Interface to be implemented by any OperationRegistry logic contract use in the protocol. * */ interface IOperationsRegistry { /** * @dev Gets the balance traded by `_user` for an `_operation`. * * @param _user user's address * @param _operation msg.sig of the function considered an operation. */ function tradingBalanceByOperation(address _user, bytes4 _operation) external view returns (uint256); /** * @dev Sets `_eurPriceFeed` as the new EUR Price feed module. * * @param _eurPriceFeed The address of the new EUR Price feed module. */ function setEurPriceFeed(address _eurPriceFeed) external; /** * @dev Sets `_asset` as allowed for calling `addTrade`. * * @param _asset asset's address. */ function allowAsset(address _asset) external; /** * @dev Sets `_asset` as disallowed for calling `addTrade`. * * @param _asset asset's address. */ function disallowAsset(address _asset) external; /** * @dev Adds `_amount` converted to ERU to the balance traded by `_user` for an `_operation`. * * @param _user user's address * @param _operation msg.sig of the function considered an operation. * @param _amount msg.sig of the function considered an operation. */ function addTrade( address _user, bytes4 _operation, uint256 _amount ) external; } //SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /** * @title IEurPriceFeed * @author Protofire * @dev Interface to be implemented by any EurPriceFeed logic contract used in the protocol. * */ interface IEurPriceFeed { /** * @dev Gets the price a `_asset` in EUR. * * @param _asset address of asset to get the price. */ function getPrice(address _asset) external returns (uint256); /** * @dev Gets how many EUR represents the `_amount` of `_asset`. * * @param _asset address of asset to get the price. * @param _amount amount of `_asset`. */ function calculateAmount(address _asset, uint256 _amount) external view returns (uint256); /** * @dev Sets feed addresses for a given group of assets. * * @param _assets Array of assets addresses. * @param _feeds Array of asset/ETH price feeds. */ function setAssetsFeeds(address[] memory _assets, address[] memory _feeds) external; /** * @dev Sets feed addresse for a given asset. * * @param _asset Assets address. * @param _feed Asset/ETH price feed. */ function setAssetFeed(address _asset, address _feed) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./ERC20.sol"; import "../../utils/Pausable.sol"; /** * @dev ERC20 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 ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } //SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "@openzeppelin/contracts/GSN/Context.sol"; import "../interfaces/IAuthorization.sol"; /** * @title Authorizable * @author Protofire * @dev Contract module which provides an authorization mechanism. * * This module is used through inheritance. It will make available the modifier * `onlyAuthorized`, which can be applied to your functions to restrict their use. */ abstract contract Authorizable is Context { /// @dev Address of Authorization contract. IAuthorization public authorization; /** * @dev Emitted when `authorization` address is set. */ event AuthorizationSet(address indexed newAuthorization); /** * @dev Throws if called by any account which is not authorized to execute the transaction. */ modifier onlyAuthorized() { require( authorization.isAuthorized(_msgSender(), address(this), msg.sig, _msgData()), "Authorizable: not authorized" ); _; } /** * @dev Sets authorization. * */ function _setAuthorization(address authorization_) internal { require(authorization_ != address(0), "Authorizable: authorization is the zero address"); authorization = IAuthorization(authorization_); emit AuthorizationSet(authorization_); } } //SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /** * @title IAuthorization * @author Protofire * @dev Interface to be implemented by any Authorization logic contract. * */ interface IAuthorization { /** * @dev Sets `_permissions` as the new Permissions module. * * @param _permissions The address of the new Pemissions module. */ function setPermissions(address _permissions) external; /** * @dev Sets `_eurPriceFeed` as the new EUR Price feed module. * * @param _eurPriceFeed The address of the new EUR Price feed module. */ function setEurPriceFeed(address _eurPriceFeed) external; /** * @dev Sets `_operationsRegistry` as the new OperationsRegistry module. * * @param _operationsRegistry The address of the new OperationsRegistry module. */ function setOperationsRegistry(address _operationsRegistry) external; /** * @dev Sets `_tradingLimit` as the new traiding limit. * * @param _tradingLimit The value of the new traiding limit. */ function setTradingLimit(uint256 _tradingLimit) external; /** * @dev Sets `_poolFactory` as the new BFactory module. * * @param _poolFactory The address of the new Balance BFactory module. */ function setPoolFactory(address _poolFactory) external; /** * @dev Sets `_xTokenWrapper` as the new XTokenWrapper module. * * @param _xTokenWrapper The address of the new XTokenWrapper module. */ function setXTokenWrapper(address _xTokenWrapper) external; /** * @dev Determins if a user is allowed to perform an operation. * * @param _user msg.sender from function using Authorizable `onlyAuthorized` modifier. * @param _asset address of the contract using Authorizable `onlyAuthorized` modifier. * @param _operation msg.sig from function using Authorizable `onlyAuthorized` modifier. * @param _data msg.data from function using Authorizable `onlyAuthorized` modifier. * @return a boolean signaling the authorization. */ function isAuthorized( address _user, address _asset, bytes4 _operation, bytes calldata _data ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../GSN/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } //SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title IXToken * @author Protofire * @dev XToken Interface. * */ interface IXToken is IERC20 { /** * @dev Triggers stopped state. * */ function pause() external; /** * @dev Returns to normal state. */ function unpause() external; /** * @dev Sets authorization. * */ function setAuthorization(address authorization_) external; /** * @dev Sets operationsRegistry. * */ function setOperationsRegistry(address operationsRegistry_) external; /** * @dev Sets kya. * */ function setKya(string memory kya_) external; /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * */ function mint(address account, uint256 amount) external; /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * */ function burnFrom(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC1155Receiver.sol"; import "../../introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() { _registerInterface( ERC1155Receiver(0).onERC1155Received.selector ^ ERC1155Receiver(0).onERC1155BatchReceived.selector ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * _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.7.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ 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 () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev 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); }
Sets `_operationsRegistry` as the new Operations Registry module. Requirements: - the caller must be the owner. - `_operationsRegistry` should not be the zero address. _operationsRegistry The address of the new Operations Registry module./
function setOperationsRegistry(address _operationsRegistry) external onlyOwner { _setOperationsRegistry(_operationsRegistry); }
9,989,694
./full_match/97/0x6Af8af4A32f98836142C324B860C04da93A83587/sources/project:/contracts/Predix.sol
Set minBetAmount Callable by admin/
function setMinBetAmount(uint256 _minBetAmount) external whenPaused onlyAdmin { require(_minBetAmount != 0, 'Must be superior to 0'); minBetAmount = _minBetAmount; emit NewMinBetAmount(currentEpoch, minBetAmount); }
5,023,586
pragma solidity ^0.4.20; // Solidity compiler version supported by Azure Blockchain Workbench //--------------------------------------------- //Generated automatically for application 'RefrigeratedTransportation' by AppCodeGen utility //--------------------------------------------- import "./RefrigeratedTransportation.sol"; contract WorkbenchBase { event WorkbenchContractCreated(string applicationName, string workflowName, address originatingAddress); event WorkbenchContractUpdated(string applicationName, string workflowName, string action, address originatingAddress); string internal ApplicationName; string internal WorkflowName; function WorkbenchBase(string applicationName, string workflowName) public { ApplicationName = applicationName; WorkflowName = workflowName; } function ContractCreated() public { WorkbenchContractCreated(ApplicationName, WorkflowName, msg.sender); } function ContractUpdated(string action) public { WorkbenchContractUpdated(ApplicationName, WorkflowName, action, msg.sender); } } // // The wrapper contract RefrigeratedTransportation_AzureBlockchainWorkBench invokes functions from RefrigeratedTransportation. // The inheritance order of RefrigeratedTransportation_AzureBlockchainWorkBench ensures that functions and variables in RefrigeratedTransportation // are not shadowed by WorkbenchBase. // Any access of WorkbenchBase function or variables is qualified with WorkbenchBase // contract RefrigeratedTransportation_AzureBlockchainWorkBench is WorkbenchBase, RefrigeratedTransportation { // // Constructor // function RefrigeratedTransportation_AzureBlockchainWorkBench(address device, address supplyChainOwner, address supplyChainObserver, int256 minHumidity, int256 maxHumidity, int256 minTemperature, int256 maxTemperature) WorkbenchBase("RefrigeratedTransportation", "RefrigeratedTransportation") RefrigeratedTransportation(device, supplyChainOwner, supplyChainObserver, minHumidity, maxHumidity, minTemperature, maxTemperature) public { // Check postconditions and access control for constructor of RefrigeratedTransportation // Constructor should transition the state to StartState assert(State == StateType.Created); // Signals successful creation of contract RefrigeratedTransportation WorkbenchBase.ContractCreated(); } //////////////////////////////////////////// // Workbench Transitions // // Naming convention of transition functions: // Transition_<CurrentState>_Number_<TransitionNumberFromCurrentState>_<FunctionNameOnTransition> // Transition function arguments same as underlying function // ////////////////////////////////////////////// function Transition_Created_Number_0_TransferResponsibility (address newCounterparty) public { // Transition preconditions require(State == StateType.Created); require(msg.sender == InitiatingCounterparty); // Call overridden function TransferResponsibility in this contract TransferResponsibility(newCounterparty); // Transition postconditions assert(State == StateType.InTransit); } function Transition_Created_Number_1_IngestTelemetry (int256 humidity, int256 temperature, int256 timestamp) public { // Transition preconditions require(State == StateType.Created); require(msg.sender == Device); // Call overridden function IngestTelemetry in this contract IngestTelemetry(humidity, temperature, timestamp); // Transition postconditions assert(State == StateType.OutOfCompliance || State == StateType.Created); } function Transition_InTransit_Number_0_TransferResponsibility (address newCounterparty) public { // Transition preconditions require(State == StateType.InTransit); require(msg.sender == Counterparty); // Call overridden function TransferResponsibility in this contract TransferResponsibility(newCounterparty); // Transition postconditions assert(State == StateType.InTransit); } function Transition_InTransit_Number_1_IngestTelemetry (int256 humidity, int256 temperature, int256 timestamp) public { // Transition preconditions require(State == StateType.InTransit); require(msg.sender == Device); // Call overridden function IngestTelemetry in this contract IngestTelemetry(humidity, temperature, timestamp); // Transition postconditions assert(State == StateType.OutOfCompliance || State == StateType.InTransit); } function Transition_InTransit_Number_2_Complete () public { // Transition preconditions require(State == StateType.InTransit); require(msg.sender == Owner); // Call overridden function Complete in this contract Complete(); // Transition postconditions assert(State == StateType.Completed); } function IngestTelemetry(int256 humidity, int256 temperature, int256 timestamp) public { // Placeholder for function preconditions // Call function IngestTelemetry of RefrigeratedTransportation RefrigeratedTransportation.IngestTelemetry(humidity, temperature, timestamp); // Placeholder for function postconditions // Signals successful execution of function IngestTelemetry WorkbenchBase.ContractUpdated("IngestTelemetry"); } function TransferResponsibility(address newCounterparty) public { // Placeholder for function preconditions // Call function TransferResponsibility of RefrigeratedTransportation RefrigeratedTransportation.TransferResponsibility(newCounterparty); // Placeholder for function postconditions // Signals successful execution of function TransferResponsibility WorkbenchBase.ContractUpdated("TransferResponsibility"); } function Complete() public { // Placeholder for function preconditions // Call function Complete of RefrigeratedTransportation RefrigeratedTransportation.Complete(); // Placeholder for function postconditions // Signals successful execution of function Complete WorkbenchBase.ContractUpdated("Complete"); } }
Transition preconditions Call overridden function IngestTelemetry in this contract Transition postconditions
function Transition_Created_Number_1_IngestTelemetry (int256 humidity, int256 temperature, int256 timestamp) public { require(State == StateType.Created); require(msg.sender == Device); IngestTelemetry(humidity, temperature, timestamp); assert(State == StateType.OutOfCompliance || State == StateType.Created); }
5,533,605
/** *Submitted for verification at Etherscan.io on 2021-02-24 */ // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(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)); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view 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: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // File: contracts/SigToken.sol pragma solidity 0.6.12; // SushiToken with Governance. contract SigToken is ERC20, Ownable, ERC20Burnable { using SafeMath for uint256; // Bitcoin-like supply system: // 50 tokens per block (however it's Ethereum ~15 seconds block vs Bitcoin 10 minutes) // every 210,000 blocks is halving ~ 36 days 11 hours // 32 eras ~ 3 years 71 days 16 hours until complete mint // 21,000,000 is total supply // // i,e. if each block is about 15 seconds on average: // 40,320 blocks/week // 2,016,000 tokens/week before first halving // 10,500,000 total before first halving // uint256 constant MAX_MAIN_SUPPLY = 21_000_000 * 1e18; // the first week mint has x2 bonus = +2,016,000 // the second week mint has x1.5 bonus = +1,008,000 // uint256 constant BONUS_SUPPLY = 3_024_000 * 1e18; // so total max supply is 24,024,000 + 24 to init the uniswap pool uint256 constant MAX_TOTAL_SUPPLY = MAX_MAIN_SUPPLY + BONUS_SUPPLY; // The block number when SIG mining starts. uint256 public startBlock; uint256 constant DECIMALS_MUL = 1e18; uint256 constant BLOCKS_PER_WEEK = 40_320; uint256 constant HALVING_BLOCKS = 210_000; // uint265 constant INITIAL_BLOCK_REWARD = 50; function maxRewardMintAfterBlocks(uint256 t) public pure returns (uint256) { // the first week x2 mint if (t < BLOCKS_PER_WEEK) { return DECIMALS_MUL * 100 * t; } // second week x1.5 mint if (t < BLOCKS_PER_WEEK * 2) { return DECIMALS_MUL * (100 * BLOCKS_PER_WEEK + 75 * (t - BLOCKS_PER_WEEK)); } // after two weeks standard bitcoin issuance model https://en.bitcoin.it/wiki/Controlled_supply uint256 totalBonus = DECIMALS_MUL * (BLOCKS_PER_WEEK * 50 + BLOCKS_PER_WEEK * 25); assert(totalBonus >= 0); // how many halvings so far? uint256 era = t / HALVING_BLOCKS; assert(0 <= era); if (32 <= era) return MAX_TOTAL_SUPPLY; // total reward before current era (mul base reward 50) // sum : 1 + 1/2 + 1/4 … 1/2^n == 2 - 1/2^n == 1 - 1/1<<n == 1 - 1>>n // era reward per block (*1e18 *50) if (era == 0) { return totalBonus + DECIMALS_MUL* 50 * (t % HALVING_BLOCKS); } uint256 eraRewardPerBlock = (DECIMALS_MUL >> era); // assert(0 <= eraRewardPerBlock); uint256 bcReward = (DECIMALS_MUL + DECIMALS_MUL - (eraRewardPerBlock<<1) ) * 50 * HALVING_BLOCKS; // assert(0 <= bcReward); // reward in the last era which isn't over uint256 eraReward = eraRewardPerBlock * 50 * (t % HALVING_BLOCKS); // assert(0 <= eraReward); uint256 result = totalBonus + bcReward + eraReward; assert(0 <= result); return result; } constructor( uint256 _tinyMint ) public ERC20("xSigma", "SIG") { // dev needs a little of SIG tokens for uniswap SIG/ETH initialization _mint(msg.sender, _tinyMint); } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256(abi.encode(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), "SIG::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "SIG::delegateBySig: invalid nonce"); require(now <= expiry, "SIG::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, "SIG::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 SIGs (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, "SIG::_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; } } // File: contracts/SigMasterChef.sol /** * Fork of MasterChef https://etherscan.io/address/0xc2edad668740f1aa35e4d8f227fb8e17dca888cd#code */ // We intentional leave many variables with original sushi name // so you could save time at diff comparison while verifying the code pragma solidity 0.6.12; // former SushiToken interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to SushiSwap. // 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. // SushiSwap must mint EXACTLY the same amount of SushiSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once SUSHI is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract SigMasterChef 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 SUSHIs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSushiPerShare` (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. SUSHIs to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below. } // The SUSHI TOKEN! SigToken public sushi; // Dev address // here's it growthFund address public devaddr; // xSigma's sharedVault of investors address public sharedVault; // 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 SUSHI mining starts. uint256 public startBlock; // reward time factor, the bigger it's the longer it take to distribute reward uint256 public rewardTimeFactor = 4; uint256 constant MIN_REWARD_TIME_FACTOR = 1; uint256 constant MAX_REWARD_TIME_FACTOR = 40; 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); function totalRewardAtBlock(uint256 atBlock) public view returns (uint256) { if (atBlock < startBlock) return 0; uint256 t = (atBlock - startBlock).div(rewardTimeFactor); return sushi.maxRewardMintAfterBlocks(t); } constructor( SigToken _sushi, address _devaddr, address _sharedVault, uint256 _startBlock ) public { sushi = _sushi; devaddr = _devaddr; sharedVault = _sharedVault; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // use it very consciously function changeFactor(uint256 newFactor) public onlyOwner { require(MIN_REWARD_TIME_FACTOR <= newFactor && newFactor <= MAX_REWARD_TIME_FACTOR, "Invalid time factor"); massUpdatePools(); rewardTimeFactor = newFactor; } // 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, accSushiPerShare: 0 })); } // Update the given pool's SUSHI 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; } // View function to see pending SUSHIs on "frontend". function pendingSushi(uint256 _pid, address _user) external view returns (uint256) { // better name: currPoolInfo PoolInfo storage pool = poolInfo[_pid]; // better name: userOfCurrPool UserInfo storage user = userInfo[_pid][_user]; // Accumulated SUSHIs per share, times 1e12. uint256 accSushiPerShare = pool.accSushiPerShare; // better name: total_staked_LpTokens_of_currPool uint256 lpSupply = pool.lpToken.balanceOf(address(this)); // how many LP_tokens staked in the MasterChef // if currPool has any LpToken staked if (block.number > pool.lastRewardBlock && lpSupply != 0) { // 🐧 we use different reward function, so instead the original code: uint256 totalSushiReward = totalRewardAtBlock(block.number).sub(totalRewardAtBlock(pool.lastRewardBlock)); uint256 totalSushiRewardForPool = totalSushiReward.mul(pool.allocPoint).div(totalAllocPoint); accSushiPerShare = accSushiPerShare.add(totalSushiRewardForPool.mul(1e12).div(lpSupply)); } // return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt); // because original sushi contact mints 1 sushi to dev (in addition to 10 for LPs) // they implicitly diluted supply for ~9.09% as dev tax // to keep math clean, we explicitly we give LPs 60%, growthFund 10% // and 30% to xSigma investors and team so and we need to account for that uint256 userAmountBeforeTax = user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt); return userAmountBeforeTax.mul(60).div(100); } // copy of pendingSushi with explicit blockNumber for the frontend usage function pendingSushi2(uint256 _pid, address _user, uint256 blockNumber) external view returns (uint256) { require(blockNumber >= block.number, "require blockNumber >= block.number"); // better name: currPoolInfo PoolInfo storage pool = poolInfo[_pid]; // better name: userOfCurrPool UserInfo storage user = userInfo[_pid][_user]; // Accumulated SUSHIs per share, times 1e12. uint256 accSushiPerShare = pool.accSushiPerShare; // better name: total_staked_LpTokens_of_currPool uint256 lpSupply = pool.lpToken.balanceOf(address(this)); // how many LP_tokens staked in the MasterChef // if currPool has any LpToken staked if (blockNumber > pool.lastRewardBlock && lpSupply != 0) { uint256 totalSushiReward = totalRewardAtBlock(blockNumber).sub(totalRewardAtBlock(pool.lastRewardBlock)); uint256 totalSushiRewardForPool = totalSushiReward.mul(pool.allocPoint).div(totalAllocPoint); accSushiPerShare = accSushiPerShare.add(totalSushiRewardForPool.mul(1e12).div(lpSupply)); } uint256 userAmountBeforeTax = user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt); return userAmountBeforeTax.mul(60).div(100); } // 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; } // 🐧 we use different reward function, so instead the code above: uint256 totalSushiReward = totalRewardAtBlock(block.number) - totalRewardAtBlock(pool.lastRewardBlock); uint256 totalSushiRewardForPool = totalSushiReward.mul(pool.allocPoint).div(totalAllocPoint); // 60% for Lps sushi.mint(address(this), totalSushiRewardForPool.mul(60).div(100)); // 10% for growthFund sushi.mint(devaddr, totalSushiRewardForPool.div(10)); // 30% are minted/unlock directly from reward token sushi.mint(address(sharedVault), totalSushiRewardForPool.mul(30).div(100)); pool.accSushiPerShare = pool.accSushiPerShare.add(totalSushiRewardForPool.mul(1e12).div(lpSupply)); // pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for SUSHI 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.accSushiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSushiTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } // I could do this instead: user.rewardDebt += pending user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSushiTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // 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(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs. function safeSushiTransfer(address _to, uint256 _amount) internal { uint256 sushiBal = sushi.balanceOf(address(this)); if (_amount > sushiBal) { sushi.transfer(_to, sushiBal); } else { sushi.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
Deposit LP tokens to MasterChef for SUSHI 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.accSushiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSushiTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } emit Deposit(msg.sender, _pid, _amount); }
6,592,966
// SPDX-License-Identifier: MIT LICENSE /** . ' , ' , . ' . _________ _________ _________ _ /_|_____|_\ _ _ /_|_____|_\ _ _ /_|_____|_\ _ '. \ / .' '. \ / .' '. \ / .' '.\ /.' '.\ /.' '.\ /.' '.' '.' '.' ██████╗ ██╗ █████╗ ███╗ ███╗ ██████╗ ███╗ ██╗██████╗ ██╔══██╗██║██╔══██╗████╗ ████║██╔═══██╗████╗ ██║██╔══██╗ ██║ ██║██║███████║██╔████╔██║██║ ██║██╔██╗ ██║██║ ██║ ██║ ██║██║██╔══██║██║╚██╔╝██║██║ ██║██║╚██╗██║██║ ██║ ██████╔╝██║██║ ██║██║ ╚═╝ ██║╚██████╔╝██║ ╚████║██████╔╝ ╚═════╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═════╝ ██╗ ██╗███████╗██╗███████╗████████╗ ██║ ██║██╔════╝██║██╔════╝╚══██╔══╝ <'l __ ███████║█████╗ ██║███████╗ ██║ ll (___()'`; ██╔══██║██╔══╝ ██║╚════██║ ██║ llama~ /, /` ██║ ██║███████╗██║███████║ ██║ || || \\"--\\ ╚═╝ ╚═╝╚══════╝╚═╝╚══════╝ ╚═╝ '' '' */ pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./interfaces/IDiamondHeist.sol"; import "./interfaces/IDIAMOND.sol"; import "./interfaces/IStaking.sol"; import "./interfaces/ITraits.sol"; contract DiamondHeist is IDiamondHeist, ERC721Enumerable, Ownable, Pausable, ReentrancyGuard { // Tracks the last block that a caller has written to state. // Disallow some access to functions if they occur while a change is being written. mapping(address => uint256) private lastWrite; event LlamaMinted(uint256 indexed tokenId); event DogMinted(uint256 indexed tokenId); event LlamaBurned(uint256 indexed tokenId); event DogBurned(uint256 indexed tokenId); // max number of tokens that can be minted - 50000 in production uint256 public immutable MAX_TOKENS; // number of tokens that can be claimed for a fee - 20% of MAX_TOKENS uint256 public PAID_TOKENS; // number of tokens have been minted so far uint16 public minted; uint256 public MINT_PRICE = .06 ether; // whitelist, 10 mints, get a discount, 1 free uint16 public constant MAX_COMMUNITY_AMOUNT = 10; uint256 public constant COMMUNITY_SALE_MINT_PRICE = .04 ether; bytes32 public whitelistMerkleRoot; mapping(address => uint256) public claimed; // mapping from tokenId to a struct containing the token's traits mapping(uint256 => LlamaDog) public tokenTraits; // mapping from hashed(tokenTrait) to the tokenId it's associated with // used to ensure there are no duplicates mapping(uint256 => uint256) public existingCombinations; // list of probabilities for each trait type uint8[][14] public rarities; // list of aliases for Walker's Alias algorithm uint8[][14] public aliases; // reference to the Staking for choosing random Dog thieves IStaking public staking; // reference to $DIAMOND for burning on mint IDIAMOND public diamond; // reference to Traits ITraits public traits; /** * instantiates contract and rarity tables */ constructor(uint256 _maxTokens) ERC721("Diamond Heist", "DIAMONDHEIST") { MAX_TOKENS = _maxTokens; PAID_TOKENS = _maxTokens / 5; _pause(); // Llama/Body rarities[0] = [255, 61, 122, 30, 183, 224, 142, 30, 214, 173, 214, 122]; aliases[0] = [0, 0, 0, 7, 7, 0, 5, 6, 7, 8, 8, 9]; // Llama/Hat rarities[1] = [114, 254, 191, 152, 242, 152, 191, 229, 242, 114, 254, 76, 76, 203, 191]; aliases[1] = [6, 0, 6, 6, 1, 6, 4, 6, 6, 6, 8, 6, 8, 10, 13]; // Llama/Eye rarities[2] = [165, 66, 198, 255, 165, 211, 168, 165, 107, 99, 186, 175, 165]; aliases[2] = [6, 6, 6, 0, 6, 3, 5, 6, 6, 8, 8, 10, 11]; // Llama/Mouth rarities[3] = [140, 224, 28, 112, 112, 112, 254, 229, 160, 221, 140]; aliases[3] = [7, 7, 7, 7, 7, 8, 0, 6, 7, 8, 9]; // Llama/Clothes rarities[4] = [229, 254, 191, 216, 127, 152, 152, 165, 76, 114, 254, 152, 203, 76, 191]; aliases[4] = [1, 0, 1, 2, 3, 2, 2, 4, 2, 4, 7, 4, 10, 7, 12]; // Llama/Tail rarities[5] = [127, 255, 127, 127, 229, 102, 255, 255, 178, 51]; aliases[5] = [7, 0, 7, 7, 7, 7, 0, 0, 7, 8]; // Llama/alphaIndex rarities[6] = [255]; aliases[6] = [0]; // Dog/Body rarities[7] = [140, 254, 28, 224, 56, 181, 244, 84, 219, 28, 193]; aliases[7] = [1, 0, 1, 1, 5, 1, 5, 5, 6, 10, 8]; // Dog/Hat rarities[8] = [99, 165, 255, 178, 33, 232, 102, 33, 198, 232, 209, 198, 132]; aliases[8] = [6, 6, 0, 2, 6, 6, 3, 6, 6, 6, 6, 6, 10]; // Dog/Eye rarities[9] = [254, 30, 224, 153, 203, 30, 153, 214, 91, 91, 214, 153]; aliases[9] = [0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 4]; // Dog/Mouth rarities[10] = [254, 122, 61, 30, 61, 122, 142, 91, 91, 183, 244, 244]; aliases[10] = [0, 0, 0, 0, 8, 8, 0, 9, 6, 8, 9, 9]; // Dog/Clothes rarities[11] = [254, 107, 107, 35, 152, 198, 35, 107, 117, 132, 107, 107, 107, 107]; aliases[11] = [0, 4, 5, 5, 0, 4, 5, 5, 5, 8, 8, 8, 9, 9]; // Dog/Tail rarities[12] = [140, 254, 84, 84, 84, 203, 140, 196, 196, 140, 140]; aliases[12] = [1, 0, 5, 5, 5, 1, 5, 5, 5, 5, 5]; // Dog/alphaIndex rarities[13] = [254, 101, 153, 51]; aliases[13] = [0, 0, 0, 1]; } modifier requireContractsSet() { require( address(traits) != address(0) && address(staking) != address(0), "Contracts not set" ); _; } modifier disallowIfStateIsChanging() { // frens can always call whenever they want :) require( lastWrite[tx.origin] < block.number, "RESTRICTED" ); _; } function updateOriginAccess() external { lastWrite[tx.origin] = block.number; } function getTokenWriteBlock() external view override returns(uint256) { return lastWrite[tx.origin]; } function setContracts(ITraits _traits, IStaking _staking, IDIAMOND _diamond) external onlyOwner { traits = _traits; staking = _staking; diamond = _diamond; } function setWhiteListMerkleRoot(bytes32 _root) external onlyOwner { whitelistMerkleRoot = _root; } modifier isValidMerkleProof(bytes32[] memory proof) { require( MerkleProof.verify( proof, whitelistMerkleRoot, bytes32(uint256(uint160(_msgSender()))) ), "INVALID_MERKLE_PROOF" ); _; } /** EXTERNAL */ function communitySaleLeft(bytes32[] memory merkleProof) external view isValidMerkleProof(merkleProof) returns (uint256) { if (minted >= PAID_TOKENS) return 0; return MAX_COMMUNITY_AMOUNT - claimed[_msgSender()]; } /** * mint a token - 90% Llama, 10% Dog * The first 20% are free to claim, the remaining cost $DIAMOND */ function mintGame(uint256 amount, bool stake) internal whenNotPaused nonReentrant returns (uint16[] memory tokenIds) { require(tx.origin == _msgSender(), "ONLY_EOA"); require(minted + amount <= MAX_TOKENS, "MINT_ENDED"); require(amount > 0 && amount <= 15, "MINT_AMOUNT_INVALID"); uint256 totalDiamondCost = 0; tokenIds = new uint16[](amount); uint256 seed; for (uint256 i = 0; i < amount; i++) { minted++; seed = random(minted); generate(minted, seed); _safeMint(stake ? address(staking) : _msgSender(), minted); tokenIds[i] = minted; totalDiamondCost += mintCost(minted); } if (totalDiamondCost > 0) { diamond.burn(_msgSender(), totalDiamondCost); diamond.updateOriginAccess(); } if (stake) staking.addManyToStaking(_msgSender(), tokenIds); return tokenIds; } /** * mint a token - 90% Llama, 10% Dog * The first 20% are free to claim, the remaining cost $DIAMOND */ function mint(uint256 amount, bool stake) external payable { if (minted < PAID_TOKENS) { // we have to still pay in ETH, we can make a transaction that pays both in ETH and DIAMOND // check how many tokens should be paid in ETH, the DIAMOND will be burned in mintGame function require(msg.value == (amount > (PAID_TOKENS - minted) ? (PAID_TOKENS - minted) : amount) * MINT_PRICE, "MINT_PAID_PRICE_INVALID"); } else { require(msg.value == 0, "MINT_PAID_IN_DIAMONDS"); } mintGame(amount, stake); } function mintCommunitySale( bytes32[] memory merkleProof, uint256 amount, bool stake ) external payable isValidMerkleProof(merkleProof) { require( claimed[_msgSender()] + amount <= MAX_COMMUNITY_AMOUNT, "MINT_COMMUNITY_ENDED" ); require(minted + amount <= PAID_TOKENS, "MINT_ENDED"); require(msg.value == COMMUNITY_SALE_MINT_PRICE * (claimed[_msgSender()] == 0 ? amount - 1 : amount), "MINT_COMMUNITY_PRICE_INVALID"); claimed[_msgSender()] += amount; mintGame(amount, stake); } /** * 0 - 20% = eth * 20 - 40% = 200 DIAMONDS * 40 - 60% = 300 DIAMONDS * 60 - 80% = 400 DIAMONDS * 80 - 100% = 500 DIAMONDS * @param tokenId the ID to check the cost of to mint * @return the cost of the given token ID */ function mintCost(uint256 tokenId) public view returns (uint256) { if (tokenId <= PAID_TOKENS) return 0; // 1 / 5 = PAID_TOKENS if (tokenId <= (MAX_TOKENS * 2) / 5) return 200 ether; if (tokenId <= (MAX_TOKENS * 3) / 5) return 300 ether; if (tokenId <= (MAX_TOKENS * 4) / 5) return 400 ether; return 500 ether; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override(ERC721, IERC721) nonReentrant { // Hardcode the Staking's approval so that users don't have to waste gas approving if (_msgSender() != address(staking)) require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** INTERNAL */ /** * generates traits for a specific token, checking to make sure it's unique * @param tokenId the id of the token to generate traits for * @param seed a pseudorandom 256 bit number to derive traits from * @return t - a struct of traits for the given token ID */ function generate(uint256 tokenId, uint256 seed) internal returns (LlamaDog memory t) { t = selectTraits(tokenId, seed); if (existingCombinations[structToHash(t)] == 0) { tokenTraits[tokenId] = t; existingCombinations[structToHash(t)] = tokenId; if (t.isLlama) { emit LlamaMinted(tokenId); } else { emit DogMinted(tokenId); } return t; } return generate(tokenId, random(seed)); } /** * uses A.J. Walker's Alias algorithm for O(1) rarity table lookup * ensuring O(1) instead of O(n) reduces mint cost by more than 50% * probability & alias tables are generated off-chain beforehand * @param seed portion of the 256 bit seed to remove trait correlation * @param traitType the trait type to select a trait for * @return the ID of the randomly selected trait */ function selectTrait(uint16 seed, uint8 traitType) internal view returns (uint8) { uint8 trait = uint8(seed) % uint8(rarities[traitType].length); // If a selected random trait probability is selected (biased coin) return that trait if (seed >> 8 <= rarities[traitType][trait]) return trait; return aliases[traitType][trait]; } /** * selects the species and all of its traits based on the seed value * @param seed a pseudorandom 256 bit number to derive traits from * @return t - a struct of randomly selected traits */ function selectTraits(uint256 tokenId, uint256 seed) internal view returns (LlamaDog memory t) { // if tokenId < PAID_TOKENS, 2 in 10 chance of a dog, otherwise 1 in 10 chance of a dog t.isLlama = tokenId < PAID_TOKENS ? (seed & 0xFFFF) % 10 < 9 : (seed & 0xFFFF) % 10 < 1; uint8 shift = t.isLlama ? 0 : 7; // what happens here is that we check the 16 least signficial bits of the seed // and then remove them from the seed, so that the next 16 bits are used for the next trait // Before: EBD302F8B72AB0883F98D59C3BB7C25C61E30A77AB5F93924D234A620A32 // After: EBD302F8B72AB0883F98D59C3BB7C25C61E30A77AB5F93924D234A62 // trait 1: 0A32 -> 00001010 00110010 seed >>= 16; t.body = selectTrait(uint16(seed & 0xFFFF), 0 + shift); seed >>= 16; t.hat = selectTrait(uint16(seed & 0xFFFF), 1 + shift); seed >>= 16; t.eye = selectTrait(uint16(seed & 0xFFFF), 2 + shift); seed >>= 16; t.mouth = selectTrait(uint16(seed & 0xFFFF), 3 + shift); seed >>= 16; t.clothes = selectTrait(uint16(seed & 0xFFFF), 4 + shift); seed >>= 16; t.tail = selectTrait(uint16(seed & 0xFFFF), 5 + shift); seed >>= 16; t.alphaIndex = selectTrait(uint16(seed & 0xFFFF), 6 + shift); } /** * converts a struct to a 256 bit hash to check for uniqueness * @param s the struct to pack into a hash * @return the 256 bit hash of the struct */ function structToHash(LlamaDog memory s) internal pure returns (uint256) { return uint256( bytes32( abi.encodePacked( s.isLlama, s.body, s.hat, s.eye, s.mouth, s.clothes, s.tail, s.alphaIndex ) ) ); } /** * generates a pseudorandom number * @param seed a value ensure different outcomes for different sources in the same block * @return a pseudorandom value */ function random(uint256 seed) internal view returns (uint256) { return uint256( keccak256( abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, seed ) ) ); } /** READ */ function getTokenTraits(uint256 tokenId) external view override returns (LlamaDog memory) { require( _exists(tokenId), "ERC721Metadata: token traits query for nonexistent token" ); return tokenTraits[tokenId]; } function getPaidTokens() external view override returns (uint256) { return PAID_TOKENS; } /** * checks if a token is a Wizards * @param tokenId the ID of the token to check * @return wizard - whether or not a token is a Wizards */ function isLlama(uint256 tokenId) external view override disallowIfStateIsChanging returns (bool) { // Sneaky dragons will be slain if they try to peep this after mint. Nice try. IDiamondHeist.LlamaDog memory s = tokenTraits[tokenId]; return s.isLlama; } function getMaxTokens() external view override returns (uint256) { return MAX_TOKENS; } /** ADMIN */ /** * allows owner to withdraw funds from minting */ function withdraw() external onlyOwner { payable(owner()).transfer(address(this).balance); } /** * updates the number of tokens for sale */ function setPaidTokens(uint256 _paidTokens) external onlyOwner { PAID_TOKENS = _paidTokens; } /** * updates the mint price */ function setMintPrice(uint256 _mintPrice) external onlyOwner { MINT_PRICE = _mintPrice; } /** * enables owner to pause / unpause minting */ function setPaused(bool _paused) external onlyOwner { if (_paused) _pause(); else _unpause(); } /** RENDER */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); return traits.tokenURI(tokenId); } function realOwnerOf(uint256 tokenId) public view returns (address owner) { if (ownerOf(tokenId) != address(staking)) { return owner; } return staking.realOwnerOf(tokenId); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; interface IDiamondHeist is IERC721Enumerable { // struct to store each token's traits struct LlamaDog { bool isLlama; uint8 body; uint8 hat; uint8 eye; uint8 mouth; uint8 clothes; uint8 tail; uint8 alphaIndex; } function getMaxTokens() external view returns (uint256); function getPaidTokens() external view returns (uint256); function getTokenWriteBlock() external view returns(uint256); function getTokenTraits(uint256 tokenId) external view returns (LlamaDog memory); function isLlama(uint256 tokenId) external view returns(bool); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IDIAMOND { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; function updateOriginAccess() external; function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IStaking { function addManyToStaking(address account, uint16[] calldata tokenIds) external; function realOwnerOf(uint256 tokenId) external view returns (address); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface ITraits { function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
updates the mint price/
function setMintPrice(uint256 _mintPrice) external onlyOwner { MINT_PRICE = _mintPrice; }
10,060,812
/** * SPDX-License-Identifier: MIT * * Copyright (c) 2020 Coinbase, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { EnumerableSet } from "@openzeppelin/contracts/utils/EnumerableSet.sol"; import { EnumerableSetExtra } from "./util/EnumerableSetExtra.sol"; import { Administrable } from "./util/Administrable.sol"; /** * @title Multi-sig Admin Contract * @notice Used to add configurable multi-sig approval process to existing * smart contracts. */ contract MultiSigAdmin is Administrable { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; using EnumerableSetExtra for EnumerableSet.AddressSet; using EnumerableSetExtra for EnumerableSet.UintSet; struct ContractCallType { Configuration config; // IDs of open proposals for this type of contract call EnumerableSet.UintSet openProposals; // Number of open proposals of each approver mapping(address => uint256) numOpenProposals; } struct Configuration { // Minimum number of approvals required to execute a proposal uint256 minApprovals; // Maximum number of open proposals per approver - if exceeded, the // approver has to close or execute an existing open proposal to be able // to create another proposal. uint256 maxOpenProposals; // Addresses of qualified approvers - accounts that can propose, // approve, and execute proposals EnumerableSet.AddressSet approvers; } enum ProposalState { NotExist, // Default state (0) for nonexistent proposals Open, // Proposal can receive approvals OpenAndExecutable, // Proposal has received required number of approvals Closed, // Proposal is closed Executed // Proposal has been executed } struct Proposal { ProposalState state; address proposer; address targetContract; bytes4 selector; bytes argumentData; // Addresses of accounts that have submitted approvals EnumerableSet.AddressSet approvals; } /** * @dev Use this selector to call the target contract without any calldata. * It can be used to call receive Ether function (receive()). */ bytes4 public constant SELECTOR_NONE = 0x00000000; /** * @dev Preconfigured contract call types: * Contract address => Function selector => ContractCallType */ mapping(address => mapping(bytes4 => ContractCallType)) private _types; /** * @dev Proposals: Proposal ID => Proposal */ mapping(uint256 => Proposal) private _proposals; /** * @dev Next proposal ID */ uint256 private _nextProposalId; event ConfigurationChanged( address indexed targetContract, bytes4 indexed selector, address indexed admin ); event ConfigurationRemoved( address indexed targetContract, bytes4 indexed selector, address indexed admin ); event ProposalCreated(uint256 indexed id, address indexed proposer); event ProposalClosed(uint256 indexed id, address indexed closer); event ProposalApprovalSubmitted( uint256 indexed id, address indexed approver, uint256 numApprovals, uint256 minApprovals ); event ProposalApprovalRescinded( uint256 indexed id, address indexed approver, uint256 numApprovals, uint256 minApprovals ); event ProposalExecuted(uint256 indexed id, address indexed executor); /** * @notice Ensure that the configuration for the given type of contract call * is present * @param targetContract Address of the contract * @param selector Selector of the function in the contract */ modifier configurationExists(address targetContract, bytes4 selector) { require( _types[targetContract][selector].config.minApprovals > 0, "MultiSigAdmin: configuration does not exist" ); _; } /** * @notice Ensure that the caller is an approver for the given type of * contract call * @param targetContract Address of the contract * @param selector Selector of the function in the contract */ modifier onlyApprover(address targetContract, bytes4 selector) { require( _types[targetContract][selector].config.approvers.contains( msg.sender ), "MultiSigAdmin: caller is not an approver" ); _; } /** * @notice Ensure that the caller is the proposer of a given proposal * @param proposalId Proposal ID */ modifier onlyProposer(uint256 proposalId) { require( _proposals[proposalId].proposer == msg.sender, "MultiSigAdmin: caller is not the proposer" ); _; } /** * @notice Ensure that the proposal is open * @param proposalId Proposal ID */ modifier proposalIsOpen(uint256 proposalId) { ProposalState state = _proposals[proposalId].state; require( state == ProposalState.Open || state == ProposalState.OpenAndExecutable, "MultiSigAdmin: proposal is not open" ); _; } /** * @notice Ensure that the caller can approve a given proposal * @param proposalId Proposal ID */ modifier onlyApproverForProposal(uint256 proposalId) { Proposal storage proposal = _proposals[proposalId]; require( _types[proposal.targetContract][proposal.selector] .config .approvers .contains(msg.sender), "MultiSigAdmin: caller is not an approver" ); _; } /** * @notice Configure requirements for a type of contract call * @dev minApprovals must be greater than zero. If updating an existing * configuration, this function will close all affected open proposals. * This function will revert if any of the affected proposals is executable. * To close all affected executable proposals before calling this function, * call removeConfiguration with closeExecutable = true. * @param targetContract Address of the contract * @param selector Selector of the function in the contract * @param minApprovals Minimum number of approvals required * @param maxOpenProposals Maximum number of open proposals per approver * @param approvers List of approvers' addresses */ function configure( address targetContract, bytes4 selector, uint256 minApprovals, uint256 maxOpenProposals, address[] calldata approvers ) external onlyAdmin { require( targetContract != address(0), "MultiSigAdmin: targetContract is the zero address" ); require(minApprovals > 0, "MultiSigAdmin: minApprovals is zero"); require( maxOpenProposals > 0, "MultiSigAdmin: maxOpenProposals is zero" ); ContractCallType storage callType = _types[targetContract][selector]; Configuration storage config = callType.config; // Set approvers config.approvers.clear(); for (uint256 i = 0; i < approvers.length; i++) { config.approvers.add(approvers[i]); } require( config.approvers.length() >= minApprovals, "MultiSigAdmin: approvers fewer than minApprovals" ); // Set minApprovals and maxOpenProposals config.minApprovals = minApprovals; config.maxOpenProposals = maxOpenProposals; // Close existing open proposals _closeOpenProposals(callType, false); emit ConfigurationChanged(targetContract, selector, msg.sender); } /** * @notice Remove the configuration for a given type of contract call * @dev This closes all affected proposals. * @param targetContract Address of the contract * @param selector Selector of the function in the contract * @param closeExecutable If false, this function will revert if any of * the affected open proposals to be closed is executable */ function removeConfiguration( address targetContract, bytes4 selector, bool closeExecutable ) external onlyAdmin configurationExists(targetContract, selector) { ContractCallType storage callType = _types[targetContract][selector]; Configuration storage config = callType.config; // Reset minApprovals, maxOpenProposals, and approvers config.minApprovals = 0; config.maxOpenProposals = 0; config.approvers.clear(); // Close existing open proposals _closeOpenProposals(callType, closeExecutable); emit ConfigurationRemoved(targetContract, selector, msg.sender); } /** * @notice Propose a contract call * @dev Only approvers for a given type of contract call are able to * propose. Emits the proposal ID in ProposalCreated event. * @param targetContract Address of the contract * @param selector Selector of the function in the contract * @param argumentData ABI-encoded argument data * @return Proposal ID */ function propose( address targetContract, bytes4 selector, bytes calldata argumentData ) external configurationExists(targetContract, selector) onlyApprover(targetContract, selector) returns (uint256) { return _propose(msg.sender, targetContract, selector, argumentData); } /** * @notice Close a proposal without executing * @dev This can only be called by the proposer. * @param proposalId Proposal */ function closeProposal(uint256 proposalId) external proposalIsOpen(proposalId) onlyProposer(proposalId) { _closeProposal(proposalId, msg.sender); } /** * @notice Submit an approval for a proposal * @dev Only the approvers for the type of contract call specified in the * proposal are able to submit approvals. * @param proposalId Proposal ID */ function approve(uint256 proposalId) external proposalIsOpen(proposalId) onlyApproverForProposal(proposalId) { _approve(msg.sender, proposalId); } /** * @notice Rescind a previously submitted approval * @dev Approvals can only be rescinded while the proposal is still open. * @param proposalId Proposal ID */ function rescindApproval(uint256 proposalId) external proposalIsOpen(proposalId) onlyApproverForProposal(proposalId) { Proposal storage proposal = _proposals[proposalId]; EnumerableSet.AddressSet storage approvals = proposal.approvals; require( approvals.contains(msg.sender), "MultiSigAdmin: caller has not approved the proposal" ); approvals.remove(msg.sender); uint256 numApprovals = proposal.approvals.length(); uint256 minApprovals = _types[proposal.targetContract][proposal .selector] .config .minApprovals; // if it was marked as executable, but no longer meets the required // number of approvals, mark it as just open but not executable if ( proposal.state == ProposalState.OpenAndExecutable && numApprovals < minApprovals ) { proposal.state = ProposalState.Open; } emit ProposalApprovalRescinded( proposalId, msg.sender, numApprovals, minApprovals ); } /** * @notice Execute an approved proposal * @dev Required number of approvals must have been met; only the approvers * for a given type of contract call proposed are able to execute. * @param proposalId Proposal ID * @return Return data from the contract call */ function execute(uint256 proposalId) external payable proposalIsOpen(proposalId) onlyApproverForProposal(proposalId) returns (bytes memory) { return _execute(msg.sender, proposalId); } /** * @notice A convenience function to cast the final approval required and * execute the contract call. Same as doing approve() followed by execute(). * @param proposalId Proposal ID * @return Return data from the contract call */ function approveAndExecute(uint256 proposalId) external payable proposalIsOpen(proposalId) onlyApproverForProposal(proposalId) returns (bytes memory) { _approve(msg.sender, proposalId); return _execute(msg.sender, proposalId); } /** * @notice A convenience function to create a proposal and execute * immediately. Same as doing propose() followed by approve() and execute(). * @dev This works only if the number of approvals required is one (1). * @param targetContract Address of the contract * @param selector Selector of the function in the contract * @param argumentData ABI-encoded argument data * @return Return data from the contract call */ function proposeAndExecute( address targetContract, bytes4 selector, bytes calldata argumentData ) external payable configurationExists(targetContract, selector) onlyApprover(targetContract, selector) returns (bytes memory) { uint256 proposalId = _propose( msg.sender, targetContract, selector, argumentData ); _approve(msg.sender, proposalId); return _execute(msg.sender, proposalId); } /** * @notice Minimum number of approvals required for a given type of contract * call * @param targetContract Address of the contract * @param selector Selector of the function in the contract * @return Minimum number of approvals required for execution */ function getMinApprovals(address targetContract, bytes4 selector) external view returns (uint256) { return _types[targetContract][selector].config.minApprovals; } /** * @notice Maximum number of open proposals per approver for a given type of * contract call * @param targetContract Address of the contract * @param selector Selector of the function in the contract * @return Minimum number of approvals required for execution */ function getMaxOpenProposals(address targetContract, bytes4 selector) external view returns (uint256) { return _types[targetContract][selector].config.maxOpenProposals; } /** * @notice List of approvers for a given type of contract call * @param targetContract Address of the contract * @param selector Selector of the function in the contract * @return List of approvers' addresses */ function getApprovers(address targetContract, bytes4 selector) external view returns (address[] memory) { return _types[targetContract][selector].config.approvers.elements(); } /** * @notice Whether a given account is configured to be able to approve a * given type of contract call * @param targetContract Address of the contract * @param selector Selector of the function in the contract * @param account Address of the account to check * @return True if an approver */ function isApprover( address targetContract, bytes4 selector, address account ) external view returns (bool) { return _types[targetContract][selector].config.approvers.contains(account); } /** * @notice List of IDs of open proposals for a given type of contract call * @param targetContract Address of the contract * @param selector Selector of the function in the contract * @return List of IDs of open proposals */ function getOpenProposals(address targetContract, bytes4 selector) external view returns (uint256[] memory) { return _types[targetContract][selector].openProposals.elements(); } /** * @notice List of IDs of executable proposals (i.e. open proposals that * have received the required number of approvals) for a given type of * contract call * @dev Avoid calling this function from another contract, and only use it * outside of a tranasction (eth_call), as this function is inefficient in * terms of gas usage due to the limitations of dynamic memory arrays. * @param targetContract Address of the contract * @param selector Selector of the function in the contract * @return List of IDs of executable proposals */ function getExecutableProposals(address targetContract, bytes4 selector) external view returns (uint256[] memory) { uint256[] memory openProposals = _types[targetContract][selector] .openProposals .elements(); uint256[] memory executableProposals = new uint256[]( openProposals.length ); uint256 numExecutableProposals = 0; // Iterate through open proposals and find executable proposals for (uint256 i = 0; i < openProposals.length; i++) { uint256 proposalId = openProposals[i]; if ( _proposals[proposalId].state == ProposalState.OpenAndExecutable ) { executableProposals[numExecutableProposals++] = proposalId; } } // Now that the number of executable proposals is known, create a // an array of the exact size needed and copy contents uint256[] memory executableProposalsResized = new uint256[]( numExecutableProposals ); for (uint256 i = 0; i < numExecutableProposals; i++) { executableProposalsResized[i] = executableProposals[i]; } return executableProposalsResized; } /** * @notice Number of approvals received for a given proposal * @param proposalId Proposal ID * @return Number of approvals */ function getNumApprovals(uint256 proposalId) external view returns (uint256) { return _proposals[proposalId].approvals.length(); } /** * @notice List of approvers that have approved a given proposal * @dev Approvers who have rescinded their approvals are not included. * @param proposalId Proposal ID * @return List of approvers' addresses */ function getApprovals(uint256 proposalId) external view returns (address[] memory) { return _proposals[proposalId].approvals.elements(); } /** * @notice Whether a proposal has received required number of approvals * @param proposalId Proposal ID * @return True if executable */ function isExecutable(uint256 proposalId) external view returns (bool) { return _proposals[proposalId].state == ProposalState.OpenAndExecutable; } /** * @notice Whether an approver has already approved a proposal * @dev False if the approval was rescinded. * @param proposalId Proposal ID * @param approver Approver's address * @return True if approved */ function hasApproved(uint256 proposalId, address approver) external view returns (bool) { return _proposals[proposalId].approvals.contains(approver); } /** * @notice State of a given proposal * @param proposalId Proposal ID * @return Proposal state */ function getProposalState(uint256 proposalId) external view returns (ProposalState) { return _proposals[proposalId].state; } /** * @notice Proposer of a given proposal * @param proposalId Proposal ID * @return Proposer's address */ function getProposer(uint256 proposalId) external view returns (address) { return _proposals[proposalId].proposer; } /** * @notice Target contract address of a given proposal * @param proposalId Proposal ID * @return Contract address */ function getTargetContract(uint256 proposalId) external view returns (address) { return _proposals[proposalId].targetContract; } /** * @notice Target function selector of a given proposal * @param proposalId Proposal ID * @return Function selector */ function getSelector(uint256 proposalId) external view returns (bytes4) { return _proposals[proposalId].selector; } /** * @notice Call argument data of a given proposal * @param proposalId Proposal ID * @return Argument data */ function getArgumentData(uint256 proposalId) external view returns (bytes memory) { return _proposals[proposalId].argumentData; } /** * @notice Private function to close a proposal * @param proposalId Proposal ID * @param closer Closer's address */ function _closeProposal(uint256 proposalId, address closer) private { Proposal storage proposal = _proposals[proposalId]; // Update state to Closed proposal.state = ProposalState.Closed; ContractCallType storage callType = _types[proposal .targetContract][proposal.selector]; // Remove proposal from openProposals callType.openProposals.remove(proposalId); // Decrement open proposal count for the proposer address proposer = proposal.proposer; callType.numOpenProposals[proposer] = callType .numOpenProposals[proposer] .sub(1); emit ProposalClosed(proposalId, closer); } /** * @notice Private function to close open proposals * @param callType Contract call type * @param closeExecutable If false, this function will revert if any of * the open proposals to be closed is executable */ function _closeOpenProposals( ContractCallType storage callType, bool closeExecutable ) private { uint256 openProposalCount = callType.openProposals.length(); for (uint256 i = 0; i < openProposalCount; i++) { // Keep removing the first open proposal, because _clearProposal // removes the closed proposal from the list uint256 proposalId = callType.openProposals.at(0); if (!closeExecutable) { require( _proposals[proposalId].state != ProposalState.OpenAndExecutable, "MultiSigAdmin: an executable proposal exists" ); } _closeProposal(proposalId, msg.sender); } } /** * @notice Private function to create a new proposal * @param proposer Proposer's address * @param targetContract Address of the contract * @param selector Selector of the function in the contract * @param argumentData ABI-encoded argument data * @return Proposal ID */ function _propose( address proposer, address targetContract, bytes4 selector, bytes memory argumentData ) private returns (uint256) { ContractCallType storage callType = _types[targetContract][selector]; uint256 numOpenProposals = callType.numOpenProposals[proposer]; require( numOpenProposals < callType.config.maxOpenProposals, "MultiSigAdmin: Maximum open proposal limit reached" ); uint256 proposalId = _nextProposalId; _nextProposalId = _nextProposalId.add(1); Proposal storage proposal = _proposals[proposalId]; proposal.state = ProposalState.Open; proposal.proposer = proposer; proposal.targetContract = targetContract; proposal.selector = selector; proposal.argumentData = argumentData; // Increment open proposal count for the proposer callType.numOpenProposals[proposer] = numOpenProposals.add(1); // Add proposal ID to the set of open proposals callType.openProposals.add(proposalId); emit ProposalCreated(proposalId, proposer); return proposalId; } /** * @notice Private function to add an approval to a proposal * @param approver Approver's address * @param proposalId Proposal ID */ function _approve(address approver, uint256 proposalId) private { Proposal storage proposal = _proposals[proposalId]; EnumerableSet.AddressSet storage approvals = proposal.approvals; require( !approvals.contains(approver), "MultiSigAdmin: caller has already approved the proposal" ); approvals.add(approver); uint256 numApprovals = proposal.approvals.length(); uint256 minApprovals = _types[proposal.targetContract][proposal .selector] .config .minApprovals; // if the required number of approvals is met, mark it as executable if (numApprovals >= minApprovals) { proposal.state = ProposalState.OpenAndExecutable; } emit ProposalApprovalSubmitted( proposalId, approver, numApprovals, minApprovals ); } /** * @notice Private function to execute a proposal * @dev Before calling this function, be sure that the state of the proposal * is Open. * @param executor Executor's address * @param proposalId Proposal ID */ function _execute(address executor, uint256 proposalId) private returns (bytes memory) { Proposal storage proposal = _proposals[proposalId]; require( proposal.state == ProposalState.OpenAndExecutable, "MultiSigAdmin: proposal needs more approvals" ); address targetContract = proposal.targetContract; require( Address.isContract(targetContract), "MultiSigAdmin: targetContract is not a contract" ); // Mark the proposal as executed proposal.state = ProposalState.Executed; bytes4 selector = proposal.selector; ContractCallType storage callType = _types[targetContract][selector]; // Remove the proposal ID from openProposals callType.openProposals.remove(proposalId); // Decrement open proposal count for the proposer address proposer = proposal.proposer; callType.numOpenProposals[proposer] = callType .numOpenProposals[proposer] .sub(1); emit ProposalExecuted(proposalId, executor); bool success; bytes memory returnData; if (selector == SELECTOR_NONE) { (success, returnData) = targetContract.call{ value: msg.value }(""); } else { (success, returnData) = targetContract.call{ value: msg.value }( abi.encodePacked(selector, proposal.argumentData) ); } if (!success) { string memory err = "MultiSigAdmin: call failed"; // Return data will be at least 100 bytes if it contains the reason // string: Error(string) selector[4] + string offset[32] + string // length[32] + string data[32] = 100 if (returnData.length < 100) { revert(err); } // If the reason string exists, extract it, and bubble it up string memory reason; assembly { // Skip over the bytes length[32] + Error(string) selector[4] + // string offset[32] = 68 (0x44) reason := add(returnData, 0x44) } revert(string(abi.encodePacked(err, ": ", reason))); } return returnData; } }
Maximum number of open proposals per approver for a given type of contract call targetContract Address of the contract selector Selector of the function in the contract return Minimum number of approvals required for execution/
function getMaxOpenProposals(address targetContract, bytes4 selector) external view returns (uint256) { return _types[targetContract][selector].config.maxOpenProposals; }
925,747
./partial_match/56/0x628449b26804B9AFb704eF3317C43841c2955996/sources/TokenGeyser.sol
1. User data Fake redeem from most recent stake and go backwards in time to compute all pending rewards as if unstaking while (sharesLeftToBurn > 0) { fully redeem a past stake
function pendingUserReward(address user) public view returns (uint256) { Stake[] storage accountStakes = _userStakes[user]; uint256 stakingSharesToBurn = totalStakingShares.mul(totalStakedFor(user)).div(totalStaked()); uint256 stakingShareSecondsToBurn = 0; uint256 sharesLeftToBurn = stakingSharesToBurn; uint256 rewardAmount = 0; uint256 length = accountStakes.length; for (uint256 k = 0; k < length; k++) { Stake storage lastStake = accountStakes[accountStakes.length - 1 - k]; uint256 stakeTimeSec = now.sub(lastStake.timestampSec); uint256 newStakingShareSecondsToBurn = 0; newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSec); rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec); stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn); sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.stakingShares); } return rewardAmount; }
11,196,806
./full_match/137/0xDbF5E966E8A912b4FcAaCc28beCE5761c3E61dF9/sources/contracts/MultiChainERC721.sol
set the token to be on another chain - only a token owner can do this we also keep a record of where it's been put - and potentuall an alternative tokenid do the transfer
function moveOffChain(uint256 _tokenId, uint _chainId, string memory _altTokenId) virtual public { require(_isApprovedOrOwner(_msgSender(), _tokenId), "ERC721: transfer caller is not owner nor approved"); address owner = ownerOf(_tokenId); _tokenChains[_tokenId].chainId = _chainId; _tokenChains[_tokenId].altTokenId = _altTokenId; _transfer(owner, tokenHolderAddress, _tokenId ); }
4,777,344
./partial_match/43113/0x26639692ec4bFB0767f505BbEbC871b84C3D4bbE/sources/contracts/SingleStakeFactory_flattened.sol
Override _beforeStake() hook to ensure staking is only possible when rewards are emitting/
function _beforeStake( address _account, uint256 _amount ) internal virtual override whenEmitting returns (uint256) { return super._beforeStake(_account, _amount); }
16,909,107
./partial_match/42/0x4E951A6FB550c0eab2615619253900B2Dbc5F363/sources/STYK_I.sol
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.
interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function getRoundData(uint80 _roundId) external view returns ( uint256 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint256 answeredInRound ); function latestRoundData() external view returns ( uint256 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint256 answeredInRound ); }
3,304,621
pragma solidity ^0.4.21; /** * @title Maths * A library to make working with numbers in Solidity hurt your brain less. */ library Maths { /** * @dev Adds two addends together, returns the sum * @param addendA the first addend * @param addendB the second addend * @return sum the sum of the equation (e.g. addendA + addendB) */ function plus( uint256 addendA, uint256 addendB ) public pure returns (uint256 sum) { sum = addendA + addendB; } /** * @dev Subtracts the minuend from the subtrahend, returns the difference * @param minuend the minuend * @param subtrahend the subtrahend * @return difference the difference (e.g. minuend - subtrahend) */ function minus( uint256 minuend, uint256 subtrahend ) public pure returns (uint256 difference) { assert(minuend >= subtrahend); difference = minuend - subtrahend; } /** * @dev Multiplies two factors, returns the product * @param factorA the first factor * @param factorB the second factor * @return product the product of the equation (e.g. factorA * factorB) */ function mul( uint256 factorA, uint256 factorB ) public pure returns (uint256 product) { if (factorA == 0 || factorB == 0) return 0; product = factorA * factorB; assert(product / factorA == factorB); } /** * @dev Multiplies two factors, returns the product * @param factorA the first factor * @param factorB the second factor * @return product the product of the equation (e.g. factorA * factorB) */ function times( uint256 factorA, uint256 factorB ) public pure returns (uint256 product) { return mul(factorA, factorB); } /** * @dev Divides the dividend by divisor, returns the truncated quotient * @param dividend the dividend * @param divisor the divisor * @return quotient the quotient of the equation (e.g. dividend / divisor) */ function div( uint256 dividend, uint256 divisor ) public pure returns (uint256 quotient) { quotient = dividend / divisor; assert(quotient * divisor == dividend); } /** * @dev Divides the dividend by divisor, returns the truncated quotient * @param dividend the dividend * @param divisor the divisor * @return quotient the quotient of the equation (e.g. dividend / divisor) */ function dividedBy( uint256 dividend, uint256 divisor ) public pure returns (uint256 quotient) { return div(dividend, divisor); } /** * @dev Divides the dividend by divisor, returns the quotient and remainder * @param dividend the dividend * @param divisor the divisor * @return quotient the quotient of the equation (e.g. dividend / divisor) * @return remainder the remainder of the equation (e.g. dividend % divisor) */ function divideSafely( uint256 dividend, uint256 divisor ) public pure returns (uint256 quotient, uint256 remainder) { quotient = div(dividend, divisor); remainder = dividend % divisor; } /** * @dev Returns the lesser of two values. * @param a the first value * @param b the second value * @return result the lesser of the two values */ function min( uint256 a, uint256 b ) public pure returns (uint256 result) { result = a <= b ? a : b; } /** * @dev Returns the greater of two values. * @param a the first value * @param b the second value * @return result the greater of the two values */ function max( uint256 a, uint256 b ) public pure returns (uint256 result) { result = a >= b ? a : b; } /** * @dev Determines whether a value is less than another. * @param a the first value * @param b the second value * @return isTrue whether a is less than b */ function isLessThan(uint256 a, uint256 b) public pure returns (bool isTrue) { isTrue = a < b; } /** * @dev Determines whether a value is equal to or less than another. * @param a the first value * @param b the second value * @return isTrue whether a is less than or equal to b */ function isAtMost(uint256 a, uint256 b) public pure returns (bool isTrue) { isTrue = a <= b; } /** * @dev Determines whether a value is greater than another. * @param a the first value * @param b the second value * @return isTrue whether a is greater than b */ function isGreaterThan(uint256 a, uint256 b) public pure returns (bool isTrue) { isTrue = a > b; } /** * @dev Determines whether a value is equal to or greater than another. * @param a the first value * @param b the second value * @return isTrue whether a is less than b */ function isAtLeast(uint256 a, uint256 b) public pure returns (bool isTrue) { isTrue = a >= b; } }
Multiplies two factors, returns the product factorA the first factor factorB the second factor return product the product of the equation (e.g. factorA factorB)/
function mul( uint256 factorA, uint256 factorB ) public pure returns (uint256 product) { if (factorA == 0 || factorB == 0) return 0; product = factorA * factorB; assert(product / factorA == factorB); }
482,029
// Upgraded Date: 01-28-2022 // Commits: https://github.com/Sperax/USDs/commit/177c1f24c9de18940ec0b5ddce996f87b2343b8d#diff-b094db7ce2f99cbcbde7ec178a6754bac666e2192f076807acbd70d49ddd0559 // https://github.com/Sperax/USDs/commit/7d5d63260f7b0088f4aac60c690bc4a1b9265f2f#diff-b094db7ce2f99cbcbde7ec178a6754bac666e2192f076807acbd70d49ddd0559 // https://github.com/Sperax/USDs/commit/6ebcb7bb4ce895474953a98a2e518db31ed649b5#diff-b094db7ce2f99cbcbde7ec178a6754bac666e2192f076807acbd70d49ddd0559 // Changes: 1. now the contract collects yield in the token with higher return, // instead of in the original invested token // 2. optimized token flow of withdrawal // Implementation Contract Address: // 1. USDC strategy: 0x5D2A5d67fD5C970A4A4Ab60bA6cF9b438f869fb9 // 2. USDT strategy: 0xa2255E689D1E4cC82a7cDC1F01CAe603C93Fd92D // SPDX-License-Identifier: MIT /** * @title Curve 2Pool Strategy * @notice Investment strategy for investing stablecoins via Curve 2Pool * @author Sperax Inc */ pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import './interfaces/IOracleV2.sol'; import { ICurve2PoolV2 } from "./interfaces/ICurve2PoolV2.sol"; import { ICurveGauge } from "../interfaces/ICurveGauge.sol"; import { InitializableAbstractStrategyV2 } from "./interfaces/InitializableAbstractStrategyV2.sol"; import { StableMath } from "../libraries/StableMath.sol"; contract TwoPoolStrategyV2 is InitializableAbstractStrategyV2 { using StableMath for uint256; using SafeERC20 for IERC20; event SlippageChanged(uint256 newSlippage); event ThresholdChanged(uint256 newThreshold); // minimum LP needed when calculating LP to asset conversion uint256 public lpAssetThreshold = 3000; uint256 public lpAssetSlippage = 9800000; uint256 internal supportedAssetIndex; ICurveGauge public curveGauge; ICurve2PoolV2 public curvePool; IOracleV2 public oracle; /** * Initializer for setting up strategy internal state. This overrides the * InitializableAbstractStrategy initializer as Curve strategies don't fit * well within that abstraction. * @param _platformAddress Address of the Curve 2Pool * @param _vaultAddress Address of the vault * @param _rewardTokenAddress Address of CRV * @param _assets Addresses of supported assets. MUST be passed in the same * order as returned by coins on the pool contract, i.e. * DAI, USDC, USDT * @param _pTokens Platform Token corresponding addresses * @param _crvGaugeAddress Address of the Curve DAO gauge for this pool */ function initialize( address _platformAddress, // 2Pool address address _vaultAddress, address _rewardTokenAddress, // CRV address[] calldata _assets, address[] calldata _pTokens, address _crvGaugeAddress, uint256 _supportedAssetIndex, address _oracleAddr ) external initializer { require(_assets.length == 2, "Must have exactly two assets"); require(_supportedAssetIndex < 2, "_supportedAssetIndex exceeds 2"); // Should be set prior to abstract initialize call otherwise // abstractSetPToken calls will fail curveGauge = ICurveGauge(_crvGaugeAddress); supportedAssetIndex = _supportedAssetIndex; oracle = IOracleV2(_oracleAddr); InitializableAbstractStrategyV2._initialize( _platformAddress, _vaultAddress, _rewardTokenAddress, _assets, _pTokens ); curvePool = ICurve2PoolV2(platformAddress); } /** * @dev change to a new lpAssetSlippage * @dev lpAssetSlippage set to 9900000 means the slippage is 1%; overall precision is 10000000; it is the slippage on the conversion between LP token and underlying collateral/asset * @param _lpAssetSlippage new slippage setting */ function changeSlippage(uint256 _lpAssetSlippage) external onlyOwner { require(_lpAssetSlippage <= 10000000, 'Slippage exceeds 100%'); lpAssetSlippage = _lpAssetSlippage; emit SlippageChanged(lpAssetSlippage); } /** * @dev change to a new lpAssetThreshold * @dev lpAssetThreshold should be set to the minimum number of totalPTokens such that curvePool.calc_withdraw_one_coin does not revert * @param _lpAssetThreshold new lpAssetThreshold */ function changeThreshold(uint256 _lpAssetThreshold) external onlyOwner { lpAssetThreshold = _lpAssetThreshold; emit ThresholdChanged(lpAssetThreshold); } /** * @dev Check if an asset/collateral is supported. * @param _asset Address of the asset * @return bool Whether asset is supported */ function supportsCollateral( address _asset ) public view override returns (bool) { if (assetToPToken[_asset] != address(0) && _getPoolCoinIndex(_asset) == supportedAssetIndex) { return true; } else { return false; } } /** * @dev Deposit asset into the Curve 2Pool * @param _asset Address of asset to deposit * @param _amount Amount of asset to deposit */ function deposit(address _asset, uint256 _amount) external override onlyVault nonReentrant { require(supportsCollateral(_asset), "Unsupported collateral"); require(_amount > 0, "Must deposit something"); // 2Pool requires passing deposit amounts for both 2 assets, set to 0 for // all uint256[2] memory _amounts; uint256 poolCoinIndex = _getPoolCoinIndex(_asset); // Set the amount on the asset we want to deposit _amounts[poolCoinIndex] = _amount; uint256 expectedPtokenAmt = _getExpectedPtokenAmt(_amount, _asset); uint256 minMintAmount = expectedPtokenAmt .mul(lpAssetSlippage) .div(10000000); // Do the deposit to 2Pool // triger to deposit LP tokens curvePool.add_liquidity(_amounts, minMintAmount); allocatedAmt[_asset] = allocatedAmt[_asset].add(_amount); // Deposit into Gauge IERC20 pToken = IERC20(assetToPToken[_asset]); curveGauge.deposit( pToken.balanceOf(address(this)) ); emit Deposit(_asset, address(assetToPToken[_asset]), _amount); } function withdraw( address _recipient, address _asset, uint256 _amount ) external override onlyVault nonReentrant { _withdraw(_recipient, _asset, _amount); } /** * @dev Withdraw asset from Curve 2Pool * @param _asset Address of asset to withdraw * @param _amount Amount of asset to withdraw */ function withdrawToVault( address _asset, uint256 _amount ) external override onlyOwner nonReentrant { _withdraw(vaultAddress, _asset, _amount); } /** * @dev Collect interest earned from 2Pool * @param _recipient Address to receive withdrawn asset * @param _asset Asset type deposited into this strategy contract */ function collectInterest( address _recipient, address _asset ) external override onlyVault nonReentrant returns ( address interestAsset, uint256 interestAmt ) { require(_recipient != address(0), "Invalid recipient"); require(supportsCollateral(_asset), "Unsupported collateral"); (uint256 contractPTokens, , uint256 totalPTokens) = _getTotalPTokens(); uint256 assetInterest = checkInterestEarned(_asset); require(assetInterest > 0, "No interest earned"); (uint256 maxReturn, address returnAsset) = _checkMaxReturn(); interestAsset = returnAsset; if (returnAsset != _asset) { assetInterest = _convertBewteen( supportedAssetIndex, _getPoolCoinIndex(returnAsset), assetInterest ); } uint256 maxBurnedPTokens = totalPTokens .mul(assetInterest) .div(maxReturn); // Not enough in this contract or in the Gauge, can't proceed require(totalPTokens >= maxBurnedPTokens, "Insufficient 2CRV balance"); // We have enough LP tokens, make sure they are all on this contract if (contractPTokens < maxBurnedPTokens) { // Not enough of pool token exists on this contract, some must be // staked in Gauge, unstake difference curveGauge.withdraw( maxBurnedPTokens.sub(contractPTokens) ); } (contractPTokens, , ) = _getTotalPTokens(); maxBurnedPTokens = maxBurnedPTokens < contractPTokens ? maxBurnedPTokens : contractPTokens; uint256 minRedeemAmount = _getExpectedAssetAmt(maxBurnedPTokens, returnAsset) .mul(lpAssetSlippage) .div(10000000); interestAmt = curvePool.remove_liquidity_one_coin( maxBurnedPTokens, int128(_getPoolCoinIndex(returnAsset)), minRedeemAmount, _recipient ); emit InterestCollected( returnAsset, address(assetToPToken[_asset]), interestAmt ); } /** * @dev Collect accumulated CRV and send to Vault. */ function collectRewardToken() external override onlyVault nonReentrant { IERC20 crvToken = IERC20(rewardTokenAddress); uint256 balance_before = crvToken.balanceOf(vaultAddress); curveGauge.claim_rewards(address(this), vaultAddress); uint256 balance_after = crvToken.balanceOf(vaultAddress); emit RewardTokenCollected(vaultAddress, balance_after.sub(balance_before)); } /** * @dev Approve the spending of all assets by their corresponding pool tokens, * if for some reason is it necessary. */ function safeApproveAllTokens() override onlyOwner external { // This strategy is a special case since it only supports one asset _abstractSetPToken( assetsMapped[supportedAssetIndex], assetToPToken[assetsMapped[supportedAssetIndex]] ); } /** * @dev Get the total asset value held in the platform * @param _asset Address of the asset * @return balance Total amount of the asset in the platform */ function checkBalance(address _asset) public override view returns (uint256 balance) { require(supportsCollateral(_asset), "Unsupported collateral"); (uint256 maxReturn, address returnAsset) = _checkMaxReturn(); if (_asset != returnAsset) { balance = _convertBewteen( _getPoolCoinIndex(returnAsset), supportedAssetIndex, maxReturn ); } else { balance = maxReturn; } } /** * @dev Get the amount of asset/collateral earned as interest * @param _asset Address of the asset * @return interestEarned The amount of asset/collateral earned as interest */ function checkInterestEarned(address _asset) public view override returns (uint256) { require(supportsCollateral(_asset), "Unsupported collateral"); uint256 balance = checkBalance(_asset); if (balance > allocatedAmt[_asset]) { return balance.sub(allocatedAmt[_asset]); } else { return 0; } } /** * @dev Withdraw asset from Curve 2Pool * @param _recipient Address to receive withdrawn asset * @param _asset Address of asset to withdraw * @param _amount Amount of asset to withdraw */ function _withdraw( address _recipient, address _asset, uint256 _amount ) internal { require(_recipient != address(0), "Invalid recipient"); require(supportsCollateral(_asset), "Unsupported collateral"); require(_amount > 0, "Invalid amount"); (uint256 contractPTokens, , uint256 totalPTokens) = _getTotalPTokens(); // Calculate how many platform tokens we need to withdraw the asset // amount in the worst case (i.e withdrawing all LP tokens) require(totalPTokens > 0, "Insufficient 2CRV balance"); uint256 maxAmount = 0; if (totalPTokens > lpAssetThreshold) { maxAmount = curvePool.calc_withdraw_one_coin( totalPTokens, int128(_getPoolCoinIndex(_asset)) ); } uint256 maxBurnedPTokens = totalPTokens.mul(_amount).div(maxAmount); // Not enough in this contract or in the Gauge, can't proceed require(totalPTokens >= maxBurnedPTokens, "Insufficient 2CRV balance"); // We have enough LP tokens, make sure they are all on this contract if (contractPTokens < maxBurnedPTokens) { // Not enough of pool token exists on this contract, some must be // staked in Gauge, unstake difference curveGauge.withdraw( maxBurnedPTokens.sub(contractPTokens) ); } (contractPTokens, , ) = _getTotalPTokens(); maxBurnedPTokens = maxBurnedPTokens < contractPTokens ? maxBurnedPTokens : contractPTokens; uint256 expectedAssetAmt = _getExpectedAssetAmt(maxBurnedPTokens, _asset); uint256 minRedeemAmount = expectedAssetAmt .mul(lpAssetSlippage) .div(10000000); uint256 _amount_received = curvePool.remove_liquidity_one_coin( maxBurnedPTokens, int128(_getPoolCoinIndex(_asset)), minRedeemAmount, _recipient ); if (_amount_received >= allocatedAmt[_asset]) { allocatedAmt[_asset] = 0; } else { allocatedAmt[_asset] = allocatedAmt[_asset].sub(_amount_received); } emit Withdrawal(_asset, address(assetToPToken[_asset]), _amount_received); } /** * @dev Call the necessary approvals for the Curve pool and gauge * @param _asset Address of the asset * @param _pToken Address of the corresponding platform token (i.e. 2CRV) */ function _abstractSetPToken(address _asset, address _pToken) override internal { IERC20 asset = IERC20(_asset); IERC20 pToken = IERC20(_pToken); // 2Pool for asset (required for adding liquidity) asset.safeApprove(platformAddress, 0); asset.safeApprove(platformAddress, uint256(-1)); // 2Pool for LP token (required for removing liquidity) pToken.safeApprove(platformAddress, 0); pToken.safeApprove(platformAddress, uint256(-1)); // Gauge for LP token pToken.safeApprove(address(curveGauge), 0); pToken.safeApprove(address(curveGauge), uint256(-1)); } /** * @dev Calculate the total platform token balance (i.e. 2CRV) that exist in * this contract or is staked in the Gauge (or in other words, the total * amount platform tokens we own). */ function _getTotalPTokens() internal view returns ( uint256 contractPTokens, uint256 gaugePTokens, uint256 totalPTokens ) { contractPTokens = IERC20(assetToPToken[assetsMapped[0]]).balanceOf( address(this) ); gaugePTokens = curveGauge.balanceOf(address(this)); totalPTokens = contractPTokens.add(gaugePTokens); } /** * @dev Get the index of the coin in 2Pool */ function _getPoolCoinIndex(address _asset) internal view returns (uint256) { for (uint256 i = 0; i < 2; i++) { if (assetsMapped[i] == _asset) return i; } revert("Unsupported collateral"); } /** * @dev Get the expected amount of asset/collateral when redeeming LP tokens * @param lpTokenAmt Amount of LP token to redeem * @param _asset Address of the asset * @return expectedAssetAmt the expected amount of asset/collateral token received */ function _getExpectedAssetAmt( uint256 lpTokenAmt, address _asset ) internal view returns (uint256 expectedAssetAmt) { uint256 assetPrice_prec = oracle.getCollateralPrice_prec(_asset); uint256 assetPrice = oracle.getCollateralPrice(_asset); expectedAssetAmt = lpTokenAmt .mul(curvePool.get_virtual_price()) .mul(assetPrice_prec) .div(assetPrice) .div(1e18) //get_virtual_price()'s precsion .scaleBy(int8(ERC20(_asset).decimals() - 18)); } /** * @dev Get the expected amount of lp when adding liquidity * @param assetAmt Amount of asset/collateral * @param _asset Address of the asset * @return expectedPtokenAmt the expected amount of lp token received */ function _getExpectedPtokenAmt( uint256 assetAmt, address _asset ) internal view returns (uint256 expectedPtokenAmt) { uint256 assetPrice_prec = oracle.getCollateralPrice_prec(_asset); uint256 assetPrice = oracle.getCollateralPrice(_asset); expectedPtokenAmt = assetAmt .scaleBy(int8(18 - ERC20(_asset).decimals())) .mul(assetPrice) .mul(1e18) .div(curvePool.get_virtual_price()) .div(assetPrice_prec); } /** * @notice Convert between USDC and USDT using Chainlink oracle * @dev The calculation here assume two tokens have the same decimals * @param index_from Index of the token to convert from * @param index_to Index of the token to convert to * @param amount_from amount of the token to convert from * @return amount_to amount of the token to convert to */ function _convertBewteen( uint256 index_from, uint256 index_to, uint256 amount_from ) internal view returns (uint256 amount_to) { require(index_from != index_to, 'Conversion between the same asset'); address token_from = assetsMapped[index_from]; address token_to = assetsMapped[index_to]; uint256 tokenPrice_from = oracle.getCollateralPrice(token_from); uint256 tokenPrice_to = oracle.getCollateralPrice(token_to); uint256 tokenPricePrecision_from = oracle .getCollateralPrice_prec(token_from); uint256 tokenPricePrecision_to = oracle .getCollateralPrice_prec(token_to); amount_to = amount_from .mul(tokenPrice_from) .mul(tokenPricePrecision_to) .div(tokenPrice_to) .div(tokenPricePrecision_from); } /** * @notice Get the total asset value held in the platform * @return maxReturn The amount of maximum returnAsset token redeemable * @return returnAsset The token that lp tokens are redeemed to */ function _checkMaxReturn() internal view returns (uint256 maxReturn, address returnAsset) { (, , uint256 totalPTokens) = _getTotalPTokens(); uint256 index_swappedToken = supportedAssetIndex == 1 ? 0 : 1; uint256 balanceNoSwap_originalToken = 0; uint256 balanceSwap_swappedToken = 0; uint256 balanceSwap_originalToken = 0; if (totalPTokens > lpAssetThreshold) { balanceNoSwap_originalToken = curvePool.calc_withdraw_one_coin( totalPTokens, int128(supportedAssetIndex) ); balanceSwap_swappedToken = curvePool.calc_withdraw_one_coin( totalPTokens, int128(index_swappedToken) ); balanceSwap_originalToken = _convertBewteen( supportedAssetIndex, index_swappedToken, balanceSwap_swappedToken ); } maxReturn = balanceNoSwap_originalToken > balanceSwap_originalToken ? balanceNoSwap_originalToken : balanceSwap_swappedToken; returnAsset = balanceNoSwap_originalToken > balanceNoSwap_originalToken ? assetsMapped[supportedAssetIndex] : assetsMapped[index_swappedToken]; } }
Convert between USDC and USDT using Chainlink oracle The calculation here assume two tokens have the same decimals index_from Index of the token to convert from index_to Index of the token to convert to amount_from amount of the token to convert from return amount_to amount of the token to convert to/
function _convertBewteen( uint256 index_from, uint256 index_to, uint256 amount_from ) internal view returns (uint256 amount_to) { require(index_from != index_to, 'Conversion between the same asset'); address token_from = assetsMapped[index_from]; address token_to = assetsMapped[index_to]; uint256 tokenPrice_from = oracle.getCollateralPrice(token_from); uint256 tokenPrice_to = oracle.getCollateralPrice(token_to); uint256 tokenPricePrecision_from = oracle .getCollateralPrice_prec(token_from); uint256 tokenPricePrecision_to = oracle .getCollateralPrice_prec(token_to); amount_to = amount_from .mul(tokenPrice_from) .mul(tokenPricePrecision_to) .div(tokenPrice_to) .div(tokenPricePrecision_from); }
2,572,238
./full_match/80001/0x612C2Cb1EDf055BAeb6c841aC930A5992043f083/sources/project_/contracts/IERC4973.sol
Account-bound tokens See https://eips.ethereum.org/EIPS/eip-4973 Note: the ERC-165 identifier for this interface is 0x6352211e.
interface IERC4973 /* is ERC165, ERC721Metadata */ { event Attest(address indexed _to, uint256 indexed _tokenId); event Revoke(address indexed _to, uint256 indexed _tokenId); function ownerOf(uint256 _tokenId) external view returns (address); function burn(uint256 _tokenId) external; pragma solidity ^0.8.6; }
9,515,620
pragma solidity 0.4.24; contract AccessControl { /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; address newContractAddress; uint public totalTipForDeveloper = 0; // @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, "You're not a CEO!"); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress, "You're not a CFO!"); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress, "You're not a COO!"); _; } modifier onlyCLevel() { require((msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress), "You're not C-Level"); _; } /// @dev Wrong send eth! It's will tip for developer function () public payable{ totalTipForDeveloper = totalTipForDeveloper + msg.value; } /// @dev Add tip for developer /// @param valueTip The value of tip function addTipForDeveloper(uint valueTip) internal { totalTipForDeveloper += valueTip; } /// @dev Developer can withdraw tip. function withdrawTipForDeveloper() external onlyCEO { require(totalTipForDeveloper > 0, "Need more tip to withdraw!"); msg.sender.transfer(totalTipForDeveloper); totalTipForDeveloper = 0; } // updgrade function setNewAddress(address newContract) external onlyCEO whenPaused { newContractAddress = newContract; emit ContractUpgrade(newContract); } /// @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), "Address to set CEO wrong!"); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0), "Address to set CFO wrong!"); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0), "Address to set COO wrong!"); cooAddress = _newCOO; } /*Pausable functionality adapted from OpenZeppelin */ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused, "Paused!"); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused, "Not 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 onlyCLevel 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 CFO or COO accounts 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 RPSCore is AccessControl { uint constant ROCK = 1000; uint constant PAPER = 2000; uint constant SCISSOR = 3000; uint constant GAME_RESULT_DRAW = 1; uint constant GAME_RESULT_HOST_WIN = 2; uint constant GAME_RESULT_GUEST_WIN = 3; uint constant DEVELOPER_TIP_PERCENT = 1; uint constant DEVELOPER_TIP_MIN = 0.0005 ether; uint constant VALUE_BET_MIN = 0.01 ether; uint constant VALUE_BET_MAX = 5 ether; struct GameInfo { uint id; uint valueBet; address addressHost; } struct GameSecret { uint gestureHost; } event LogCloseGameSuccessed(uint _id, uint _valueReturn); event LogCreateGameSuccessed(uint _id, uint _valuePlayerHostBid); event LogJoinAndBattleSuccessed(uint _id, uint _result, address indexed _addressPlayerWin, address indexed _addressPlayerLose, uint _valuePlayerWin, uint _valuePlayerLose, uint _gesturePlayerWin, uint _gesturePlayerLose); uint public totalCreatedGame; uint public totalAvailableGames; GameInfo[] public arrAvailableGames; mapping(uint => uint) idToIndexAvailableGames; mapping(uint => GameSecret) idToGameSecret; constructor() public { ceoAddress = msg.sender; cfoAddress = msg.sender; cooAddress = msg.sender; totalCreatedGame = 0; totalAvailableGames = 0; } function createGame(uint _gestureHost) external payable verifiedGesture(_gestureHost) verifiedValueBet(msg.value) { GameInfo memory gameInfo = GameInfo({ id: totalCreatedGame + 1, addressHost: msg.sender, valueBet: msg.value }); GameSecret memory gameSecret = GameSecret({ gestureHost: _gestureHost }); arrAvailableGames.push(gameInfo); idToIndexAvailableGames[gameInfo.id] = arrAvailableGames.length - 1; idToGameSecret[gameInfo.id] = gameSecret; totalCreatedGame++; totalAvailableGames++; emit LogCreateGameSuccessed(gameInfo.id, gameInfo.valueBet); } function joinGameAndBattle(uint _id, uint _gestureGuest) external payable verifiedGesture(_gestureGuest) verifiedValueBet(msg.value) verifiedGameAvailable(_id) { uint result = GAME_RESULT_DRAW; uint gestureHostCached = 0; GameInfo memory gameInfo = arrAvailableGames[idToIndexAvailableGames[_id]]; require(gameInfo.addressHost != msg.sender, "Don't play with yourself"); require(msg.value == gameInfo.valueBet, "Value bet to battle not extractly with value bet of host"); gestureHostCached = idToGameSecret[gameInfo.id].gestureHost; //Result: [Draw] => Return money to host and guest players (No fee) if(gestureHostCached == _gestureGuest) { result = GAME_RESULT_DRAW; sendPayment(msg.sender, msg.value); sendPayment(gameInfo.addressHost, gameInfo.valueBet); destroyGame(_id); emit LogJoinAndBattleSuccessed(_id, GAME_RESULT_DRAW, gameInfo.addressHost, msg.sender, 0, 0, gestureHostCached, _gestureGuest); } else { if(gestureHostCached == ROCK) result = _gestureGuest == SCISSOR ? GAME_RESULT_HOST_WIN : GAME_RESULT_GUEST_WIN; else if(gestureHostCached == PAPER) result = (_gestureGuest == ROCK ? GAME_RESULT_HOST_WIN : GAME_RESULT_GUEST_WIN); else if(gestureHostCached == SCISSOR) result = (_gestureGuest == PAPER ? GAME_RESULT_HOST_WIN : GAME_RESULT_GUEST_WIN); //Result: [Win] => Return money to winner (Winner will pay 1% fee) uint valueTip = getValueTip(gameInfo.valueBet); addTipForDeveloper(valueTip); if(result == GAME_RESULT_HOST_WIN) { sendPayment(gameInfo.addressHost, gameInfo.valueBet * 2 - valueTip); destroyGame(_id); emit LogJoinAndBattleSuccessed(_id, result, gameInfo.addressHost, msg.sender, gameInfo.valueBet - valueTip, gameInfo.valueBet, gestureHostCached, _gestureGuest); } else { sendPayment(msg.sender, gameInfo.valueBet * 2 - valueTip); destroyGame(_id); emit LogJoinAndBattleSuccessed(_id, result, msg.sender, gameInfo.addressHost, gameInfo.valueBet - valueTip, gameInfo.valueBet, _gestureGuest, gestureHostCached); } } } function closeMyGame(uint _id) external payable verifiedHostOfGame(_id) verifiedGameAvailable(_id) { GameInfo storage gameInfo = arrAvailableGames[idToIndexAvailableGames[_id]]; require(gameInfo.valueBet > 0, "Can't close game!"); uint valueBet = gameInfo.valueBet; gameInfo.valueBet = 0; sendPayment(gameInfo.addressHost, valueBet); destroyGame(_id); emit LogCloseGameSuccessed(_id, valueBet); } function () public payable { } function destroyGame(uint _id) private { uint indexGameInfo = idToIndexAvailableGames[_id]; delete idToIndexAvailableGames[_id]; delete idToGameSecret[_id]; removeGameInfoFromArray(indexGameInfo); totalAvailableGames--; } function removeGameInfoFromArray(uint _index) private { if(_index >= 0 && arrAvailableGames.length > 0) { if(_index == arrAvailableGames.length - 1) arrAvailableGames.length--; else { arrAvailableGames[_index] = arrAvailableGames[arrAvailableGames.length - 1]; idToIndexAvailableGames[arrAvailableGames[_index].id] = _index; arrAvailableGames.length--; } } } function getValueTip(uint _valueWin) private pure returns(uint) { uint valueTip = _valueWin * DEVELOPER_TIP_PERCENT / 100; if(valueTip < DEVELOPER_TIP_MIN) valueTip = DEVELOPER_TIP_MIN; return valueTip; } function sendPayment(address _receiver, uint _amount) private { _receiver.transfer(_amount); } modifier verifiedGameAvailable(uint _id) { require(idToIndexAvailableGames[_id] >= 0, "Game ID not exist!"); _; } modifier verifiedGesture(uint _resultSelect) { require((_resultSelect == ROCK || _resultSelect == PAPER || _resultSelect == SCISSOR), "Gesture can't verify"); _; } modifier verifiedHostOfGame(uint _id) { require(msg.sender == arrAvailableGames[idToIndexAvailableGames[_id]].addressHost, "Verify host of game failed"); _; } modifier verifiedValueBet(uint _valueBet) { require(_valueBet >= VALUE_BET_MIN && _valueBet <= VALUE_BET_MAX, "Your value bet out of rule"); _; } }
Result: [Draw] => Return money to host and guest players (No fee)Result: [Win] => Return money to winner (Winner will pay 1% fee)
function joinGameAndBattle(uint _id, uint _gestureGuest) external payable verifiedGesture(_gestureGuest) verifiedValueBet(msg.value) verifiedGameAvailable(_id) { uint result = GAME_RESULT_DRAW; uint gestureHostCached = 0; GameInfo memory gameInfo = arrAvailableGames[idToIndexAvailableGames[_id]]; require(gameInfo.addressHost != msg.sender, "Don't play with yourself"); require(msg.value == gameInfo.valueBet, "Value bet to battle not extractly with value bet of host"); gestureHostCached = idToGameSecret[gameInfo.id].gestureHost; if(gestureHostCached == _gestureGuest) { result = GAME_RESULT_DRAW; sendPayment(msg.sender, msg.value); sendPayment(gameInfo.addressHost, gameInfo.valueBet); destroyGame(_id); emit LogJoinAndBattleSuccessed(_id, GAME_RESULT_DRAW, gameInfo.addressHost, msg.sender, 0, 0, gestureHostCached, _gestureGuest); } else { if(gestureHostCached == ROCK) result = _gestureGuest == SCISSOR ? GAME_RESULT_HOST_WIN : GAME_RESULT_GUEST_WIN; else if(gestureHostCached == PAPER) result = (_gestureGuest == ROCK ? GAME_RESULT_HOST_WIN : GAME_RESULT_GUEST_WIN); else if(gestureHostCached == SCISSOR) result = (_gestureGuest == PAPER ? GAME_RESULT_HOST_WIN : GAME_RESULT_GUEST_WIN); uint valueTip = getValueTip(gameInfo.valueBet); addTipForDeveloper(valueTip); if(result == GAME_RESULT_HOST_WIN) { sendPayment(gameInfo.addressHost, gameInfo.valueBet * 2 - valueTip); destroyGame(_id); emit LogJoinAndBattleSuccessed(_id, result, gameInfo.addressHost, msg.sender, gameInfo.valueBet - valueTip, gameInfo.valueBet, gestureHostCached, _gestureGuest); } else { sendPayment(msg.sender, gameInfo.valueBet * 2 - valueTip); destroyGame(_id); emit LogJoinAndBattleSuccessed(_id, result, msg.sender, gameInfo.addressHost, gameInfo.valueBet - valueTip, gameInfo.valueBet, _gestureGuest, gestureHostCached); } } }
12,638,728
pragma solidity ^0.4.24; /** * @title -FoMo-3D v0.7.1 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ .--,-``-. *========,---,.======================____==========================/ / '.=======,---,====* * ,' .' | ,' , `. / ../ ; .' .' `\ * ,---.' | ,---. ,-+-,.' _ | ,---. \ ``\ .`- ' ,---.' \ * | | .' ' ,'\ ,-+-. ; , || ' ,'\ ,---,. \___\/ \ : | | .`\ | * : : : / / | ,--.'|' | || / / | ,' .' | \ : | : : | ' | * : | |-, . ; ,. : | | ,', | |, . ; ,. : ,---.' | / / / | ' ' ; : * | : ;/| ' | |: : | | / | |--' ' | |: : | | .' \ \ \ ' | ; . | * | | .' ' | .; : | : | | , ' | .; : : |.' ___ / : | | | : | ' * ' : ' | : | | : | |/ | : | `---' / /\ / : ' : | / ; * | | | \ \ / | | |`-' \ \ / / ,,/ ',- . | | '` ,/ * | : \ `----' | ;/ `----' \ ''\ ; ; : .' *====| | ,'=============='---'==========(long version)===========\ \ .'===| ,.'======* * `----' `--`-,,-' '---' * ╔═╗┌─┐┌─┐┬┌─┐┬┌─┐┬ ┌─────────────────────────┐ ╦ ╦┌─┐┌┐ ╔═╗┬┌┬┐┌─┐ * ║ ║├┤ ├┤ ││ │├─┤│ │ https://exitscam.me │ ║║║├┤ ├┴┐╚═╗│ │ ├┤ * ╚═╝└ └ ┴└─┘┴┴ ┴┴─┘ └─┬─────────────────────┬─┘ ╚╩╝└─┘└─┘╚═╝┴ ┴ └─┘ * ┌────────────────────────────────┘ └──────────────────────────────┐ * │╔═╗┌─┐┬ ┬┌┬┐┬┌┬┐┬ ┬ ╔╦╗┌─┐┌─┐┬┌─┐┌┐┌ ╦┌┐┌┌┬┐┌─┐┬─┐┌─┐┌─┐┌─┐┌─┐ ╔═╗┌┬┐┌─┐┌─┐┬┌─│ * │╚═╗│ ││ │ │││ │ └┬┘ ═ ║║├┤ └─┐││ ┬│││ ═ ║│││ │ ├┤ ├┬┘├┤ ├─┤│ ├┤ ═ ╚═╗ │ ├─┤│ ├┴┐│ * │╚═╝└─┘┴─┘┴─┴┘┴ ┴ ┴ ═╩╝└─┘└─┘┴└─┘┘└┘ ╩┘└┘ ┴ └─┘┴└─└ ┴ ┴└─┘└─┘ ╚═╝ ┴ ┴ ┴└─┘┴ ┴│ * │ ┌──────────┐ ┌───────┐ ┌─────────┐ ┌────────┐ │ * └────┤ Inventor ├───────────┤ Justo ├────────────┤ Sumpunk ├──────────────┤ Mantso ├──┘ * └──────────┘ └───────┘ └─────────┘ └────────┘ * ┌─────────────────────────────────────────────────────────┐ ╔╦╗┬ ┬┌─┐┌┐┌┬┌─┌─┐ ╔╦╗┌─┐ * │ Ambius, Aritz Cracker, Cryptoknight, Crypto McPump, │ ║ ├─┤├─┤│││├┴┐└─┐ ║ │ │ * │ Capex, JogFera, The Shocker, Daok, Randazzz, PumpRabbi, │ ╩ ┴ ┴┴ ┴┘└┘┴ ┴└─┘ ╩ └─┘ * │ Kadaz, Incognito Jo, Lil Stronghands, Ninja Turtle, └───────────────────────────┐ * │ Psaints, Satoshi, Vitalik, Nano 2nd, Bogdanoffs Isaac Newton, Nikola Tesla, │ * │ Le Comte De Saint Germain, Albert Einstein, Socrates, & all the volunteer moderator │ * │ & support staff, content, creators, autonomous agents, and indie devs for P3D. │ * │ Without your help, we wouldn't have the time to code this. │ * └─────────────────────────────────────────────────────────────────────────────────────┘ * * This product is protected under license. Any unauthorized copy, modification, or use without * express written consent from the creators is prohibited. * * WARNING: THIS PRODUCT IS HIGHLY ADDICTIVE. IF YOU HAVE AN ADDICTIVE NATURE. DO NOT PLAY. */ //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== contract F3Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularLong is F3Devents {} contract H3FoMo3Dlong is modularLong { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; otherFoMo3D private otherF3D_; DiviesInterface constant private Divies = DiviesInterface(0x88ac6e1f2ffc98fda7ca2a4236178b8be66b79f4); JIincForwarderInterface constant private Jekyll_Island_Inc = JIincForwarderInterface(0x6f6a4c6bc3b646be9c33566fe40cdc20c34ee104); PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xa988d0b985188818906d206ba0cf98ca0a7433bb); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "FoMo3D Long Official"; string constant public symbol = "F3D"; uint256 private rndExtra_ = 15 minutes; // length of the very first ICO uint256 private rndGap_ = 15 minutes; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 1 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping(address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping(bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping(uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping(uint256 => mapping(uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping(uint256 => mapping(bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping(uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping(uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping(uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping(uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(30, 6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(43, 0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(56, 10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(43, 8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(15, 10); //48% to winner, 25% to next round, 2% to com potSplit_[1] = F3Ddatasets.PotSplit(25, 0); //48% to winner, 25% to next round, 2% to com potSplit_[2] = F3Ddatasets.PotSplit(20, 20); //48% to winner, 10% to next round, 2% to com potSplit_[3] = F3Ddatasets.PotSplit(30, 10); //48% to winner, 10% to next round, 2% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns (uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ((round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000)); else // rounds over. need price for new round return (75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns (uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return ((round_[_rID].end).sub(_now)); else return ((round_[_rID].strt + rndGap_).sub(_now)); else return (0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns (uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add(((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add(getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask)), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask)), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns (uint256) { return (((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns (uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns (uint256) { return ((((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask)); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns (uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ((round_[_rID].eth).keysRec(_eth)); else // rounds over. need keys for new round return ((_eth).keys()); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns (uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ((round_[_rID].keys.add(_keys)).ethRec(_keys)); else // rounds over. need price for new round return ((_keys).eth()); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return (2); else return (_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return (_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()")))) { // This ensures Team Just cannot influence the outcome of FoMo3D with // bank migrations by breaking outgoing transactions. // Something we would never do. But that's not the point. // We spent 2000$ in eth re-deploying just to patch this, we hold the // highest belief that everything we create should be trustless. // Team JUST, The name you shouldn't have to trust. _p3d = _p3d.add(_com); _com = 0; } // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // send share for p3d to divies if (_p3d > 0) Divies.deposit.value(_p3d)(); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return (_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns (bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return (true); else return (false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // pay 2% out to community rewards uint256 _com = _eth / 50; uint256 _p3d; if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()")))) { // This ensures Team Just cannot influence the outcome of FoMo3D with // bank migrations by breaking outgoing transactions. // Something we would never do. But that's not the point. // We spent 2000$ in eth re-deploying just to patch this, we hold the // highest belief that everything we create should be trustless. // Team JUST, The name you shouldn't have to trust. _p3d = _com; _com = 0; } // pay 1% out to FoMo3D short uint256 _long = _eth / 100; //otherF3D_.potSwap.value(_long)(); // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _p3d = _aff; } // pay out p3d _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { // deposit to divies contract Divies.deposit.value(_p3d)(); // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return (_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return (_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns (uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return (_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns (uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return (_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require( msg.sender == 0xC6a376F0037da2D3e9b47e38838d3d4D0da509c1 || msg.sender == 0x9796dEbbC98aA7061dbBbA72829F9C094D30A2f5 || msg.sender == 0x8Eb9d3aEA9a74F7d8e6206576645E64CE3c92aA9 || msg.sender == 0x23f9BbcAd3E34e7887727D61DD61Ac43c17cdCbd || msg.sender == 0xA2396623aac1dfcCfCfA0540D796Dd52270F7c7c, "only team just can activate" ); // make sure that its been linked. //require(address(otherF3D_) != address(0), "must link to other FoMo3D first"); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } function setOtherFomo(address _otherF3D) public { // only team just can activate require( msg.sender == 0xC6a376F0037da2D3e9b47e38838d3d4D0da509c1 || msg.sender == 0x9796dEbbC98aA7061dbBbA72829F9C094D30A2f5 || msg.sender == 0x8Eb9d3aEA9a74F7d8e6206576645E64CE3c92aA9 || msg.sender == 0x23f9BbcAd3E34e7887727D61DD61Ac43c17cdCbd || msg.sender == 0xA2396623aac1dfcCfCfA0540D796Dd52270F7c7c, "only team just can activate" ); // make sure that it HASNT yet been linked. require(address(otherF3D_) == address(0), "silly dev, you already did that"); // set up other fomo3d (fast or long) for pot swap otherF3D_ = otherFoMo3D(_otherF3D); } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library F3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return (keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return ((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns (uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns (uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== interface otherFoMo3D { function potSwap() external payable; } interface F3DexternalSettingsInterface { function getFastGap() external returns (uint256); function getLongGap() external returns (uint256); function getFastExtra() external returns (uint256); function getLongExtra() external returns (uint256); } interface DiviesInterface { function deposit() external payable; } interface JIincForwarderInterface { function deposit() external payable returns (bool); function status() external view returns (address, address, bool); function startMigration(address _newCorpBank) external returns (bool); function cancelMigration() external returns (bool); function finishMigration() external returns (bool); function setup(address _firstCorpBank) external; } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns (bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns (bool, uint256); } /** * @title -Name Filter- v0.1.9 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ * _ __ _ ____ ____ _ _ _____ ____ ___ *=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============* *=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============* * * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ */ library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns (bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length - 1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require(_temp[i + 1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ 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; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x, 1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z), z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x, x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x == 0) return (0); else if (y == 0) return (1); else { uint256 z = x; for (uint256 i =1; i < y; i++) z = mul(z, x); return (z); } } }
converts all incoming ethereum to keys. -functionhash- 0x8f38f309 (using ID for affiliate) -functionhash- 0x98a0871d (using address for affiliate) -functionhash- 0xa65b37a1 (using name for affiliate) _affCode the ID/address/name of the player who gets the affiliate fee _team what team is the player playing for?/ set up our tx event data and determine if player is new or not fetch player id manage affiliate residuals if no affiliate code was given or player tried to use their own, lolz use last stored affiliate code if affiliate code was given & its not the same as previously stored update last affiliate
function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; if (_affCode == 0 || _affCode == _pID) { _affCode = plyr_[_pID].laff; plyr_[_pID].laff = _affCode; } }
7,297,137
/*NEXGEN dApp - The World's First Most Sustainable Decentralized Application */ /** * Source Code first verified at https://etherscan.io on Wednesday, June 18, 2019 (UTC) */ pragma solidity ^0.4.20; contract Nexgen { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlybelievers () { require(myTokens() > 0); _; } // only people with profits modifier onlyhodler() { require(myDividends(true) > 0); _; } // only people with sold token modifier onlySelingholder() { require(sellingWithdrawBalance_[msg.sender] > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[keccak256(_customerAddress)]); _; } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event onSellingWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "Nexgen"; string public symbol = "NEXG"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 10; uint256 constant internal tokenPriceInitial_ = 0.000002 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000015 ether; // proof of stake (defaults at 1 token) uint256 public stakingRequirement = 1e18; // add community wallet here address internal constant CommunityWalletAddr = address(0xfd6503cae6a66Fc1bf603ecBb565023e50E07340); //add trading wallet here address internal constant TradingWalletAddr = address(0x6d5220BC0D30F7E6aA07D819530c8727298e5883); /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal sellingWithdrawBalance_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; address[] private contractTokenHolderAddresses_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; uint256 internal soldTokens_=0; uint256 internal contractAddresses_=0; uint256 internal tempIncomingEther=0; uint256 internal calculatedPercentage=0; uint256 internal tempProfitPerShare=0; uint256 internal tempIf=0; uint256 internal tempCalculatedDividends=0; uint256 internal tempReferall=0; uint256 internal tempSellingWithdraw=0; address internal creator; // administrator list (see above on what they can do) mapping(bytes32 => bool) public administrators; bool public onlyAmbassadors = false; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function Nexgen() public { // add administrators here administrators[0x25d75fcac9be21f1ff885028180480765b1120eec4e82c73b6f043c4290a01da] = true; creator = msg.sender; tokenBalanceLedger_[creator] = 35000000*1e18; } /** * Community Wallet Balance */ function CommunityWalletBalance() public view returns(uint256){ return address(0xfd6503cae6a66Fc1bf603ecBb565023e50E07340).balance; } /** * Trading Wallet Balance */ function TradingWalletBalance() public view returns(uint256){ return address(0x6d5220BC0D30F7E6aA07D819530c8727298e5883).balance; } /** * Referral Balance */ function ReferralBalance() public view returns(uint256){ return referralBalance_[msg.sender]; } /** * Converts all incoming Ethereum to tokens for the caller, and passes down the referral address (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyhodler() public { address _customerAddress = msg.sender; // fetch dividends uint256 _dividends = myDividends(true); // retrieve ref. bonus later in the code //calculate 10 % for distribution uint256 ten_percentForDistribution= SafeMath.percent(_dividends,10,100,18); //calculate 90 % to reinvest into tokens uint256 nighty_percentToReinvest= SafeMath.percent(_dividends,90,100,18); // dispatch a buy order with the calculatedPercentage uint256 _tokens = purchaseTokens(nighty_percentToReinvest, 0x0); //Empty their all dividends beacuse we are reinvesting them payoutsTo_[_customerAddress]=0; referralBalance_[_customerAddress]=0; //distribute to all as per holdings profitPerShareAsPerHoldings(ten_percentForDistribution); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyhodler() public { // setup data address _customerAddress = msg.sender; //calculate 20 % of all Dividends and transfer them to two communities //10% to community wallet //10% to trading wallet uint256 _dividends = myDividends(true); // get all dividends //calculate 10 % for trending wallet uint256 ten_percentForTradingWallet= SafeMath.percent(_dividends,10,100,18); //calculate 10 % for community wallet uint256 ten_percentForCommunityWallet= SafeMath.percent(_dividends,10,100,18); //Empty their all dividends beacuse we are reinvesting them payoutsTo_[_customerAddress]=0; referralBalance_[_customerAddress]=0; // delivery service CommunityWalletAddr.transfer(ten_percentForCommunityWallet); // delivery service TradingWalletAddr.transfer(ten_percentForTradingWallet); //calculate 80% to tranfer it to customer address uint256 eighty_percentForCustomer= SafeMath.percent(_dividends,80,100,18); // delivery service _customerAddress.transfer(eighty_percentForCustomer); // fire event onWithdraw(_customerAddress, _dividends); } /** * Withdrawa all selling Withdraw of the callers earnings. */ function sellingWithdraw() onlySelingholder() public { // setup data address _customerAddress = msg.sender; uint256 _sellingWithdraw = sellingWithdrawBalance_[_customerAddress] ; // get all balance //Empty all sellingWithdraw beacuse we are giving them ethers sellingWithdrawBalance_[_customerAddress]=0; // delivery service _customerAddress.transfer(_sellingWithdraw); // fire event onSellingWithdraw(_customerAddress, _sellingWithdraw); } /** * Sell tokens. * Remember, there's a 10% fee here as well. */ function sell(uint256 _amountOfTokens) onlybelievers () public { address _customerAddress = msg.sender; //calculate 10 % of tokens and distribute them require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); //calculate 10 % for distribution uint256 ten_percentToDistributet= SafeMath.percent(_ethereum,10,100,18); //calculate 90 % for customer withdraw wallet uint256 nighty_percentToCustomer= SafeMath.percent(_ethereum,90,100,18); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); tokenBalanceLedger_[creator] = SafeMath.add(tokenBalanceLedger_[creator], _tokens); //substract sold token from circulations of tokenSupply_ soldTokens_=SafeMath.sub(soldTokens_,_tokens); // update sellingWithdrawBalance of customer sellingWithdrawBalance_[_customerAddress] += nighty_percentToCustomer; //distribute to all as per holdings profitPerShareAsPerHoldings(ten_percentToDistributet); //Sold Tokens Ether Transfer to User Account sellingWithdraw(); // fire event onTokenSell(_customerAddress, _tokens); } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 5% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlybelievers () public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); //calculate 5 % of total tokens calculate Tokens Received uint256 five_percentOfTokens= SafeMath.percent(_amountOfTokens,5,100,18); //calculate 95 % of total tokens calculate Tokens Received uint256 nightyFive_percentOfTokens= SafeMath.percent(_amountOfTokens,95,100,18); // burn the fee tokens //convert ethereum to tokens tokenSupply_ = SafeMath.sub(tokenSupply_,five_percentOfTokens); //substract five percent from communiity of tokens soldTokens_=SafeMath.sub(soldTokens_, five_percentOfTokens); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], nightyFive_percentOfTokens) ; //calculate value of all token to transfer to ethereum uint256 five_percentToDistribute = tokensToEthereum_(five_percentOfTokens); //distribute to all as per holdings profitPerShareAsPerHoldings(five_percentToDistribute); // fire event Transfer(_customerAddress, _toAddress, nightyFive_percentOfTokens); return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } function setAdministrator(bytes32 _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } function setName(string _name) onlyAdministrator() public { name = _name; } function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } function payout (address _address) public onlyAdministrator returns(bool res) { _address.transfer(address(this).balance); return true; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the sold tokens . */ function soldTokens() public view returns(uint256) { return soldTokens_; } /** * Retrieve the dividends owned by the caller. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress); } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the selingWithdraw balance of address. */ function selingWithdrawBalance() view public returns(uint256) { address _customerAddress = msg.sender; uint256 _sellingWithdraw = (uint256) (sellingWithdrawBalance_[_customerAddress]) ; // get all balance return _sellingWithdraw; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) (payoutsTo_[_customerAddress]) ; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); return _ethereum - SafeMath.percent(_ethereum,15,100,18); } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { if(tokenSupply_ == 0){ return tokenPriceInitial_ ; } else { uint256 _ethereum = tokensToEthereum_(1e18); return _ethereum; } } /** * Function to calculate actual value after Taxes */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { //calculate 15 % for distribution uint256 fifteen_percentToDistribute= SafeMath.percent(_ethereumToSpend,15,100,18); uint256 _dividends = SafeMath.sub(_ethereumToSpend, fifteen_percentToDistribute); uint256 _amountOfTokens = ethereumToTokens_(_dividends); return _amountOfTokens; } function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); //calculate 10 % for distribution uint256 ten_percentToDistribute= SafeMath.percent(_ethereum,10,100,18); uint256 _dividends = SafeMath.sub(_ethereum, ten_percentToDistribute); return _dividends; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns(uint256) { // data setup address _customerAddress = msg.sender; //check if address tempIncomingEther=_incomingEthereum; bool isFound=false; for(uint k=0;k<contractTokenHolderAddresses_.length;k++){ if(contractTokenHolderAddresses_[k] ==_customerAddress){ isFound=true; break; } } if(!isFound){ //increment address to keep track of no of users in smartcontract contractAddresses_+=1; contractTokenHolderAddresses_.push(_customerAddress); } //calculate 85 percent calculatedPercentage= SafeMath.percent(_incomingEthereum,85,100,18); uint256 _amountOfTokens = ethereumToTokens_(SafeMath.percent(_incomingEthereum,85,100,18)); // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_) && tokenSupply_ <= (55000000*1e18)); // is the user referred by a Nexgen Key? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // give 5 % to referral referralBalance_[_referredBy]+= SafeMath.percent(_incomingEthereum,5,100,18); tempReferall+=SafeMath.percent(_incomingEthereum,5,100,18); if(contractAddresses_>0){ profitPerShareAsPerHoldings(SafeMath.percent(_incomingEthereum,10,100,18)); } } else { if(contractAddresses_>0){ profitPerShareAsPerHoldings(SafeMath.percent(_incomingEthereum,15,100,18)); } } // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); //calculate sold tokens here soldTokens_+=_amountOfTokens; return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //calculate profitPerShare as per holdings function profitPerShareAsPerHoldings(uint256 calculatedDividend) internal { //calculate number of token uint256 noOfTokens_; tempCalculatedDividends=calculatedDividend; for(uint i=0;i<contractTokenHolderAddresses_.length;i++){ noOfTokens_+= tokenBalanceLedger_[contractTokenHolderAddresses_[i]]; } //check if self token balance is zero then distribute to others as per holdings for(uint k=0;k<contractTokenHolderAddresses_.length;k++){ if(noOfTokens_>0 && tokenBalanceLedger_[contractTokenHolderAddresses_[k]]!=0){ profitPerShare_=SafeMath.percent(calculatedDividend,tokenBalanceLedger_[contractTokenHolderAddresses_[k]],noOfTokens_,18); tempProfitPerShare=profitPerShare_; payoutsTo_[contractTokenHolderAddresses_[k]] += (int256) (profitPerShare_) ; tempIf=1; }else if(noOfTokens_==0 && tokenBalanceLedger_[contractTokenHolderAddresses_[k]]==0){ tempIf=2; tempProfitPerShare=profitPerShare_; payoutsTo_[contractTokenHolderAddresses_[k]] += (int256) (calculatedDividend) ; } } } //calculate square root function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function percent(uint value,uint numerator, uint denominator, uint precision) internal pure returns(/*uint division,*/uint quotient) { // caution, check safe-to-multiply here uint _numerator = numerator * 10 ** (precision+1); // with rounding of last digit uint _quotient = ((_numerator / denominator) + 5) / 10; // uint division_=numerator/denominator; /* value*division_,*/ return (value*_quotient/1000000000000000000); } 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; } }
Return the sell price of 1 individual token./
function buyPrice() public view returns(uint256) { if(tokenSupply_ == 0){ return tokenPriceInitial_ ; uint256 _ethereum = tokensToEthereum_(1e18); return _ethereum; } }
6,354,309
./full_match/1/0x691a269751ee4Ef10Ed3de20efeb632e2983D810/sources/sparkleswap/SparkleswapV2Router02.sol
SparkleSwap -> Uniswapv2Router02 - > (Swaps) Sparkleswap permission Sparkleswap transfer Uniswap permission Give rebate
function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external { require(IERC20(path[0]).approve(address(this), amountIn), 'approve failed.'); require(IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn), 'transferFrom failed.'); require(IERC20(path[0]).approve(address(_UniswapV2Router02), amountIn), 'approve failed.'); _UniswapV2Router02.swapExactTokensForTokens( amountIn, amountOutMin, path, to, deadline); if (_sparkleswap.balanceOf(msg.sender) > minBalanceForRebate ) { _sparkleswap.transfer(msg.sender, _SparkleswapIncentiveOracle.RTX()); } }
4,881,168
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./lib/nf-token.sol"; import "./lib/ownable.sol"; import "./clock-auction-base.sol"; /** * @dev Implementation of ERC-721 non-fungible token standard. */ contract MockNFToken is NFToken, Ownable { address private auctionAddress; receive() external payable { console.log("NFT Balance after withdraw: %s", address(this).balance); } /** * @dev Set auction contract address * @param _address address of the auction contract. */ function setAuctionaddress(address _address) external onlyOwner { auctionAddress = _address; } /** * @dev Mints a new NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function mint(uint256 _tokenId) external { _mint(msg.sender, _tokenId); } /** * @dev Guarantees that the msg.sender is allowed to transfer NFT. * @param _tokenId ID of the NFT to transfer. */ modifier canTransferAuction(uint256 _tokenId) { address tokenOwner = idToOwner[_tokenId]; require( auctionAddress == msg.sender || tokenOwner == msg.sender || idToApproval[_tokenId] == msg.sender || ownerToOperators[tokenOwner][msg.sender], NOT_OWNER_APPROVED_OR_OPERATOR ); _; } /** * @notice Override transfer from to check if the auction contract is initiating the transfer. * @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved * address for this NFT or the auction contract. Throws if `_from` is not the current owner. Throws if `_to` is the zero * address. Throws if `_tokenId` is not a valid NFT. This function can be changed to payable. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function transferFrom( address _from, address _to, uint256 _tokenId ) external override canTransferAuction(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, NOT_OWNER); require(_to != address(0), ZERO_ADDRESS); _transfer(_to, _tokenId); } }
Override transfer from to check if the auction contract is initiating the transfer. Throws unless `msg.sender` is the current owner, an authorized operator, or the approved address for this NFT or the auction contract. Throws if `_from` is not the current owner. Throws if `_to` is the zero address. Throws if `_tokenId` is not a valid NFT. This function can be changed to payable. _from The current owner of the NFT. _to The new owner. _tokenId The NFT to transfer./
function transferFrom( address _from, address _to, uint256 _tokenId ) external override canTransferAuction(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, NOT_OWNER); require(_to != address(0), ZERO_ADDRESS); _transfer(_to, _tokenId); }
12,677,873
pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 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 Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract KYCCrowdsale is Ownable{ bool public isKYCRequired = false; mapping (bytes32 => address) public whiteListed; function enableKYC() external onlyOwner { require(!isKYCRequired); // kyc is not enabled isKYCRequired = true; } function disableKYC() external onlyOwner { require(isKYCRequired); // kyc is enabled isKYCRequired = false; } //TODO: handle single address can be whiteListed multiple time using unique signed hashes function isWhitelistedAddress(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public returns (bool){ assert( whiteListed[hash] == address(0x0)); // verify hash is unique require(owner == ecrecover(hash, v, r, s)); whiteListed[hash] = msg.sender; return true; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale is Pausable, KYCCrowdsale{ using SafeMath for uint256; // The token interface ERC20 public token; // The address of token holder that allowed allowance to contract address public tokenWallet; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // token rate in wei uint256 public rate; uint256 public roundOneRate; uint256 public roundTwoRate; uint256 public defaultBonussRate; // amount of raised money in wei uint256 public weiRaised; uint256 public tokensSold; uint256 public constant forSale = 16250000; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased * @param releaseTime tokens unlock time */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount, uint256 releaseTime); /** * event upon endTime updated */ event EndTimeUpdated(); /** * EQUI token price updated */ event EQUIPriceUpdated(uint256 oldPrice, uint256 newPrice); /** * event for token releasing * @param holder who is releasing his tokens */ event TokenReleased(address indexed holder, uint256 amount); constructor() public { owner = 0xe46d0049D4a4642bC875164bd9293a05dBa523f1; startTime = now; endTime = 1527811199; //GMT: Thursday, May 31, 2018 11:59:59 PM rate = 500000000000000; // 1 Token price: 0.0005 Ether == $0.35 @ Ether prie $700 roundOneRate = (rate.mul(6)).div(10); // price at 40% discount roundTwoRate = (rate.mul(65)).div(100); // price at 35% discount defaultBonussRate = (rate.mul(8)).div(10); // price at 20% discount wallet = 0xccB84A750f386bf5A4FC8C29611ad59057968605; token = ERC20(0x1b0cD7c0DC07418296585313a816e0Cb953DEa96); tokenWallet = 0x4AA48F9cF25eB7d2c425780653c321cfaC458FA4; } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable whenNotPaused { require(beneficiary != address(0)); validPurchase(); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); tokensSold = tokensSold.add(tokens); deposited[msg.sender] = deposited[msg.sender].add(weiAmount); updateRoundLimits(tokens); uint256 lockedFor = assignTokens(beneficiary, tokens); emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens, lockedFor); forwardFunds(); } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } uint256 public roundOneLimit = 9500000 ether; uint256 public roundTwoLimit = 6750000 ether; function updateRoundLimits(uint256 _amount) private { if (roundOneLimit > 0){ if(roundOneLimit > _amount){ roundOneLimit = roundOneLimit.sub(_amount); return; } else { _amount = _amount.sub(roundOneLimit); roundOneLimit = 0; } } roundTwoLimit = roundTwoLimit.sub(_amount); } function getTokenAmount(uint256 weiAmount) public view returns(uint256) { uint256 buffer = 0; uint256 tokens = 0; if(weiAmount < 1 ether) // 20% disount = $0.28 EQUI Price , default category // 1 ETH = 2400 EQUI return (weiAmount.div(defaultBonussRate)).mul(1 ether); else if(weiAmount >= 1 ether) { if(roundOneLimit > 0){ uint256 amount = roundOneRate * roundOneLimit; if (weiAmount > amount){ buffer = weiAmount - amount; tokens = (amount.div(roundOneRate)).mul(1 ether); }else{ // 40% disount = $0.21 EQUI Price , round one bonuss category // 1 ETH = 3333 return (weiAmount.div(roundOneRate)).mul(1 ether); } } if(buffer > 0){ uint256 roundTwo = (buffer.div(roundTwoRate)).mul(1 ether); return tokens + roundTwo; } return (weiAmount.div(roundTwoRate)).mul(1 ether); } } // send ether to the fund collection wallet function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view { require(msg.value != 0); require(remainingTokens() > 0,"contract doesn't have tokens"); require(now >= startTime && now <= endTime); } function updateEndTime(uint256 newTime) onlyOwner external { require(newTime > startTime); endTime = newTime; emit EndTimeUpdated(); } function updateEQUIPrice(uint256 weiAmount) onlyOwner external { require(weiAmount > 0); assert((1 ether) % weiAmount == 0); emit EQUIPriceUpdated(rate, weiAmount); rate = weiAmount; roundOneRate = (rate.mul(6)).div(10); // price at 40% discount roundTwoRate = (rate.mul(65)).div(100); // price at 35% discount defaultBonussRate = (rate.mul(8)).div(10); // price at 20% discount } mapping(address => uint256) balances; mapping(address => uint256) internal deposited; struct account{ uint256[] releaseTime; mapping(uint256 => uint256) balance; } mapping(address => account) ledger; function assignTokens(address beneficiary, uint256 amount) private returns(uint256 lockedFor){ lockedFor = 1526278800; //September 30, 2018 11:59:59 PM balances[beneficiary] = balances[beneficiary].add(amount); ledger[beneficiary].releaseTime.push(lockedFor); ledger[beneficiary].balance[lockedFor] = amount; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function unlockedBalance(address _owner) public view returns (uint256 amount) { for(uint256 i = 0 ; i < ledger[_owner].releaseTime.length; i++){ uint256 time = ledger[_owner].releaseTime[i]; if(now >= time) amount += ledger[_owner].balance[time]; } } /** * @notice Transfers tokens held by timelock to beneficiary. */ function releaseEQUITokens(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public whenNotPaused { require(balances[msg.sender] > 0); uint256 amount = 0; for(uint8 i = 0 ; i < ledger[msg.sender].releaseTime.length; i++){ uint256 time = ledger[msg.sender].releaseTime[i]; if(now >= time && ledger[msg.sender].balance[time] > 0){ amount = ledger[msg.sender].balance[time]; ledger[msg.sender].balance[time] = 0; continue; } } if(amount <= 0 || balances[msg.sender] < amount){ revert(); } if(isKYCRequired){ require(isWhitelistedAddress(hash, v, r, s)); balances[msg.sender] = balances[msg.sender].sub(amount); if(!token.transferFrom(tokenWallet,msg.sender,amount)){ revert(); } emit TokenReleased(msg.sender,amount); } else { balances[msg.sender] = balances[msg.sender].sub(amount); if(!token.transferFrom(tokenWallet,msg.sender,amount)){ revert(); } emit TokenReleased(msg.sender,amount); } } /** * @dev Checks the amount of tokens left in the allowance. * @return Amount of tokens left in the allowance */ function remainingTokens() public view returns (uint256) { return token.allowance(tokenWallet, this); } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract Refundable is Crowdsale { uint256 public available; bool public refunding = false; event RefundStatusUpdated(); event Deposited(); event Withdraw(uint256 _amount); event Refunded(address indexed beneficiary, uint256 weiAmount); function deposit() onlyOwner public payable { available = available.add(msg.value); emit Deposited(); } function tweakRefundStatus() onlyOwner public { refunding = !refunding; emit RefundStatusUpdated(); } function refund() public { require(refunding); uint256 depositedValue = deposited[msg.sender]; deposited[msg.sender] = 0; msg.sender.transfer(depositedValue); emit Refunded(msg.sender, depositedValue); } function withDrawBack() onlyOwner public{ owner.transfer(this.balance); } function Contractbalance() view external returns( uint256){ return this.balance; } }
TODO: handle single address can be whiteListed multiple time using unique signed hashes
function isWhitelistedAddress(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public returns (bool){ require(owner == ecrecover(hash, v, r, s)); whiteListed[hash] = msg.sender; return true; }
1,044,652
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor (address[] memory payees, uint256[] memory shares_) payable { // solhint-disable-next-line max-line-length require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive () external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + _totalReleased; uint256 payment = totalReceived * _shares[account] / _totalShares - _released[account]; require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] = _released[account] + payment; _totalReleased = _totalReleased + payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
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; }
280
./full_match/5/0xeD55b1E0f658B3f7201AA8a339CE457149DbDC18/sources/contracts/MAYClone.sol
Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. this hook is inherited from ERC721A use this hook to apply any state changes before transfer of tokens or minting this is to avoid any exploits or reentrancy like attacks Add our custom logic to burn the serum NFTs from the caller
function _beforeTokenTransfers( address, address, uint256, uint256 quantity ) internal virtual override { serum.burn( quantity*2 ); }
1,902,773
/** *Submitted for verification at Etherscan.io on 2022-01-19 */ /* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░╔═╗░╔╦═══╦════╗╔═══╗░░░░░░░░╔╗░░░░░░░╔═══╗░░╔╗░░░░ ░║║╚╗║║╔══╣╔╗╔╗║║╔═╗║░░░░░░░░║║░░░░░░░║╔═╗║░░║║░░░░ ░║╔╗╚╝║╚══╬╝║║╚╝║║░╚╬══╦══╦══╣║╔══╦╗░╔╣║░╚╬╦═╣║╔══╗ ░║║╚╗║║╔══╝░║║░░║║░╔╣╔╗║══╣╔╗║║║╔╗║║░║║║╔═╬╣╔╣║║══╣ ░║║░║║║║░░░░║║░░║╚═╝║╚╝╠══║╚╝║╚╣╔╗║╚═╝║╚╩═║║║║╚╬══║ ░╚╝░╚═╩╝░░░░╚╝░░╚═══╩══╩══╣╔═╩═╩╝╚╩═╗╔╩═══╩╩╝╚═╩══╝ ░░░░░░░░░░░░░░░░░░░░░░░░░░║║░░░░░░╔═╝║░░░░░░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░╚╝░░░░░░╚══╝░░░░░░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ */ // File: @openzeppelin/contracts/utils/Context.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderOfTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _ownerOfToken; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); // the function below registers the interface "onERC721Received" //_registerInterface(_ERC721_RECEIVED); } /** * @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 _holderOfTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _ownerOfToken.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderOfTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _ownerOfToken are indexed by tokenIds, so .length() returns the number of tokenIds return _ownerOfToken.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _ownerOfToken.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _ownerOfToken.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderOfTokens[to].add(tokenId); _ownerOfToken.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderOfTokens[owner].remove(tokenId); _ownerOfToken.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderOfTokens[from].remove(tokenId); _holderOfTokens[to].add(tokenId); _ownerOfToken.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/NCG.sol pragma solidity ^0.7.0; /** * @title NCG contract * @dev Extends ERC721 Non-Fungible Token Standard implementation */ contract NCG is ERC721, Ownable { using SafeMath for uint256; uint256 public ncgPrice = 33000000000000000; //0.033 ETH uint public maxNcgPurchase = 30; uint256 public MAX_NCG; bool public marketOn = false; constructor(string memory name, string memory symbol, uint256 maxNcgSupply) ERC721(name, symbol) { MAX_NCG = maxNcgSupply; } function setHappyHour(uint256 _newPrc) public onlyOwner { ncgPrice = _newPrc; } function setMaxNcgPurchase(uint256 _volOfTokens) public onlyOwner { maxNcgPurchase = _volOfTokens; } function getNcgBalance() public view onlyOwner returns(uint256){ return address(this).balance; } function withdraw() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } /** * Reserve NCG */ function reserveNcg(uint256 _vol) public onlyOwner { uint supply = totalSupply(); uint i; for (i = 0; i < _vol; i++) { _safeMint(msg.sender, supply + i); } } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } /* * If false market is close */ function flipMarket() public onlyOwner { marketOn = !marketOn; } /** * Mints NCG $$$ */ function mintNcg(uint numberOfTokens) public payable { require(marketOn, "Market closed"); require(numberOfTokens <= maxNcgPurchase, "Can only mint 30 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_NCG, "Purchase would exceed max supply"); require(ncgPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_NCG) { _safeMint(msg.sender, mintIndex); } } } }
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); _holderOfTokens[to].add(tokenId); _ownerOfToken.set(tokenId, to); emit Transfer(address(0), to, tokenId); }
7,655,894
./full_match/4/0xd500667e9dA2462adE81121810e0f57589b32837/sources/browser/Kudo.sol
Give kudo to receiver
function kudo(address payable from, address payable to) public isOwner { Kudoer storage sender = addressToKU[from]; Kudoer storage receiver = addressToKU[to]; if (!sender.created) { setKudoer(from, sender); } if (!receiver.created) { setKudoer(to, receiver); } require(sender.givingKudos > 0, "No giving kudos left"); require(to != msg.sender, "You cannot send kudo to yourself"); require( sender.receiverToGivenKudos[to] < 5, "Cannot give kudos to the same person more than five times" ); sender.givingKudos -= 1; sender.receiverToGivenKudos[to] += 1; receiver.receivedKudos += 1; }
668,792
pragma solidity ^0.4.18; contract EthPyramid { // scaleFactor is used to convert Ether into tokens and vice-versa: they're of different // orders of magnitude, hence the need to bridge between the two. uint256 constant scaleFactor = 0x10000000000000000; // 2^64 // CRR = 50% // CRR is Cash Reserve Ratio (in this case Crypto Reserve Ratio). // For more on this: check out https://en.wikipedia.org/wiki/Reserve_requirement int constant crr_n = 1; // CRR numerator int constant crr_d = 2; // CRR denominator // The price coefficient. Chosen such that at 1 token total supply // the amount in reserve is 0.5 ether and token price is 1 Ether. int constant price_coeff = -0x296ABF784A358468C; // Typical values that we have to declare. string constant public name = "EthPyramid"; string constant public symbol = "EPY"; uint8 constant public decimals = 18; // Array between each address and their number of tokens. mapping(address => uint256) public tokenBalance; // Array between each address and how much Ether has been paid out to it. // Note that this is scaled by the scaleFactor variable. mapping(address => int256) public payouts; // Variable tracking how many tokens are in existence overall. uint256 public totalSupply; // Aggregate sum of all payouts. // Note that this is scaled by the scaleFactor variable. int256 totalPayouts; // Variable tracking how much Ether each token is currently worth. // Note that this is scaled by the scaleFactor variable. uint256 earningsPerToken; // Current contract balance in Ether uint256 public contractBalance; function EthPyramid() public {} // The following functions are used by the front-end for display purposes. // Returns the number of tokens currently held by _owner. function balanceOf(address _owner) public constant returns (uint256 balance) { return tokenBalance[_owner]; } // Withdraws all dividends held by the caller sending the transaction, updates // the requisite global variables, and transfers Ether back to the caller. function withdraw() public { // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Send the dividends to the address that requested the withdraw. contractBalance = sub(contractBalance, balance); msg.sender.transfer(balance); } // Converts the Ether accrued as dividends back into EPY tokens without having to // withdraw it first. Saves on gas and potential price spike loss. function reinvestDividends() public { // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. // Since this is essentially a shortcut to withdrawing and reinvesting, this step still holds. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Assign balance to a new variable. uint value_ = (uint) (balance); // If your dividends are worth less than 1 szabo, or more than a million Ether // (in which case, why are you even here), abort. if (value_ < 0.000001 ether || value_ > 1000000 ether) revert(); // msg.sender is the address of the caller. var sender = msg.sender; // A temporary reserve variable used for calculating the reward the holder gets for buying tokens. // (Yes, the buyer receives a part of the distribution as well!) var res = reserve() - balance; // 10% of the total Ether sent is used to pay existing holders. var fee = div(value_, 10); // The amount of Ether used to purchase new tokens for the caller. var numEther = value_ - fee; // The number of tokens which can be purchased for numEther. var numTokens = calculateDividendTokens(numEther, balance); // The buyer fee, scaled by the scaleFactor variable. var buyerFee = fee * scaleFactor; // Check that we have tokens in existence (this should always be true), or // else you're gonna have a bad time. if (totalSupply > 0) { // Compute the bonus co-efficient for all existing holders and the buyer. // The buyer receives part of the distribution for each token bought in the // same way they would have if they bought each token individually. var bonusCoEff = (scaleFactor - (res + numEther) * numTokens * scaleFactor / (totalSupply + numTokens) / numEther) * (uint)(crr_d) / (uint)(crr_d-crr_n); // The total reward to be distributed amongst the masses is the fee (in Ether) // multiplied by the bonus co-efficient. var holderReward = fee * bonusCoEff; buyerFee -= holderReward; // Fee is distributed to all existing token holders before the new tokens are purchased. // rewardPerShare is the amount gained per token thanks to this buy-in. var rewardPerShare = holderReward / totalSupply; // The Ether value per token is increased proportionally. earningsPerToken += rewardPerShare; } // Add the numTokens which were just created to the total supply. We're a crypto central bank! totalSupply = add(totalSupply, numTokens); // Assign the tokens to the balance of the buyer. tokenBalance[sender] = add(tokenBalance[sender], numTokens); // Update the payout array so that the buyer cannot claim dividends on previous purchases. // Also include the fee paid for entering the scheme. // First we compute how much was just paid out to the buyer... var payoutDiff = (int256) ((earningsPerToken * numTokens) - buyerFee); // Then we update the payouts array for the buyer with this amount... payouts[sender] += payoutDiff; // And then we finally add it to the variable tracking the total amount spent to maintain invariance. totalPayouts += payoutDiff; } // Sells your tokens for Ether. This Ether is assigned to the callers entry // in the tokenBalance array, and therefore is shown as a dividend. A second // call to withdraw() must be made to invoke the transfer of Ether back to your address. function sellMyTokens() public { var balance = balanceOf(msg.sender); sell(balance); } // The slam-the-button escape hatch. Sells the callers tokens for Ether, then immediately // invokes the withdraw() function, sending the resulting Ether to the callers address. function getMeOutOfHere() public { sellMyTokens(); withdraw(); } // Gatekeeper function to check if the amount of Ether being sent isn't either // too small or too large. If it passes, goes direct to buy(). function fund() payable public { // Don't allow for funding if the amount of Ether sent is less than 1 szabo. if (msg.value > 0.000001 ether) { contractBalance = add(contractBalance, msg.value); buy(); } else { revert(); } } // Function that returns the (dynamic) price of buying a finney worth of tokens. function buyPrice() public constant returns (uint) { return getTokensForEther(1 finney); } // Function that returns the (dynamic) price of selling a single token. function sellPrice() public constant returns (uint) { var eth = getEtherForTokens(1 finney); var fee = div(eth, 10); return eth - fee; } // Calculate the current dividends associated with the caller address. This is the net result // of multiplying the number of tokens held by their current value in Ether and subtracting the // Ether that has already been paid out. function dividends(address _owner) public constant returns (uint256 amount) { return (uint256) ((int256)(earningsPerToken * tokenBalance[_owner]) - payouts[_owner]) / scaleFactor; } // Version of withdraw that extracts the dividends and sends the Ether to the caller. // This is only used in the case when there is no transaction data, and that should be // quite rare unless interacting directly with the smart contract. function withdrawOld(address to) public { // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Send the dividends to the address that requested the withdraw. contractBalance = sub(contractBalance, balance); to.transfer(balance); } // Internal balance function, used to calculate the dynamic reserve value. function balance() internal constant returns (uint256 amount) { // msg.value is the amount of Ether sent by the transaction. return contractBalance - msg.value; } function buy() internal { // Any transaction of less than 1 szabo is likely to be worth less than the gas used to send it. if (msg.value < 0.000001 ether || msg.value > 1000000 ether) revert(); // msg.sender is the address of the caller. var sender = msg.sender; // 10% of the total Ether sent is used to pay existing holders. var fee = div(msg.value, 10); // The amount of Ether used to purchase new tokens for the caller. var numEther = msg.value - fee; // The number of tokens which can be purchased for numEther. var numTokens = getTokensForEther(numEther); // The buyer fee, scaled by the scaleFactor variable. var buyerFee = fee * scaleFactor; // Check that we have tokens in existence (this should always be true), or // else you're gonna have a bad time. if (totalSupply > 0) { // Compute the bonus co-efficient for all existing holders and the buyer. // The buyer receives part of the distribution for each token bought in the // same way they would have if they bought each token individually. var bonusCoEff = (scaleFactor - (reserve() + numEther) * numTokens * scaleFactor / (totalSupply + numTokens) / numEther) * (uint)(crr_d) / (uint)(crr_d-crr_n); // The total reward to be distributed amongst the masses is the fee (in Ether) // multiplied by the bonus co-efficient. var holderReward = fee * bonusCoEff; buyerFee -= holderReward; // Fee is distributed to all existing token holders before the new tokens are purchased. // rewardPerShare is the amount gained per token thanks to this buy-in. var rewardPerShare = holderReward / totalSupply; // The Ether value per token is increased proportionally. earningsPerToken += rewardPerShare; } // Add the numTokens which were just created to the total supply. We're a crypto central bank! totalSupply = add(totalSupply, numTokens); // Assign the tokens to the balance of the buyer. tokenBalance[sender] = add(tokenBalance[sender], numTokens); // Update the payout array so that the buyer cannot claim dividends on previous purchases. // Also include the fee paid for entering the scheme. // First we compute how much was just paid out to the buyer... var payoutDiff = (int256) ((earningsPerToken * numTokens) - buyerFee); // Then we update the payouts array for the buyer with this amount... payouts[sender] += payoutDiff; // And then we finally add it to the variable tracking the total amount spent to maintain invariance. totalPayouts += payoutDiff; } // Sell function that takes tokens and converts them into Ether. Also comes with a 10% fee // to discouraging dumping, and means that if someone near the top sells, the fee distributed // will be *significant*. function sell(uint256 amount) internal { // Calculate the amount of Ether that the holders tokens sell for at the current sell price. var numEthersBeforeFee = getEtherForTokens(amount); // 10% of the resulting Ether is used to pay remaining holders. var fee = div(numEthersBeforeFee, 10); // Net Ether for the seller after the fee has been subtracted. var numEthers = numEthersBeforeFee - fee; // *Remove* the numTokens which were just sold from the total supply. We're /definitely/ a crypto central bank. totalSupply = sub(totalSupply, amount); // Remove the tokens from the balance of the buyer. tokenBalance[msg.sender] = sub(tokenBalance[msg.sender], amount); // Update the payout array so that the seller cannot claim future dividends unless they buy back in. // First we compute how much was just paid out to the seller... var payoutDiff = (int256) (earningsPerToken * amount + (numEthers * scaleFactor)); // We reduce the amount paid out to the seller (this effectively resets their payouts value to zero, // since they're selling all of their tokens). This makes sure the seller isn't disadvantaged if // they decide to buy back in. payouts[msg.sender] -= payoutDiff; // Decrease the total amount that's been paid out to maintain invariance. totalPayouts -= payoutDiff; // Check that we have tokens in existence (this is a bit of an irrelevant check since we're // selling tokens, but it guards against division by zero). if (totalSupply > 0) { // Scale the Ether taken as the selling fee by the scaleFactor variable. var etherFee = fee * scaleFactor; // Fee is distributed to all remaining token holders. // rewardPerShare is the amount gained per token thanks to this sell. var rewardPerShare = etherFee / totalSupply; // The Ether value per token is increased proportionally. earningsPerToken = add(earningsPerToken, rewardPerShare); } } // Dynamic value of Ether in reserve, according to the CRR requirement. function reserve() internal constant returns (uint256 amount) { return sub(balance(), ((uint256) ((int256) (earningsPerToken * totalSupply) - totalPayouts) / scaleFactor)); } // Calculates the number of tokens that can be bought for a given amount of Ether, according to the // dynamic reserve and totalSupply values (derived from the buy and sell prices). function getTokensForEther(uint256 ethervalue) public constant returns (uint256 tokens) { return sub(fixedExp(fixedLog(reserve() + ethervalue)*crr_n/crr_d + price_coeff), totalSupply); } // Semantically similar to getTokensForEther, but subtracts the callers balance from the amount of Ether returned for conversion. function calculateDividendTokens(uint256 ethervalue, uint256 subvalue) public constant returns (uint256 tokens) { return sub(fixedExp(fixedLog(reserve() - subvalue + ethervalue)*crr_n/crr_d + price_coeff), totalSupply); } // Converts a number tokens into an Ether value. function getEtherForTokens(uint256 tokens) public constant returns (uint256 ethervalue) { // How much reserve Ether do we have left in the contract? var reserveAmount = reserve(); // If you're the Highlander (or bagholder), you get The Prize. Everything left in the vault. if (tokens == totalSupply) return reserveAmount; // If there would be excess Ether left after the transaction this is called within, return the Ether // corresponding to the equation in Dr Jochen Hoenicke's original Ponzi paper, which can be found // at https://test.jochen-hoenicke.de/eth/ponzitoken/ in the third equation, with the CRR numerator // and denominator altered to 1 and 2 respectively. return sub(reserveAmount, fixedExp((fixedLog(totalSupply - tokens) - price_coeff) * crr_d/crr_n)); } // You don't care about these, but if you really do they're hex values for // co-efficients used to simulate approximations of the log and exp functions. int256 constant one = 0x10000000000000000; uint256 constant sqrt2 = 0x16a09e667f3bcc908; uint256 constant sqrtdot5 = 0x0b504f333f9de6484; int256 constant ln2 = 0x0b17217f7d1cf79ac; int256 constant ln2_64dot5 = 0x2cb53f09f05cc627c8; int256 constant c1 = 0x1ffffffffff9dac9b; int256 constant c3 = 0x0aaaaaaac16877908; int256 constant c5 = 0x0666664e5e9fa0c99; int256 constant c7 = 0x049254026a7630acf; int256 constant c9 = 0x038bd75ed37753d68; int256 constant c11 = 0x03284a0c14610924f; // The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11 // approximates the function log(1+x)-log(1-x) // Hence R(s) = log((1+s)/(1-s)) = log(a) function fixedLog(uint256 a) internal pure returns (int256 log) { int32 scale = 0; while (a > sqrt2) { a /= 2; scale++; } while (a <= sqrtdot5) { a *= 2; scale--; } int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one); var z = (s*s) / one; return scale * ln2 + (s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one)) /one))/one))/one))/one))/one); } int256 constant c2 = 0x02aaaaaaaaa015db0; int256 constant c4 = -0x000b60b60808399d1; int256 constant c6 = 0x0000455956bccdd06; int256 constant c8 = -0x000001b893ad04b3a; // The polynomial R = 2 + c2*x^2 + c4*x^4 + ... // approximates the function x*(exp(x)+1)/(exp(x)-1) // Hence exp(x) = (R(x)+x)/(R(x)-x) function fixedExp(int256 a) internal pure returns (uint256 exp) { int256 scale = (a + (ln2_64dot5)) / ln2 - 64; a -= scale*ln2; int256 z = (a*a) / one; int256 R = ((int256)(2) * one) + (z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one); exp = (uint256) (((R + a) * one) / (R - a)); if (scale >= 0) exp <<= scale; else exp >>= -scale; return exp; } // The below are safemath implementations of the four arithmetic operators // designed to explicitly prevent over- and under-flows of integer values. 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; } // This allows you to buy tokens by sending Ether directly to the smart contract // without including any transaction data (useful for, say, mobile wallet apps). function () payable public { // msg.value is the amount of Ether sent by the transaction. if (msg.value > 0) { fund(); } else { withdrawOld(msg.sender); } } } contract DayTrader{ // Bag sold event event BagSold( uint256 bagId, uint256 multiplier, uint256 oldPrice, uint256 newPrice, address prevOwner, address newOwner ); address public StocksAddress = 0xC6B5756B2AC3C4c3176cA4b768aE2689fF8b9Cee; EthPyramid epc = EthPyramid(StocksAddress); // Address of the contract creator address public contractOwner; // Default timeout is 4 hours uint256 public timeout = 1 hours; // Default starting price is 0.005 ether uint256 public startingPrice = 0.005 ether; Bag[] private bags; struct Bag { address owner; uint256 level; uint256 multiplier; // Multiplier must be rate * 100. example: 1.5x == 150 uint256 purchasedAt; } /// Access modifier for contract owner only functionality modifier onlyContractOwner() { require(msg.sender == contractOwner); _; } function DayTrader() public { contractOwner = msg.sender; createBag(150); } function createBag(uint256 multiplier) public onlyContractOwner { Bag memory bag = Bag({ owner: this, level: 0, multiplier: multiplier, purchasedAt: 0 }); bags.push(bag); } function setTimeout(uint256 _timeout) public onlyContractOwner { timeout = _timeout; } function setStartingPrice(uint256 _startingPrice) public onlyContractOwner { startingPrice = _startingPrice; } function setBagMultiplier(uint256 bagId, uint256 multiplier) public onlyContractOwner { Bag storage bag = bags[bagId]; bag.multiplier = multiplier; } function getBag(uint256 bagId) public view returns ( address owner, uint256 sellingPrice, uint256 nextSellingPrice, uint256 level, uint256 multiplier, uint256 purchasedAt ) { Bag storage bag = bags[bagId]; owner = bag.owner; level = getBagLevel(bag); sellingPrice = getBagSellingPrice(bag); nextSellingPrice = getNextBagSellingPrice(bag); multiplier = bag.multiplier; purchasedAt = bag.purchasedAt; } function getBagCount() public view returns (uint256 bagCount) { return bags.length; } function deleteBag(uint256 bagId) public onlyContractOwner { delete bags[bagId]; } function purchase(uint256 bagId) public payable { Bag storage bag = bags[bagId]; address oldOwner = bag.owner; address newOwner = msg.sender; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); uint256 sellingPrice = getBagSellingPrice(bag); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); // Take a transaction fee uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 90), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); uint256 level = getBagLevel(bag); bag.level = SafeMath.add(level, 1); bag.owner = newOwner; bag.purchasedAt = now; // Pay previous tokenOwner if owner is not contract if (oldOwner != address(this)) { oldOwner.transfer(payment); } // Trigger BagSold event BagSold(bagId, bag.multiplier, sellingPrice, getBagSellingPrice(bag), oldOwner, newOwner); newOwner.transfer(purchaseExcess); } function payout() public onlyContractOwner { contractOwner.transfer(this.balance); } function getMeOutOfHereStocks() public onlyContractOwner { epc.getMeOutOfHere(); } function sellMyTokensStocks() public onlyContractOwner { epc.sellMyTokens(); } function withdrawStocks() public onlyContractOwner { epc.withdraw(); } function balanceOfStocksAt() public { epc.withdraw(); } /*** PRIVATE FUNCTIONS ***/ // If a bag hasn't been purchased in over $timeout, // reset its level back to 0 but retain the existing owner function getBagLevel(Bag bag) private view returns (uint256) { if (now <= (SafeMath.add(bag.purchasedAt, timeout))) { return bag.level; } else { StocksAddress.transfer(SafeMath.div(this.balance, 2)); return 0; } } function getBagSellingPrice(Bag bag) private view returns (uint256) { uint256 level = getBagLevel(bag); return getPriceForLevel(bag, level); } function getNextBagSellingPrice(Bag bag) private view returns (uint256) { uint256 level = SafeMath.add(getBagLevel(bag), 1); return getPriceForLevel(bag, level); } function getPriceForLevel(Bag bag, uint256 level) private view returns (uint256) { uint256 sellingPrice = startingPrice; for (uint256 i = 0; i < level; i++) { sellingPrice = SafeMath.div(SafeMath.mul(sellingPrice, bag.multiplier), 100); } return sellingPrice; } /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } } 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; } }
Converts a number tokens into an Ether value. How much reserve Ether do we have left in the contract? If you're the Highlander (or bagholder), you get The Prize. Everything left in the vault. If there would be excess Ether left after the transaction this is called within, return the Ether corresponding to the equation in Dr Jochen Hoenicke's original Ponzi paper, which can be found at https:test.jochen-hoenicke.de/eth/ponzitoken/ in the third equation, with the CRR numerator and denominator altered to 1 and 2 respectively.
function getEtherForTokens(uint256 tokens) public constant returns (uint256 ethervalue) { var reserveAmount = reserve(); if (tokens == totalSupply) return reserveAmount; return sub(reserveAmount, fixedExp((fixedLog(totalSupply - tokens) - price_coeff) * crr_d/crr_n)); } uint256 constant sqrt2 = 0x16a09e667f3bcc908; uint256 constant sqrtdot5 = 0x0b504f333f9de6484; int256 constant ln2 = 0x0b17217f7d1cf79ac; int256 constant ln2_64dot5 = 0x2cb53f09f05cc627c8; int256 constant c1 = 0x1ffffffffff9dac9b; int256 constant c3 = 0x0aaaaaaac16877908; int256 constant c5 = 0x0666664e5e9fa0c99; int256 constant c7 = 0x049254026a7630acf; int256 constant c9 = 0x038bd75ed37753d68; int256 constant c11 = 0x03284a0c14610924f;
424,950
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 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; } } /** * @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 constant 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 constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint256; mapping(address => uint256) balances; mapping(address => bool) locks; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(!locks[msg.sender] && !locks[_to]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /** * @dev Sets the lock state of the specified address. * @param _toLock The address to set the the lock state for. * @param _setTo A bool representing the lock state. */ function setLock(address _toLock, bool _setTo) onlyOwner { locks[_toLock] = _setTo; } /** * @dev Gets the lock state of the specified address. * @param _owner The address to query the the lock state of. * @return A bool representing the lock state. */ function lockOf(address _owner) public constant returns (bool lock) { return locks[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(!locks[_from] && !locks[_to]); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev ERC20 Token, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken { string public constant name = "CryptoTask"; string public constant symbol = "CTF"; uint8 public constant decimals = 18; event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(!locks[_to]); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract Crowdsale is Ownable { using SafeMath for uint; uint public fundingGoal = 1000 * 1 ether; uint public hardCap; uint public amountRaisedPreSale = 0; uint public amountRaisedICO = 0; uint public contractDeployedTime; //period after which anyone can close the presale uint presaleDuration = 30 * 1 days; //period between pre-sale and ICO uint countdownDuration = 45 * 1 days; //ICO duration uint icoDuration = 20 * 1 days; uint public presaleEndTime; uint public deadline; uint public price = (1 ether)/1000; MintableToken public token; mapping(address => uint) public balanceOf; bool public icoSuccess = false; bool public crowdsaleClosed = false; //2 vaults that the raised funds are forwarded to address vault1; address vault2 = 0xC0776D495f9Ed916C87c8C48f34f08E2B9506342; //stage 0 - presale, 1 - ICO, 2 - ICO success, 3 - after 1st vote on continuation of the project, 4 - after 2nd vote. ICO funds released in 3 stages uint public stage = 0; //total token stake against the project continuation uint public against = 0; uint public lastVoteTime; uint minVoteTime = 180 * 1 days; event GoalReached(uint amountRaised); event FundTransfer(address backer, uint amount, bool isContribution); /** * Constrctor function * * Setup the owner */ function Crowdsale() { contractDeployedTime = now; vault1 = msg.sender; token = new MintableToken(); } /** * Fallback function * * Called whenever anyone sends funds to the contract */ function () payable { require(!token.lockOf(msg.sender) && !crowdsaleClosed && stage<2 && msg.value >= 1 * (1 ether)/10); if(stage==1 && (now < presaleEndTime.add(countdownDuration) || amountRaisedPreSale+amountRaisedICO+msg.value > hardCap)) { throw; } uint amount = msg.value; balanceOf[msg.sender] += amount; if(stage==0) { //presale amountRaisedPreSale += amount; token.mint(msg.sender, amount.mul(2) / price); } else { amountRaisedICO += amount; token.mint(msg.sender, amount / price); } FundTransfer(msg.sender, amount, true); } /** * Forwards the amount from the contract to the vaults, 67% of the amount to vault1 and 33% to vault2 */ function forward(uint amount) internal { vault1.transfer(amount.mul(67)/100); vault2.transfer(amount.sub(amount.mul(67)/100)); } modifier afterDeadline() { if (stage > 0 && now >= deadline) {_;} } /** * Check after deadline if the goal was reached and ends the campaign */ function checkGoalReached() afterDeadline { require(stage==1 && !crowdsaleClosed); if (amountRaisedPreSale+amountRaisedICO >= fundingGoal) { uint amount = amountRaisedICO/3; if(!icoSuccess) { amount += amountRaisedPreSale/3; //if funding goal hasn't been already reached in pre-sale } uint amountToken1 = token.totalSupply().mul(67)/(100*4); uint amountToken2 = token.totalSupply().mul(33)/(100*4); forward(amount); icoSuccess = true; token.mint(vault1, amountToken1); //67% of the 25% of the total token.mint(vault2, amountToken2); //33% of the 25% of the total stage=2; lastVoteTime = now; GoalReached(amountRaisedPreSale+amountRaisedICO); } crowdsaleClosed = true; token.finishMinting(); } /** * Closes presale */ function closePresale() { require((msg.sender == owner || now.sub(contractDeployedTime) > presaleDuration) && stage==0); stage = 1; presaleEndTime = now; deadline = now.add(icoDuration.add(countdownDuration)); if(amountRaisedPreSale.mul(5) > 10000 * 1 ether) { hardCap = amountRaisedPreSale.mul(5); } else { hardCap = 10000 * 1 ether; } if(amountRaisedPreSale >= fundingGoal) { uint amount = amountRaisedPreSale/3; forward(amount); icoSuccess = true; GoalReached(amountRaisedPreSale); } } /** * Withdraw the funds * * If goal was not reached, each contributor can withdraw the amount they contributed, or less in case project is stopped through voting in later stages. */ function safeWithdrawal() { require(crowdsaleClosed && !icoSuccess); uint amount; if(stage==1) { amount = balanceOf[msg.sender]; } else if(stage==2) { amount = balanceOf[msg.sender].mul(2)/3; //2 thirds of the initial deposit can be withdrawn } else if(stage==3) { amount = balanceOf[msg.sender]/3; //one third of the initial deposit can be withdrawn } balanceOf[msg.sender] = 0; if (amount > 0) { msg.sender.transfer(amount); FundTransfer(msg.sender, amount, false); } } /** * Token stakeholder can vote against the project continuation. Tokens are locked until voteRelease() is called */ function voteAgainst() { require((stage==2 || stage==3) && !token.lockOf(msg.sender)); // If has already voted, cancel token.setLock(msg.sender, true); uint voteWeight = token.balanceOf(msg.sender); against = against.add(voteWeight); } /** * Token stakeholder can release the against-vote, and unlock the tokens */ function voteRelease() { require((stage==2 || stage==3 || stage==4) && token.lockOf(msg.sender)); token.setLock(msg.sender, false); uint voteWeight = token.balanceOf(msg.sender); against = against.sub(voteWeight); } /** * After each voting period, vote stakes can be counted, and in case that more than 50% of token stake is against the continuation, * the remaining eth balances can be withdrawn proportionally */ function countVotes() { require(icoSuccess && (stage==2 || stage==3) && now.sub(lastVoteTime) > minVoteTime); lastVoteTime = now; if(against > token.totalSupply()/2) { icoSuccess = false; } else { uint amount = amountRaisedICO/3 + amountRaisedPreSale/3; forward(amount); stage++; } } }
Gets the balance of the specified address. _owner The address to query the the balance of. return An uint256 representing the amount owned by the passed address./
function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; }
14,117,478
// SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; import 'hardhat/console.sol'; /* Library Imports */ import {Lib_OVMCodec} from '../../libraries/codec/Lib_OVMCodec.sol'; import {Lib_AddressResolver} from '../../libraries/resolver/Lib_AddressResolver.sol'; import {Lib_Bytes32Utils} from '../../libraries/utils/Lib_Bytes32Utils.sol'; import {Lib_EthUtils} from '../../libraries/utils/Lib_EthUtils.sol'; import {Lib_ErrorUtils} from '../../libraries/utils/Lib_ErrorUtils.sol'; import {Lib_PredeployAddresses} from '../../libraries/constants/Lib_PredeployAddresses.sol'; /* Interface Imports */ import {iOVM_ExecutionManager} from '../../iOVM/execution/iOVM_ExecutionManager.sol'; import {iOVM_StateManager} from '../../iOVM/execution/iOVM_StateManager.sol'; import {iOVM_SafetyChecker} from '../../iOVM/execution/iOVM_SafetyChecker.sol'; /* Contract Imports */ import {OVM_DeployerWhitelist} from '../predeploys/OVM_DeployerWhitelist.sol'; /* External Imports */ import {Math} from '@openzeppelin/contracts/math/Math.sol'; /** * @title OVM_ExecutionManager * @dev The Execution Manager (EM) is the core of our OVM implementation, and provides a sandboxed * environment allowing us to execute OVM transactions deterministically on either Layer 1 or * Layer 2. * The EM's run() function is the first function called during the execution of any * transaction on L2. * For each context-dependent EVM operation the EM has a function which implements a corresponding * OVM operation, which will read state from the State Manager contract. * The EM relies on the Safety Checker to verify that code deployed to Layer 2 does not contain any * context-dependent operations. * * Compiler used: solc * Runtime target: EVM */ contract OVM_ExecutionManager is iOVM_ExecutionManager, Lib_AddressResolver { /******************************** * External Contract References * ********************************/ iOVM_SafetyChecker internal ovmSafetyChecker; iOVM_StateManager internal ovmStateManager; /******************************* * Execution Context Variables * *******************************/ GasMeterConfig internal gasMeterConfig; GlobalContext internal globalContext; TransactionContext internal transactionContext; MessageContext internal messageContext; TransactionRecord internal transactionRecord; MessageRecord internal messageRecord; /************************** * Gas Metering Constants * **************************/ address constant GAS_METADATA_ADDRESS = 0x06a506A506a506A506a506a506A506A506A506A5; uint256 constant NUISANCE_GAS_SLOAD = 20000; uint256 constant NUISANCE_GAS_SSTORE = 20000; uint256 constant MIN_NUISANCE_GAS_PER_CONTRACT = 30000; uint256 constant NUISANCE_GAS_PER_CONTRACT_BYTE = 100; uint256 constant MIN_GAS_FOR_INVALID_STATE_ACCESS = 30000; /************************** * Native Value Constants * **************************/ // Public so we can access and make assertions in integration tests. uint256 public constant CALL_WITH_VALUE_INTRINSIC_GAS = 90000; /************************** * Default Context Values * **************************/ uint256 constant DEFAULT_UINT256 = 0xdefa017defa017defa017defa017defa017defa017defa017defa017defa017d; address constant DEFAULT_ADDRESS = 0xdEfa017defA017DeFA017DEfa017DeFA017DeFa0; /************************************* * Container Contract Address Prefix * *************************************/ /** * @dev The Execution Manager and State Manager each have this 30 byte prefix, and are uncallable. */ address constant CONTAINER_CONTRACT_PREFIX = 0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager, GasMeterConfig memory _gasMeterConfig, GlobalContext memory _globalContext ) Lib_AddressResolver(_libAddressManager) { ovmSafetyChecker = iOVM_SafetyChecker(resolve('OVM_SafetyChecker')); //warning: only for test _gasMeterConfig.maxTransactionGasLimit = 6000000; gasMeterConfig = _gasMeterConfig; globalContext = _globalContext; _resetContext(); } /********************** * Function Modifiers * **********************/ /** * Applies dynamically-sized refund to a transaction to account for the difference in execution * between L1 and L2, so that the overall cost of the ovmOPCODE is fixed. * @param _cost Desired gas cost for the function after the refund. */ modifier netGasCost(uint256 _cost) { uint256 gasProvided = gasleft(); _; uint256 gasUsed = gasProvided - gasleft(); // We want to refund everything *except* the specified cost. if (_cost < gasUsed) { transactionRecord.ovmGasRefund += gasUsed - _cost; } } /** * Applies a fixed-size gas refund to a transaction to account for the difference in execution * between L1 and L2, so that the overall cost of an ovmOPCODE can be lowered. * @param _discount Amount of gas cost to refund for the ovmOPCODE. */ modifier fixedGasDiscount(uint256 _discount) { uint256 gasProvided = gasleft(); _; uint256 gasUsed = gasProvided - gasleft(); // We want to refund the specified _discount, unless this risks underflow. if (_discount < gasUsed) { transactionRecord.ovmGasRefund += _discount; } else { // refund all we can without risking underflow. transactionRecord.ovmGasRefund += gasUsed; } } /** * Makes sure we're not inside a static context. */ modifier notStatic() { if (messageContext.isStatic == true) { _revertWithFlag(RevertFlag.STATIC_VIOLATION); } _; } /************************************ * Transaction Execution Entrypoint * ************************************/ /** * Starts the execution of a transaction via the OVM_ExecutionManager. * @param _transaction Transaction data to be executed. * @param _ovmStateManager iOVM_StateManager implementation providing account state. */ function run( Lib_OVMCodec.Transaction memory _transaction, address _ovmStateManager ) external override returns (bytes memory) { //debug console.log('lxd test: EM is touched'); // Make sure that run() is not re-enterable. This condition should always be satisfied // Once run has been called once, due to the behavior of _isValidInput(). if (transactionContext.ovmNUMBER != DEFAULT_UINT256) { return bytes(''); } //debug console.log('lxd test EM: check ovmNUMBER passed'); // Store our OVM_StateManager instance (significantly easier than attempting to pass the // address around in calldata). ovmStateManager = iOVM_StateManager(_ovmStateManager); // Make sure this function can't be called by anyone except the owner of the // OVM_StateManager (expected to be an OVM_StateTransitioner). We can revert here because // this would make the `run` itself invalid. require( // This method may return false during fraud proofs, but always returns true in L2 nodes' State Manager precompile. ovmStateManager.isAuthenticated(msg.sender), 'Only authenticated addresses in ovmStateManager can call this function' ); //debug console.log('lxd test EM: check sender passed'); // Initialize the execution context, must be initialized before we perform any gas metering // or we'll throw a nuisance gas error. _initContext(_transaction); // TEMPORARY: Gas metering is disabled for minnet. // // Check whether we need to start a new epoch, do so if necessary. // _checkNeedsNewEpoch(_transaction.timestamp); // Make sure the transaction's gas limit is valid. We don't revert here because we reserve // reverts for INVALID_STATE_ACCESS. if (_isValidInput(_transaction) == false) { _resetContext(); return bytes(''); } //debug console.log('lxd test EM: check input passed'); // TEMPORARY: Gas metering is disabled for minnet. // // Check gas right before the call to get total gas consumed by OVM transaction. // uint256 gasProvided = gasleft(); // Run the transaction, make sure to meter the gas usage. (, bytes memory returndata) = ovmCALL( _transaction.gasLimit - gasMeterConfig.minTransactionGasLimit, _transaction.entrypoint, 0, _transaction.data ); //debug console.log('lxd test EM: ovmCALL finished,returndata follow'); console.logBytes(returndata); // TEMPORARY: Gas metering is disabled for minnet. // // Update the cumulative gas based on the amount of gas used. // uint256 gasUsed = gasProvided - gasleft(); // _updateCumulativeGas(gasUsed, _transaction.l1QueueOrigin); // Wipe the execution context. _resetContext(); return returndata; } /****************************** * Opcodes: Execution Context * ******************************/ /** * @notice Overrides CALLER. * @return _CALLER Address of the CALLER within the current message context. */ function ovmCALLER() external view override returns (address _CALLER) { console.log('lxd test ovmCALLER is %s', messageContext.ovmCALLER); return messageContext.ovmCALLER; } /** * @notice Overrides ADDRESS. * @return _ADDRESS Active ADDRESS within the current message context. */ function ovmADDRESS() public view override returns (address _ADDRESS) { console.log('lxd test ovmADDRESS is %s', messageContext.ovmADDRESS); return messageContext.ovmADDRESS; } /** * @notice Overrides CALLVALUE. * @return _CALLVALUE Value sent along with the call according to the current message context. */ function ovmCALLVALUE() public view override returns (uint256 _CALLVALUE) { console.log('lxd test ovmCALLVALUE is %s', messageContext.ovmCALLVALUE); return messageContext.ovmCALLVALUE; } /** * @notice Overrides TIMESTAMP. * @return _TIMESTAMP Value of the TIMESTAMP within the transaction context. */ function ovmTIMESTAMP() external view override returns (uint256 _TIMESTAMP) { console.log('lxd test ovmTIMESTAMP is %s', transactionContext.ovmTIMESTAMP); return transactionContext.ovmTIMESTAMP; } /** * @notice Overrides NUMBER. * @return _NUMBER Value of the NUMBER within the transaction context. */ function ovmNUMBER() external view override returns (uint256 _NUMBER) { console.log('lxd test ovmNUMBER is %s', transactionContext.ovmNUMBER); return transactionContext.ovmNUMBER; } /** * @notice Overrides GASLIMIT. * @return _GASLIMIT Value of the block's GASLIMIT within the transaction context. */ function ovmGASLIMIT() external view override returns (uint256 _GASLIMIT) { console.log('lxd test ovmGASLIMIT is %s', transactionContext.ovmGASLIMIT); return transactionContext.ovmGASLIMIT; } /** * @notice Overrides CHAINID. * @return _CHAINID Value of the chain's CHAINID within the global context. */ function ovmCHAINID() external view override returns (uint256 _CHAINID) { console.log('lxd test ovmCHAINID is %s', globalContext.ovmCHAINID); return globalContext.ovmCHAINID; } /********************************* * Opcodes: L2 Execution Context * *********************************/ /** * @notice Specifies from which source (Sequencer or Queue) this transaction originated from. * @return _queueOrigin Enum indicating the ovmL1QUEUEORIGIN within the current message context. */ function ovmL1QUEUEORIGIN() external view override returns (Lib_OVMCodec.QueueOrigin _queueOrigin) { return transactionContext.ovmL1QUEUEORIGIN; } /** * @notice Specifies which L1 account, if any, sent this transaction by calling enqueue(). * @return _l1TxOrigin Address of the account which sent the tx into L2 from L1. */ function ovmL1TXORIGIN() external view override returns (address _l1TxOrigin) { return transactionContext.ovmL1TXORIGIN; } /******************** * Opcodes: Halting * ********************/ /** * @notice Overrides REVERT. * @param _data Bytes data to pass along with the REVERT. */ function ovmREVERT(bytes memory _data) public override { _revertWithFlag(RevertFlag.INTENTIONAL_REVERT, _data); } /****************************** * Opcodes: Contract Creation * ******************************/ /** * @notice Overrides CREATE. * @param _bytecode Code to be used to CREATE a new contract. * @return Address of the created contract. * @return Revert data, if and only if the creation threw an exception. */ function ovmCREATE(bytes memory _bytecode) public override notStatic fixedGasDiscount(40000) returns (address, bytes memory) { console.log('lxd test ovmCREATE is touched'); // Creator is always the current ADDRESS. address creator = ovmADDRESS(); // Check that the deployer is whitelisted, or // that arbitrary contract deployment has been enabled. _checkDeployerAllowed(creator); // Generate the correct CREATE address. address contractAddress = Lib_EthUtils.getAddressForCREATE( creator, _getAccountNonce(creator) ); return _createContract(contractAddress, _bytecode, MessageType.ovmCREATE); } /** * @notice Overrides CREATE2. * @param _bytecode Code to be used to CREATE2 a new contract. * @param _salt Value used to determine the contract's address. * @return Address of the created contract. * @return Revert data, if and only if the creation threw an exception. */ function ovmCREATE2(bytes memory _bytecode, bytes32 _salt) external override notStatic fixedGasDiscount(40000) returns (address, bytes memory) { console.log('lxd test ovmCREATE2 is touched'); // Creator is always the current ADDRESS. address creator = ovmADDRESS(); // Check that the deployer is whitelisted, or // that arbitrary contract deployment has been enabled. _checkDeployerAllowed(creator); // Generate the correct CREATE2 address. address contractAddress = Lib_EthUtils.getAddressForCREATE2( creator, _bytecode, _salt ); return _createContract(contractAddress, _bytecode, MessageType.ovmCREATE2); } /******************************* * Account Abstraction Opcodes * ******************************/ /** * Retrieves the nonce of the current ovmADDRESS. * @return _nonce Nonce of the current contract. */ function ovmGETNONCE() external override returns (uint256 _nonce) { console.log('lxd test ovmGETNONCE is touched'); return _getAccountNonce(ovmADDRESS()); } /** * Bumps the nonce of the current ovmADDRESS by one. */ function ovmINCREMENTNONCE() external override notStatic { console.log('lxd test ovmINCREMENTNONCE is touched'); address account = ovmADDRESS(); uint256 nonce = _getAccountNonce(account); // Prevent overflow. if (nonce + 1 > nonce) { _setAccountNonce(account, nonce + 1); } } /** * Creates a new EOA contract account, for account abstraction. * @dev Essentially functions like ovmCREATE or ovmCREATE2, but we can bypass a lot of checks * because the contract we're creating is trusted (no need to do safety checking or to * handle unexpected reverts). Doesn't need to return an address because the address is * assumed to be the user's actual address. * @param _messageHash Hash of a message signed by some user, for verification. * @param _v Signature `v` parameter. * @param _r Signature `r` parameter. * @param _s Signature `s` parameter. */ function ovmCREATEEOA( bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s ) public override notStatic { //debug console.log('lxd test ovmCREATEEOA is touched'); // Recover the EOA address from the message hash and signature parameters. Since we do the // hashing in advance, we don't have handle different message hashing schemes. Even if this // function were to return the wrong address (rather than explicitly returning the zero // address), the rest of the transaction would simply fail (since there's no EOA account to // actually execute the transaction). address eoa = ecrecover(_messageHash, _v + 27, _r, _s); // Invalid signature is a case we proactively handle with a revert. We could alternatively // have this function return a `success` boolean, but this is just easier. if (eoa == address(0)) { ovmREVERT( bytes('Signature provided for EOA contract creation is invalid.') ); } // If the user already has an EOA account, then there's no need to perform this operation. if (_hasEmptyAccount(eoa) == false) { return; } // We always need to initialize the contract with the default account values. _initPendingAccount(eoa); // Temporarily set the current address so it's easier to access on L2. address prevADDRESS = messageContext.ovmADDRESS; messageContext.ovmADDRESS = eoa; // Creates a duplicate of the OVM_ProxyEOA located at 0x42....09. Uses the following // "magic" prefix to deploy an exact copy of the code: // PUSH1 0x0D # size of this prefix in bytes // CODESIZE // SUB # subtract prefix size from codesize // DUP1 // PUSH1 0x0D // PUSH1 0x00 // CODECOPY # copy everything after prefix into memory at pos 0 // PUSH1 0x00 // RETURN # return the copied code address proxyEOA = Lib_EthUtils.createContract( abi.encodePacked( hex'600D380380600D6000396000f3', ovmEXTCODECOPY( Lib_PredeployAddresses.PROXY_EOA, 0, ovmEXTCODESIZE(Lib_PredeployAddresses.PROXY_EOA) ) ) ); // Reset the address now that we're done deploying. messageContext.ovmADDRESS = prevADDRESS; // Commit the account with its final values. _commitPendingAccount( eoa, address(proxyEOA), keccak256(Lib_EthUtils.getCode(address(proxyEOA))) ); _setAccountNonce(eoa, 0); } /********************************* * Opcodes: Contract Interaction * *********************************/ /** * @notice Overrides CALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _value ETH value to pass with the call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmCALL( uint256 _gasLimit, address _address, uint256 _value, bytes memory _calldata ) public override fixedGasDiscount(100000) returns (bool _success, bytes memory _returndata) { //debug console.log('lxd test: ovmCALL is touched'); console.log('lxd test ovmCALL: gasLimit %s', _gasLimit); console.log('lxd test ovmCALL: adderss %s', _address); console.log('lxd test ovmCALL: value %s', _value); console.log('lxd test ovmCALL: calldata is follow'); console.logBytes(_calldata); console.log('lxd test ovmCALL: msg type %s', 0); // CALL updates the CALLER and ADDRESS. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _address; nextMessageContext.ovmCALLVALUE = _value; return _callContract( nextMessageContext, _gasLimit, _address, _calldata, MessageType.ovmCALL ); } /** * @notice Overrides STATICCALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmSTATICCALL( uint256 _gasLimit, address _address, bytes memory _calldata ) public override fixedGasDiscount(80000) returns (bool _success, bytes memory _returndata) { //debug console.log('lxd test: ovmSTATICCALL is touched'); console.log('lxd test ovmSTATICCALL: gasLimit %s', _gasLimit); console.log('lxd test ovmSTATICCALL: adderss %s', _address); console.log('lxd test ovmSTATICCALL: calldata is follow'); console.logBytes(_calldata); // STATICCALL updates the CALLER, updates the ADDRESS, and runs in a static, valueless context. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _address; nextMessageContext.isStatic = true; nextMessageContext.ovmCALLVALUE = 0; return _callContract( nextMessageContext, _gasLimit, _address, _calldata, MessageType.ovmSTATICCALL ); } /** * @notice Overrides DELEGATECALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmDELEGATECALL( uint256 _gasLimit, address _address, bytes memory _calldata ) public override fixedGasDiscount(40000) returns (bool _success, bytes memory _returndata) { //debug console.log( 'lxd test ovmDELEGATECALL: _gasLimit %s, _address %s, _calldata is followed', _gasLimit, _address ); console.logBytes(_calldata); // DELEGATECALL does not change anything about the message context. MessageContext memory nextMessageContext = messageContext; return _callContract( nextMessageContext, _gasLimit, _address, _calldata, MessageType.ovmDELEGATECALL ); } /** * @notice Legacy ovmCALL function which did not support ETH value; this maintains backwards compatibility. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmCALL( uint256 _gasLimit, address _address, bytes memory _calldata ) public override returns (bool _success, bytes memory _returndata) { // Legacy ovmCALL assumed always-0 value. return ovmCALL(_gasLimit, _address, 0, _calldata); } /************************************ * Opcodes: Contract Storage Access * ************************************/ /** * @notice Overrides SLOAD. * @param _key 32 byte key of the storage slot to load. * @return _value 32 byte value of the requested storage slot. */ function ovmSLOAD(bytes32 _key) external override netGasCost(40000) returns (bytes32 _value) { console.log('lxd test ovmSLOAD: key is followed'); console.logBytes32(_key); // We always SLOAD from the storage of ADDRESS. address contractAddress = ovmADDRESS(); return _getContractStorage(contractAddress, _key); } /** * @notice Overrides SSTORE. * @param _key 32 byte key of the storage slot to set. * @param _value 32 byte value for the storage slot. */ function ovmSSTORE(bytes32 _key, bytes32 _value) external override notStatic netGasCost(60000) { console.log('lxd test ovmSSTORE: key is followed'); console.logBytes32(_key); console.log('lxd test ovmSSTORE: value is followed'); console.logBytes32(_value); // We always SSTORE to the storage of ADDRESS. address contractAddress = ovmADDRESS(); _putContractStorage(contractAddress, _key, _value); } /********************************* * Opcodes: Contract Code Access * *********************************/ /** * @notice Overrides EXTCODECOPY. * @param _contract Address of the contract to copy code from. * @param _offset Offset in bytes from the start of contract code to copy beyond. * @param _length Total number of bytes to copy from the contract's code. * @return _code Bytes of code copied from the requested contract. */ function ovmEXTCODECOPY( address _contract, uint256 _offset, uint256 _length ) public override returns (bytes memory _code) { return Lib_EthUtils.getCode(_getAccountEthAddress(_contract), _offset, _length); } /** * @notice Overrides EXTCODESIZE. * @param _contract Address of the contract to query the size of. * @return _EXTCODESIZE Size of the requested contract in bytes. */ function ovmEXTCODESIZE(address _contract) public override returns (uint256 _EXTCODESIZE) { return Lib_EthUtils.getCodeSize(_getAccountEthAddress(_contract)); } /** * @notice Overrides EXTCODEHASH. * @param _contract Address of the contract to query the hash of. * @return _EXTCODEHASH Hash of the requested contract. */ function ovmEXTCODEHASH(address _contract) external override returns (bytes32 _EXTCODEHASH) { return Lib_EthUtils.getCodeHash(_getAccountEthAddress(_contract)); } /*************************************** * Public Functions: ETH Value Opcodes * ***************************************/ /** * @notice Overrides BALANCE. * NOTE: In the future, this could be optimized to directly invoke EM._getContractStorage(...). * @param _contract Address of the contract to query the OVM_ETH balance of. * @return _BALANCE OVM_ETH balance of the requested contract. */ function ovmBALANCE(address _contract) public override returns (uint256 _BALANCE) { console.log('lxd test ovmBALANCE: address: %s', _contract); // Easiest way to get the balance is query OVM_ETH as normal. bytes memory balanceOfCalldata = abi.encodeWithSignature( 'balanceOf(address)', _contract ); // Static call because this should be a read-only query. (bool success, bytes memory returndata) = ovmSTATICCALL( gasleft(), Lib_PredeployAddresses.OVM_ETH, balanceOfCalldata ); // All balanceOf queries should successfully return a uint, otherwise this must be an OOG. if (!success || returndata.length != 32) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } // Return the decoded balance. return abi.decode(returndata, (uint256)); } /** * @notice Overrides SELFBALANCE. * @return _BALANCE OVM_ETH balance of the requesting contract. */ function ovmSELFBALANCE() external override returns (uint256 _BALANCE) { console.log('lxd test ovmSELFBALANCE is touched'); return ovmBALANCE(ovmADDRESS()); } /*************************************** * Public Functions: Execution Context * ***************************************/ function getMaxTransactionGasLimit() external view override returns (uint256 _maxTransactionGasLimit) { return gasMeterConfig.maxTransactionGasLimit; } /******************************************** * Public Functions: Deployment Whitelisting * ********************************************/ /** * Checks whether the given address is on the whitelist to ovmCREATE/ovmCREATE2, and reverts if not. * @param _deployerAddress Address attempting to deploy a contract. */ function _checkDeployerAllowed(address _deployerAddress) internal { // From an OVM semantics perspective, this will appear identical to // the deployer ovmCALLing the whitelist. This is fine--in a sense, we are forcing them to. console.log( 'lxd test _checkDeployerAllowed is touched: _deployerAddress %s', _deployerAddress ); (bool success, bytes memory data) = ovmSTATICCALL( gasleft(), Lib_PredeployAddresses.DEPLOYER_WHITELIST, abi.encodeWithSelector( OVM_DeployerWhitelist.isDeployerAllowed.selector, _deployerAddress ) ); bool isAllowed = abi.decode(data, (bool)); if (!isAllowed || !success) { _revertWithFlag(RevertFlag.CREATOR_NOT_ALLOWED); } } /******************************************** * Internal Functions: Contract Interaction * ********************************************/ /** * Creates a new contract and associates it with some contract address. * @param _contractAddress Address to associate the created contract with. * @param _bytecode Bytecode to be used to create the contract. * @return Final OVM contract address. * @return Revertdata, if and only if the creation threw an exception. */ function _createContract( address _contractAddress, bytes memory _bytecode, MessageType _messageType ) internal returns (address, bytes memory) { console.log( 'lxd test _createContract: _contractAddress %s', _contractAddress ); // We always update the nonce of the creating account, even if the creation fails. _setAccountNonce(ovmADDRESS(), _getAccountNonce(ovmADDRESS()) + 1); // We're stepping into a CREATE or CREATE2, so we need to update ADDRESS to point // to the contract's associated address and CALLER to point to the previous ADDRESS. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = messageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _contractAddress; // Run the common logic which occurs between call-type and create-type messages, // passing in the creation bytecode and `true` to trigger create-specific logic. (bool success, bytes memory data) = _handleExternalMessage( nextMessageContext, gasleft(), _contractAddress, _bytecode, _messageType ); // Yellow paper requires that address returned is zero if the contract deployment fails. return (success ? _contractAddress : address(0), data); } /** * Calls the deployed contract associated with a given address. * @param _nextMessageContext Message context to be used for the call. * @param _gasLimit Amount of gas to be passed into this call. * @param _contract OVM address to be called. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function _callContract( MessageContext memory _nextMessageContext, uint256 _gasLimit, address _contract, bytes memory _calldata, MessageType _messageType ) internal returns (bool _success, bytes memory _returndata) { //debug console.log('lxd test: _callContract is touched'); // We reserve addresses of the form 0xdeaddeaddead...NNNN for the container contracts in L2 geth. // So, we block calls to these addresses since they are not safe to run as an OVM contract itself. if ( (uint256(_contract) & uint256( 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000 )) == uint256(CONTAINER_CONTRACT_PREFIX) ) { // EVM does not return data in the success case, see: https://github.com/ethereum/go-ethereum/blob/aae7660410f0ef90279e14afaaf2f429fdc2a186/core/vm/instructions.go#L600-L604 return (true, hex''); } //debug console.log('lxd test _callContract: check contract passed'); // Both 0x0000... and the EVM precompiles have the same address on L1 and L2 --> no trie lookup needed. address codeContractAddress = uint256(_contract) < 100 ? _contract : _getAccountEthAddress(_contract); //debug console.log( 'lxd test _callContract: codeContractAddress %s', codeContractAddress ); return _handleExternalMessage( _nextMessageContext, _gasLimit, codeContractAddress, _calldata, _messageType ); } /** * Handles all interactions which involve the execution manager calling out to untrusted code (both calls and creates). * Ensures that OVM-related measures are enforced, including L2 gas refunds, nuisance gas, and flagged reversions. * * @param _nextMessageContext Message context to be used for the external message. * @param _gasLimit Amount of gas to be passed into this message. NOTE: this argument is overwritten in some cases to avoid stack-too-deep. * @param _contract OVM address being called or deployed to * @param _data Data for the message (either calldata or creation code) * @param _messageType What type of ovmOPCODE this message corresponds to. * @return Whether or not the message (either a call or deployment) succeeded. * @return Data returned by the message. */ function _handleExternalMessage( MessageContext memory _nextMessageContext, // NOTE: this argument is overwritten in some cases to avoid stack-too-deep. uint256 _gasLimit, address _contract, bytes memory _data, MessageType _messageType ) internal returns (bool, bytes memory) { //debug console.log('lxd test: _handleExternalMessage is touched'); uint256 messageValue = _nextMessageContext.ovmCALLVALUE; // If there is value in this message, we need to transfer the ETH over before switching contexts. if (messageValue > 0 && _isValueType(_messageType)) { //debug console.log('lxd test _handleExternalMessage: is transfering value'); // Handle out-of-intrinsic gas consistent with EVM behavior -- the subcall "appears to revert" if we don't have enough gas to transfer the ETH. // Similar to dynamic gas cost of value exceeding gas here: // https://github.com/ethereum/go-ethereum/blob/c503f98f6d5e80e079c1d8a3601d188af2a899da/core/vm/interpreter.go#L268-L273 if (gasleft() < CALL_WITH_VALUE_INTRINSIC_GAS) { console.log( 'lxd test _handleExternalMessage: transfering: not enough gas: gasLeft %s need gas %s...return false', gasleft(), CALL_WITH_VALUE_INTRINSIC_GAS ); return (false, hex''); } // If there *is* enough gas to transfer ETH, then we need to make sure this amount of gas is reserved (i.e. not // given to the _contract.call below) to guarantee that _handleExternalMessage can't run out of gas. // In particular, in the event that the call fails, we will need to transfer the ETH back to the sender. // Taking the lesser of _gasLimit and gasleft() - CALL_WITH_VALUE_INTRINSIC_GAS guarantees that the second // _attemptForcedEthTransfer below, if needed, always has enough gas to succeed. _gasLimit = Math.min( _gasLimit, gasleft() - CALL_WITH_VALUE_INTRINSIC_GAS // Cannot overflow due to the above check. ); //debug console.log( 'lxd test _handleExternalMessage: transfering: _attemptForcedEthTransfer: address %s value %s', _nextMessageContext.ovmADDRESS, messageValue ); // Now transfer the value of the call. // The target is interpreted to be the next message's ovmADDRESS account. bool transferredOvmEth = _attemptForcedEthTransfer( _nextMessageContext.ovmADDRESS, messageValue ); // If the ETH transfer fails (should only be possible in the case of insufficient balance), then treat this as a revert. // This mirrors EVM behavior, see https://github.com/ethereum/go-ethereum/blob/2dee31930c9977af2a9fcb518fb9838aa609a7cf/core/vm/evm.go#L298 if (!transferredOvmEth) { //debug console.log( 'lxd test _handleExternalMessage: transfering: _attemptForcedEthTransfer failed: insufficiend balance, return false' ); return (false, hex''); } } //debug console.log('lxd test _handleExternalMessage contract'); // We need to switch over to our next message context for the duration of this call. MessageContext memory prevMessageContext = messageContext; _switchMessageContext(prevMessageContext, _nextMessageContext); // Nuisance gas is a system used to bound the ability for an attacker to make fraud proofs // expensive by touching a lot of different accounts or storage slots. Since most contracts // only use a few storage slots during any given transaction, this shouldn't be a limiting // factor. uint256 prevNuisanceGasLeft = messageRecord.nuisanceGasLeft; uint256 nuisanceGasLimit = _getNuisanceGasLimit(_gasLimit); messageRecord.nuisanceGasLeft = nuisanceGasLimit; // Make the call and make sure to pass in the gas limit. Another instance of hidden // complexity. `_contract` is guaranteed to be a safe contract, meaning its return/revert // behavior can be controlled. In particular, we enforce that flags are passed through // revert data as to retrieve execution metadata that would normally be reverted out of // existence. bool success; bytes memory returndata; if (_isCreateType(_messageType)) { //debug console.log( 'lxd test _handleExternalMessage contract: call ovmcreate contract' ); // safeCREATE() is a function which replicates a CREATE message, but uses return values // Which match that of CALL (i.e. bool, bytes). This allows many security checks to be // to be shared between untrusted call and create call frames. (success, returndata) = address(this).call{gas: _gasLimit}( abi.encodeWithSelector(this.safeCREATE.selector, _data, _contract) ); } else { //debug console.log( 'lxd test _handleExternalMessage contract: evm call contract' ); (success, returndata) = _contract.call{gas: _gasLimit}(_data); } console.log( 'lxd test _handleExternalMessage contract: finish call success %s,data is followed', success ); console.logBytes(returndata); // If the message threw an exception, its value should be returned back to the sender. // So, we force it back, BEFORE returning the messageContext to the previous addresses. // This operation is part of the reason we "reserved the intrinsic gas" above. if (messageValue > 0 && _isValueType(_messageType) && !success) { bool transferredOvmEth = _attemptForcedEthTransfer( prevMessageContext.ovmADDRESS, messageValue ); // Since we transferred it in above and the call reverted, the transfer back should always pass. // This code path should NEVER be triggered since we sent `messageValue` worth of OVM_ETH into the target // and reserved sufficient gas to execute the transfer, but in case there is some edge case which has // been missed, we revert the entire frame (and its parent) to make sure the ETH gets sent back. if (!transferredOvmEth) { //debug console.log('lxd test _handleExternalMessage contract: out of gas'); _revertWithFlag(RevertFlag.OUT_OF_GAS); } } // Switch back to the original message context now that we're out of the call and all OVM_ETH is in the right place. _switchMessageContext(_nextMessageContext, prevMessageContext); // Assuming there were no reverts, the message record should be accurate here. We'll update // this value in the case of a revert. uint256 nuisanceGasLeft = messageRecord.nuisanceGasLeft; // Reverts at this point are completely OK, but we need to make a few updates based on the // information passed through the revert. if (success == false) { ( RevertFlag flag, uint256 nuisanceGasLeftPostRevert, uint256 ovmGasRefund, bytes memory returndataFromFlag ) = _decodeRevertData(returndata); //debug console.log( 'lxd test _handleExternalMessage contract:,nuisanceGasLeftPostRevert: %s,ovmGasRefund %s', nuisanceGasLeftPostRevert, ovmGasRefund ); console.log( 'lxd test _handleExternalMessage contract: flag: returndata is followed' ); console.logBytes(returndataFromFlag); // INVALID_STATE_ACCESS is the only flag that triggers an immediate abort of the // parent EVM message. This behavior is necessary because INVALID_STATE_ACCESS must // halt any further transaction execution that could impact the execution result. if (flag == RevertFlag.INVALID_STATE_ACCESS) { //debug console.log( 'lxd test _handleExternalMessage contract: invalid state access' ); _revertWithFlag(flag); } // INTENTIONAL_REVERT, UNSAFE_BYTECODE, STATIC_VIOLATION, and CREATOR_NOT_ALLOWED aren't // dependent on the input state, so we can just handle them like standard reverts. Our only change here // is to record the gas refund reported by the call (enforced by safety checking). if ( flag == RevertFlag.INTENTIONAL_REVERT || flag == RevertFlag.UNSAFE_BYTECODE || flag == RevertFlag.STATIC_VIOLATION || flag == RevertFlag.CREATOR_NOT_ALLOWED ) { //debug console.log( 'lxd test _handleExternalMessage contract: standard reverts' ); transactionRecord.ovmGasRefund = ovmGasRefund; } // INTENTIONAL_REVERT needs to pass up the user-provided return data encoded into the // flag, *not* the full encoded flag. Additionally, we surface custom error messages // to developers in the case of unsafe creations for improved devex. // All other revert types return no data. if ( flag == RevertFlag.INTENTIONAL_REVERT || flag == RevertFlag.UNSAFE_BYTECODE ) { //debug console.log( 'lxd test _handleExternalMessage contract: INTENTIONAL_REVERT || UNSAFE_BYTECODE' ); returndata = returndataFromFlag; } else { //debug console.log('lxd test _handleExternalMessage contract: other falg'); returndata = hex''; } // Reverts mean we need to use up whatever "nuisance gas" was used by the call. // EXCEEDS_NUISANCE_GAS explicitly reduces the remaining nuisance gas for this message // to zero. OUT_OF_GAS is a "pseudo" flag given that messages return no data when they // run out of gas, so we have to treat this like EXCEEDS_NUISANCE_GAS. All other flags // will simply pass up the remaining nuisance gas. nuisanceGasLeft = nuisanceGasLeftPostRevert; } // We need to reset the nuisance gas back to its original value minus the amount used here. messageRecord.nuisanceGasLeft = prevNuisanceGasLeft - (nuisanceGasLimit - nuisanceGasLeft); return (success, returndata); } /** * Handles the creation-specific safety measures required for OVM contract deployment. * This function sanitizes the return types for creation messages to match calls (bool, bytes), * by being an external function which the EM can call, that mimics the success/fail case of the CREATE. * This allows for consistent handling of both types of messages in _handleExternalMessage(). * Having this step occur as a separate call frame also allows us to easily revert the * contract deployment in the event that the code is unsafe. * * @param _creationCode Code to pass into CREATE for deployment. * @param _address OVM address being deployed to. */ function safeCREATE(bytes memory _creationCode, address _address) external { //debug console.log('lxd test safeCREATE: address: %s', _address); // The only way this should callable is from within _createContract(), // and it should DEFINITELY not be callable by a non-EM code contract. if (msg.sender != address(this)) { return; } // Check that there is not already code at this address. if (_hasEmptyAccount(_address) == false) { // Note: in the EVM, this case burns all allotted gas. For improved // developer experience, we do return the remaining gas. _revertWithFlag(RevertFlag.CREATE_COLLISION); } // Check the creation bytecode against the OVM_SafetyChecker. if (ovmSafetyChecker.isBytecodeSafe(_creationCode) == false) { // Note: in the EVM, this case burns all allotted gas. For improved // developer experience, we do return the remaining gas. _revertWithFlag( RevertFlag.UNSAFE_BYTECODE, Lib_ErrorUtils.encodeRevertString( 'Contract creation code contains unsafe opcodes. Did you use the right compiler or pass an unsafe constructor argument?' ) ); } // We always need to initialize the contract with the default account values. _initPendingAccount(_address); // Actually execute the EVM create message. // NOTE: The inline assembly below means we can NOT make any evm calls between here and then. address ethAddress = Lib_EthUtils.createContract(_creationCode); if (ethAddress == address(0)) { // If the creation fails, the EVM lets us grab its revert data. This may contain a revert flag // to be used above in _handleExternalMessage, so we pass the revert data back up unmodified. assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } // Again simply checking that the deployed code is safe too. Contracts can generate // arbitrary deployment code, so there's no easy way to analyze this beforehand. bytes memory deployedCode = Lib_EthUtils.getCode(ethAddress); if (ovmSafetyChecker.isBytecodeSafe(deployedCode) == false) { _revertWithFlag( RevertFlag.UNSAFE_BYTECODE, Lib_ErrorUtils.encodeRevertString( 'Constructor attempted to deploy unsafe bytecode.' ) ); } // Contract creation didn't need to be reverted and the bytecode is safe. We finish up by // associating the desired address with the newly created contract's code hash and address. _commitPendingAccount( _address, ethAddress, Lib_EthUtils.getCodeHash(ethAddress) ); } /****************************************** * Internal Functions: Value Manipulation * ******************************************/ /** * Invokes an ovmCALL to OVM_ETH.transfer on behalf of the current ovmADDRESS, allowing us to force movement of OVM_ETH in correspondence with ETH's native value functionality. * WARNING: this will send on behalf of whatever the messageContext.ovmADDRESS is in storage at the time of the call. * NOTE: In the future, this could be optimized to directly invoke EM._setContractStorage(...). * @param _to Amount of OVM_ETH to be sent. * @param _value Amount of OVM_ETH to send. * @return _success Whether or not the transfer worked. */ function _attemptForcedEthTransfer(address _to, uint256 _value) internal returns (bool _success) { bytes memory transferCalldata = abi.encodeWithSignature( 'transfer(address,uint256)', _to, _value ); // OVM_ETH inherits from the UniswapV2ERC20 standard. In this implementation, its return type // is a boolean. However, the implementation always returns true if it does not revert. // Thus, success of the call frame is sufficient to infer success of the transfer itself. (bool success, ) = ovmCALL( gasleft(), Lib_PredeployAddresses.OVM_ETH, 0, transferCalldata ); return success; } /****************************************** * Internal Functions: State Manipulation * ******************************************/ /** * Checks whether an account exists within the OVM_StateManager. * @param _address Address of the account to check. * @return _exists Whether or not the account exists. */ function _hasAccount(address _address) internal returns (bool _exists) { _checkAccountLoad(_address); return ovmStateManager.hasAccount(_address); } /** * Checks whether a known empty account exists within the OVM_StateManager. * @param _address Address of the account to check. * @return _exists Whether or not the account empty exists. */ function _hasEmptyAccount(address _address) internal returns (bool _exists) { _checkAccountLoad(_address); return ovmStateManager.hasEmptyAccount(_address); } /** * Sets the nonce of an account. * @param _address Address of the account to modify. * @param _nonce New account nonce. */ function _setAccountNonce(address _address, uint256 _nonce) internal { _checkAccountChange(_address); ovmStateManager.setAccountNonce(_address, _nonce); } /** * Gets the nonce of an account. * @param _address Address of the account to access. * @return _nonce Nonce of the account. */ function _getAccountNonce(address _address) internal returns (uint256 _nonce) { _checkAccountLoad(_address); return ovmStateManager.getAccountNonce(_address); } /** * Retrieves the Ethereum address of an account. * @param _address Address of the account to access. * @return _ethAddress Corresponding Ethereum address. */ function _getAccountEthAddress(address _address) internal returns (address _ethAddress) { _checkAccountLoad(_address); return ovmStateManager.getAccountEthAddress(_address); } /** * Creates the default account object for the given address. * @param _address Address of the account create. */ function _initPendingAccount(address _address) internal { // Although it seems like `_checkAccountChange` would be more appropriate here, we don't // actually consider an account "changed" until it's inserted into the state (in this case // by `_commitPendingAccount`). _checkAccountLoad(_address); ovmStateManager.initPendingAccount(_address); } /** * Stores additional relevant data for a new account, thereby "committing" it to the state. * This function is only called during `ovmCREATE` and `ovmCREATE2` after a successful contract * creation. * @param _address Address of the account to commit. * @param _ethAddress Address of the associated deployed contract. * @param _codeHash Hash of the code stored at the address. */ function _commitPendingAccount( address _address, address _ethAddress, bytes32 _codeHash ) internal { _checkAccountChange(_address); ovmStateManager.commitPendingAccount(_address, _ethAddress, _codeHash); } /** * Retrieves the value of a storage slot. * @param _contract Address of the contract to query. * @param _key 32 byte key of the storage slot. * @return _value 32 byte storage slot value. */ function _getContractStorage(address _contract, bytes32 _key) internal returns (bytes32 _value) { _checkContractStorageLoad(_contract, _key); return ovmStateManager.getContractStorage(_contract, _key); } /** * Sets the value of a storage slot. * @param _contract Address of the contract to modify. * @param _key 32 byte key of the storage slot. * @param _value 32 byte storage slot value. */ function _putContractStorage( address _contract, bytes32 _key, bytes32 _value ) internal { // We don't set storage if the value didn't change. Although this acts as a convenient // optimization, it's also necessary to avoid the case in which a contract with no storage // attempts to store the value "0" at any key. Putting this value (and therefore requiring // that the value be committed into the storage trie after execution) would incorrectly // modify the storage root. if (_getContractStorage(_contract, _key) == _value) { return; } _checkContractStorageChange(_contract, _key); ovmStateManager.putContractStorage(_contract, _key, _value); } /** * Validation whenever a contract needs to be loaded. Checks that the account exists, charges * nuisance gas if the account hasn't been loaded before. * @param _address Address of the account to load. */ function _checkAccountLoad(address _address) internal { // See `_checkContractStorageLoad` for more information. if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } // See `_checkContractStorageLoad` for more information. if (ovmStateManager.hasAccount(_address) == false) { _revertWithFlag(RevertFlag.INVALID_STATE_ACCESS); } // Check whether the account has been loaded before and mark it as loaded if not. We need // this because "nuisance gas" only applies to the first time that an account is loaded. bool _wasAccountAlreadyLoaded = ovmStateManager.testAndSetAccountLoaded( _address ); // If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based // on the size of the contract code. if (_wasAccountAlreadyLoaded == false) { _useNuisanceGas( (Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address)) * NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT ); } } /** * Validation whenever a contract needs to be changed. Checks that the account exists, charges * nuisance gas if the account hasn't been changed before. * @param _address Address of the account to change. */ function _checkAccountChange(address _address) internal { // Start by checking for a load as we only want to charge nuisance gas proportional to // contract size once. _checkAccountLoad(_address); // Check whether the account has been changed before and mark it as changed if not. We need // this because "nuisance gas" only applies to the first time that an account is changed. bool _wasAccountAlreadyChanged = ovmStateManager.testAndSetAccountChanged( _address ); // If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based // on the size of the contract code. if (_wasAccountAlreadyChanged == false) { ovmStateManager.incrementTotalUncommittedAccounts(); _useNuisanceGas( (Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address)) * NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT ); } } /** * Validation whenever a slot needs to be loaded. Checks that the account exists, charges * nuisance gas if the slot hasn't been loaded before. * @param _contract Address of the account to load from. * @param _key 32 byte key to load. */ function _checkContractStorageLoad(address _contract, bytes32 _key) internal { // Another case of hidden complexity. If we didn't enforce this requirement, then a // contract could pass in just enough gas to cause the INVALID_STATE_ACCESS check to fail // on L1 but not on L2. A contract could use this behavior to prevent the // OVM_ExecutionManager from detecting an invalid state access. Reverting with OUT_OF_GAS // allows us to also charge for the full message nuisance gas, because you deserve that for // trying to break the contract in this way. if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } // We need to make sure that the transaction isn't trying to access storage that hasn't // been provided to the OVM_StateManager. We'll immediately abort if this is the case. // We know that we have enough gas to do this check because of the above test. if (ovmStateManager.hasContractStorage(_contract, _key) == false) { _revertWithFlag(RevertFlag.INVALID_STATE_ACCESS); } // Check whether the slot has been loaded before and mark it as loaded if not. We need // this because "nuisance gas" only applies to the first time that a slot is loaded. bool _wasContractStorageAlreadyLoaded = ovmStateManager .testAndSetContractStorageLoaded(_contract, _key); // If we hadn't already loaded the account, then we'll need to charge some fixed amount of // "nuisance gas". if (_wasContractStorageAlreadyLoaded == false) { _useNuisanceGas(NUISANCE_GAS_SLOAD); } } /** * Validation whenever a slot needs to be changed. Checks that the account exists, charges * nuisance gas if the slot hasn't been changed before. * @param _contract Address of the account to change. * @param _key 32 byte key to change. */ function _checkContractStorageChange(address _contract, bytes32 _key) internal { // Start by checking for load to make sure we have the storage slot and that we charge the // "nuisance gas" necessary to prove the storage slot state. _checkContractStorageLoad(_contract, _key); // Check whether the slot has been changed before and mark it as changed if not. We need // this because "nuisance gas" only applies to the first time that a slot is changed. bool _wasContractStorageAlreadyChanged = ovmStateManager .testAndSetContractStorageChanged(_contract, _key); // If we hadn't already changed the account, then we'll need to charge some fixed amount of // "nuisance gas". if (_wasContractStorageAlreadyChanged == false) { // Changing a storage slot means that we're also going to have to change the // corresponding account, so do an account change check. _checkAccountChange(_contract); ovmStateManager.incrementTotalUncommittedContractStorage(); _useNuisanceGas(NUISANCE_GAS_SSTORE); } } /************************************ * Internal Functions: Revert Logic * ************************************/ /** * Simple encoding for revert data. * @param _flag Flag to revert with. * @param _data Additional user-provided revert data. * @return _revertdata Encoded revert data. */ function _encodeRevertData(RevertFlag _flag, bytes memory _data) internal view returns (bytes memory _revertdata) { // Out of gas and create exceptions will fundamentally return no data, so simulating it shouldn't either. if (_flag == RevertFlag.OUT_OF_GAS) { return bytes(''); } // INVALID_STATE_ACCESS doesn't need to return any data other than the flag. if (_flag == RevertFlag.INVALID_STATE_ACCESS) { return abi.encode(_flag, 0, 0, bytes('')); } // Just ABI encode the rest of the parameters. return abi.encode( _flag, messageRecord.nuisanceGasLeft, transactionRecord.ovmGasRefund, _data ); } /** * Simple decoding for revert data. * @param _revertdata Revert data to decode. * @return _flag Flag used to revert. * @return _nuisanceGasLeft Amount of nuisance gas unused by the message. * @return _ovmGasRefund Amount of gas refunded during the message. * @return _data Additional user-provided revert data. */ function _decodeRevertData(bytes memory _revertdata) internal pure returns ( RevertFlag _flag, uint256 _nuisanceGasLeft, uint256 _ovmGasRefund, bytes memory _data ) { // A length of zero means the call ran out of gas, just return empty data. if (_revertdata.length == 0) { return (RevertFlag.OUT_OF_GAS, 0, 0, bytes('')); } // ABI decode the incoming data. return abi.decode(_revertdata, (RevertFlag, uint256, uint256, bytes)); } /** * Causes a message to revert or abort. * @param _flag Flag to revert with. * @param _data Additional user-provided data. */ function _revertWithFlag(RevertFlag _flag, bytes memory _data) internal view { bytes memory revertdata = _encodeRevertData(_flag, _data); assembly { revert(add(revertdata, 0x20), mload(revertdata)) } } /** * Causes a message to revert or abort. * @param _flag Flag to revert with. */ function _revertWithFlag(RevertFlag _flag) internal { _revertWithFlag(_flag, bytes('')); } /****************************************** * Internal Functions: Nuisance Gas Logic * ******************************************/ /** * Computes the nuisance gas limit from the gas limit. * @dev This function is currently using a naive implementation whereby the nuisance gas limit * is set to exactly equal the lesser of the gas limit or remaining gas. It's likely that * this implementation is perfectly fine, but we may change this formula later. * @param _gasLimit Gas limit to compute from. * @return _nuisanceGasLimit Computed nuisance gas limit. */ function _getNuisanceGasLimit(uint256 _gasLimit) internal view returns (uint256 _nuisanceGasLimit) { return _gasLimit < gasleft() ? _gasLimit : gasleft(); } /** * Uses a certain amount of nuisance gas. * @param _amount Amount of nuisance gas to use. */ function _useNuisanceGas(uint256 _amount) internal { // Essentially the same as a standard OUT_OF_GAS, except we also retain a record of the gas // refund to be given at the end of the transaction. if (messageRecord.nuisanceGasLeft < _amount) { _revertWithFlag(RevertFlag.EXCEEDS_NUISANCE_GAS); } messageRecord.nuisanceGasLeft -= _amount; } /************************************ * Internal Functions: Gas Metering * ************************************/ /** * Checks whether a transaction needs to start a new epoch and does so if necessary. * @param _timestamp Transaction timestamp. */ function _checkNeedsNewEpoch(uint256 _timestamp) internal { if ( _timestamp >= (_getGasMetadata(GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP) + gasMeterConfig.secondsPerEpoch) ) { _putGasMetadata(GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP, _timestamp); _putGasMetadata( GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS, _getGasMetadata(GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS) ); _putGasMetadata( GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS, _getGasMetadata(GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS) ); } } /** * Validates the input values of a transaction. * @return _valid Whether or not the transaction data is valid. */ function _isValidInput(Lib_OVMCodec.Transaction memory _transaction) internal view returns (bool) { // Prevent reentrancy to run(): // This check prevents calling run with the default ovmNumber. // Combined with the first check in run(): // if (transactionContext.ovmNUMBER != DEFAULT_UINT256) { return; } // It should be impossible to re-enter since run() returns before any other call frames are created. // Since this value is already being written to storage, we save much gas compared to // using the standard nonReentrant pattern. if (_transaction.blockNumber == DEFAULT_UINT256) { return false; } if ( _isValidGasLimit(_transaction.gasLimit, _transaction.l1QueueOrigin) == false ) { return false; } return true; } /** * Validates the gas limit for a given transaction. * @param _gasLimit Gas limit provided by the transaction. * param _queueOrigin Queue from which the transaction originated. * @return _valid Whether or not the gas limit is valid. */ function _isValidGasLimit( uint256 _gasLimit, Lib_OVMCodec.QueueOrigin // _queueOrigin ) internal view returns (bool _valid) { // Always have to be below the maximum gas limit. if (_gasLimit > gasMeterConfig.maxTransactionGasLimit) { return false; } // Always have to be above the minimum gas limit. if (_gasLimit < gasMeterConfig.minTransactionGasLimit) { return false; } // TEMPORARY: Gas metering is disabled for minnet. return true; // GasMetadataKey cumulativeGasKey; // GasMetadataKey prevEpochGasKey; // if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) { // cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS; // prevEpochGasKey = GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS; // } else { // cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS; // prevEpochGasKey = GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS; // } // return ( // ( // _getGasMetadata(cumulativeGasKey) // - _getGasMetadata(prevEpochGasKey) // + _gasLimit // ) < gasMeterConfig.maxGasPerQueuePerEpoch // ); } /** * Updates the cumulative gas after a transaction. * @param _gasUsed Gas used by the transaction. * @param _queueOrigin Queue from which the transaction originated. */ function _updateCumulativeGas( uint256 _gasUsed, Lib_OVMCodec.QueueOrigin _queueOrigin ) internal { GasMetadataKey cumulativeGasKey; if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) { cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS; } else { cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS; } _putGasMetadata( cumulativeGasKey, (_getGasMetadata(cumulativeGasKey) + gasMeterConfig.minTransactionGasLimit + _gasUsed - transactionRecord.ovmGasRefund) ); } /** * Retrieves the value of a gas metadata key. * @param _key Gas metadata key to retrieve. * @return _value Value stored at the given key. */ function _getGasMetadata(GasMetadataKey _key) internal returns (uint256 _value) { return uint256( _getContractStorage(GAS_METADATA_ADDRESS, bytes32(uint256(_key))) ); } /** * Sets the value of a gas metadata key. * @param _key Gas metadata key to set. * @param _value Value to store at the given key. */ function _putGasMetadata(GasMetadataKey _key, uint256 _value) internal { _putContractStorage( GAS_METADATA_ADDRESS, bytes32(uint256(_key)), bytes32(uint256(_value)) ); } /***************************************** * Internal Functions: Execution Context * *****************************************/ /** * Swaps over to a new message context. * @param _prevMessageContext Context we're switching from. * @param _nextMessageContext Context we're switching to. */ function _switchMessageContext( MessageContext memory _prevMessageContext, MessageContext memory _nextMessageContext ) internal { // These conditionals allow us to avoid unneccessary SSTOREs. However, they do mean that the current storage // value for the messageContext MUST equal the _prevMessageContext argument, or an SSTORE might be erroneously skipped. if (_prevMessageContext.ovmCALLER != _nextMessageContext.ovmCALLER) { messageContext.ovmCALLER = _nextMessageContext.ovmCALLER; } if (_prevMessageContext.ovmADDRESS != _nextMessageContext.ovmADDRESS) { messageContext.ovmADDRESS = _nextMessageContext.ovmADDRESS; } if (_prevMessageContext.isStatic != _nextMessageContext.isStatic) { messageContext.isStatic = _nextMessageContext.isStatic; } if (_prevMessageContext.ovmCALLVALUE != _nextMessageContext.ovmCALLVALUE) { messageContext.ovmCALLVALUE = _nextMessageContext.ovmCALLVALUE; } } /** * Initializes the execution context. * @param _transaction OVM transaction being executed. */ function _initContext(Lib_OVMCodec.Transaction memory _transaction) internal { transactionContext.ovmTIMESTAMP = _transaction.timestamp; transactionContext.ovmNUMBER = _transaction.blockNumber; transactionContext.ovmTXGASLIMIT = _transaction.gasLimit; transactionContext.ovmL1QUEUEORIGIN = _transaction.l1QueueOrigin; transactionContext.ovmL1TXORIGIN = _transaction.l1TxOrigin; transactionContext.ovmGASLIMIT = gasMeterConfig.maxGasPerQueuePerEpoch; messageRecord.nuisanceGasLeft = _getNuisanceGasLimit(_transaction.gasLimit); } /** * Resets the transaction and message context. */ function _resetContext() internal { transactionContext.ovmL1TXORIGIN = DEFAULT_ADDRESS; transactionContext.ovmTIMESTAMP = DEFAULT_UINT256; transactionContext.ovmNUMBER = DEFAULT_UINT256; transactionContext.ovmGASLIMIT = DEFAULT_UINT256; transactionContext.ovmTXGASLIMIT = DEFAULT_UINT256; transactionContext.ovmL1QUEUEORIGIN = Lib_OVMCodec .QueueOrigin .SEQUENCER_QUEUE; transactionRecord.ovmGasRefund = DEFAULT_UINT256; messageContext.ovmCALLER = DEFAULT_ADDRESS; messageContext.ovmADDRESS = DEFAULT_ADDRESS; messageContext.isStatic = false; messageRecord.nuisanceGasLeft = DEFAULT_UINT256; // Reset the ovmStateManager. ovmStateManager = iOVM_StateManager(address(0)); } /****************************************** * Internal Functions: Message Typechecks * ******************************************/ /** * Returns whether or not the given message type is a CREATE-type. * @param _messageType the message type in question. */ function _isCreateType(MessageType _messageType) internal pure returns (bool) { return (_messageType == MessageType.ovmCREATE || _messageType == MessageType.ovmCREATE2); } /** * Returns whether or not the given message type (potentially) requires the transfer of ETH value along with the message. * @param _messageType the message type in question. */ function _isValueType(MessageType _messageType) internal pure returns (bool) { // ovmSTATICCALL and ovmDELEGATECALL types do not accept or transfer value. return (_messageType == MessageType.ovmCALL || _messageType == MessageType.ovmCREATE || _messageType == MessageType.ovmCREATE2); } /***************************** * L2-only Helper Functions * *****************************/ /** * Unreachable helper function for simulating eth_calls with an OVM message context. * This function will throw an exception in all cases other than when used as a custom entrypoint in L2 Geth to simulate eth_call. * @param _transaction the message transaction to simulate. * @param _from the OVM account the simulated call should be from. * @param _value the amount of ETH value to send. * @param _ovmStateManager the address of the OVM_StateManager precompile in the L2 state. */ function simulateMessage( Lib_OVMCodec.Transaction memory _transaction, address _from, uint256 _value, iOVM_StateManager _ovmStateManager ) external returns (bytes memory) { // Prevent this call from having any effect unless in a custom-set VM frame require(msg.sender == address(0)); // Initialize the EM's internal state, ignoring nuisance gas. ovmStateManager = _ovmStateManager; _initContext(_transaction); messageRecord.nuisanceGasLeft = uint256(-1); // Set the ovmADDRESS to the _from so that the subsequent call frame "comes from" them. messageContext.ovmADDRESS = _from; // Execute the desired message. bool isCreate = _transaction.entrypoint == address(0); if (isCreate) { (address created, bytes memory revertData) = ovmCREATE(_transaction.data); if (created == address(0)) { return abi.encode(false, revertData); } else { // The eth_call RPC endpoint for to = undefined will return the deployed bytecode // in the success case, differing from standard create messages. return abi.encode(true, Lib_EthUtils.getCode(created)); } } else { (bool success, bytes memory returndata) = ovmCALL( _transaction.gasLimit, _transaction.entrypoint, _value, _transaction.data ); return abi.encode(success, returndata); } } }
Retrieves the nonce of the current ovmADDRESS. return _nonce Nonce of the current contract./
function ovmGETNONCE() external override returns (uint256 _nonce) { console.log('lxd test ovmGETNONCE is touched'); return _getAccountNonce(ovmADDRESS()); }
5,528,694
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.8.10; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import './Manager.sol'; import '../interfaces/managers/IStrategyManager.sol'; import '../interfaces/aaveV2/ILendingPool.sol'; import '../interfaces/aaveV2/ILendingPoolAddressesProvider.sol'; import '../interfaces/aaveV2/IAaveIncentivesController.sol'; import '../interfaces/aaveV2/IStakeAave.sol'; import '../interfaces/aaveV2/IAToken.sol'; // This contract contains logic for depositing staker funds into Aave V2 as a yield strategy contract AaveV2Strategy is IStrategyManager, Manager { using SafeERC20 for IERC20; // Need to call a provider because Aave has the ability to change the lending pool address ILendingPoolAddressesProvider public constant LP_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); // Aave contract that controls stkAAVE rewards IAaveIncentivesController public immutable aaveIncentivesController; // This is the token being deposited (USDC) IERC20 public immutable override want; // This is the receipt token Aave gives in exchange for a token deposit (aUSDC) IAToken public immutable aWant; // Address to receive stkAAVE rewards address public immutable aaveLmReceiver; // Constructor takes the aUSDC address and the rewards receiver address (a Sherlock address) as args constructor(IAToken _aWant, address _aaveLmReceiver) { if (address(_aWant) == address(0)) revert ZeroArgument(); if (_aaveLmReceiver == address(0)) revert ZeroArgument(); aWant = _aWant; // This gets the underlying token associated with aUSDC (USDC) want = IERC20(_aWant.UNDERLYING_ASSET_ADDRESS()); // Gets the specific rewards controller for this token type aaveIncentivesController = _aWant.getIncentivesController(); aaveLmReceiver = _aaveLmReceiver; } // Returns the current Aave lending pool address that should be used function getLp() internal view returns (ILendingPool) { return ILendingPool(LP_ADDRESS_PROVIDER.getLendingPool()); } /// @notice Checks the aUSDC balance in this contract function balanceOf() public view override returns (uint256) { return aWant.balanceOf(address(this)); } /// @notice Deposits all USDC held in this contract into Aave's lending pool function deposit() external override whenNotPaused { ILendingPool lp = getLp(); // Checking the USDC balance of this contract uint256 amount = want.balanceOf(address(this)); if (amount == 0) revert InvalidConditions(); // If allowance for this contract is too low, approve the max allowance if (want.allowance(address(this), address(lp)) < amount) { want.safeIncreaseAllowance(address(lp), type(uint256).max); } // Deposits the full balance of USDC held in this contract into Aave's lending pool lp.deposit(address(want), amount, address(this), 0); } /// @notice Withdraws all USDC from Aave's lending pool back into the Sherlock core contract /// @dev Only callable by the Sherlock core contract /// @return The final amount withdrawn function withdrawAll() external override onlySherlockCore returns (uint256) { ILendingPool lp = getLp(); if (balanceOf() == 0) { return 0; } // Withdraws all USDC from Aave's lending pool and sends it to the Sherlock core contract (msg.sender) return lp.withdraw(address(want), type(uint256).max, msg.sender); } /// @notice Withdraws a specific amount of USDC from Aave's lending pool back into the Sherlock core contract /// @param _amount Amount of USDC to withdraw function withdraw(uint256 _amount) external override onlySherlockCore { // Ensures that it doesn't execute a withdrawAll() call // AAVE V2 uses uint256.max as a magic number to withdraw max amount if (_amount == type(uint256).max) revert InvalidArgument(); ILendingPool lp = getLp(); // Withdraws _amount of USDC and sends it to the Sherlock core contract // If the amount withdrawn is not equal to _amount, it reverts if (lp.withdraw(address(want), _amount, msg.sender) != _amount) revert InvalidConditions(); } // Claims the stkAAVE rewards and sends them to the receiver address function claimRewards() external whenNotPaused { // Creates an array with one slot address[] memory assets = new address[](1); // Sets the slot equal to the address of aUSDC assets[0] = address(aWant); // Claims all the rewards on aUSDC and sends them to the aaveLmReceiver (an address controlled by governance) // Tokens are NOT meant to be (directly) distributed to stakers. aaveIncentivesController.claimRewards(assets, type(uint256).max, aaveLmReceiver); } /// @notice Function used to check if this is the current active yield strategy /// @return Boolean indicating it's active /// @dev If inactive the owner can pull all ERC20s and ETH /// @dev Will be checked by calling the sherlock contract function isActive() public view returns (bool) { return address(sherlockCore.yieldStrategy()) == address(this); } // Only contract owner can call this // Sends all specified tokens in this contract to the receiver's address (as well as ETH) function sweep(address _receiver, IERC20[] memory _extraTokens) external onlyOwner { if (_receiver == address(0)) revert ZeroArgument(); // This contract must NOT be the current assigned yield strategy contract if (isActive()) revert InvalidConditions(); // Executes the sweep for ERC-20s specified in _extraTokens as well as for ETH _sweep(_receiver, _extraTokens); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.8.10; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/security/Pausable.sol'; import '../interfaces/managers/IManager.sol'; abstract contract Manager is IManager, Ownable, Pausable { using SafeERC20 for IERC20; address private constant DEPLOYER = 0x1C11bE636415973520DdDf1b03822b4e2930D94A; ISherlock internal sherlockCore; modifier onlySherlockCore() { if (msg.sender != address(sherlockCore)) revert InvalidSender(); _; } /// @notice Set sherlock core address /// @param _sherlock Current core contract /// @dev Only deployer is able to set core address on all chains except Hardhat network /// @dev One time function, will revert once `sherlock` != address(0) /// @dev This contract will be deployed first, passed on as argument in core constuctor /// @dev emits `SherlockCoreSet` function setSherlockCoreAddress(ISherlock _sherlock) external override { if (address(_sherlock) == address(0)) revert ZeroArgument(); // 31337 is of the Hardhat network blockchain if (block.chainid != 31337 && msg.sender != DEPLOYER) revert InvalidSender(); if (address(sherlockCore) != address(0)) revert InvalidConditions(); sherlockCore = _sherlock; emit SherlockCoreSet(_sherlock); } // Internal function to send tokens remaining in a contract to the receiver address function _sweep(address _receiver, IERC20[] memory _extraTokens) internal { // Loops through the extra tokens (ERC20) provided and sends all of them to the receiver address for (uint256 i; i < _extraTokens.length; i++) { IERC20 token = _extraTokens[i]; token.safeTransfer(_receiver, token.balanceOf(address(this))); } // Sends any remaining ETH to the receiver address (as long as receiver address is payable) (bool success, ) = _receiver.call{ value: address(this).balance }(''); if (success == false) revert InvalidConditions(); } function pause() external onlySherlockCore { _pause(); } function unpause() external onlySherlockCore { _unpause(); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.8.10; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import './IManager.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IStrategyManager is IManager { /// @return Returns the token type being deposited into a strategy function want() external view returns (IERC20); /// @notice Withdraws all USDC from the strategy back into the Sherlock core contract /// @dev Only callable by the Sherlock core contract /// @return The final amount withdrawn function withdrawAll() external returns (uint256); /// @notice Withdraws a specific amount of USDC from the strategy back into the Sherlock core contract /// @param _amount Amount of USDC to withdraw function withdraw(uint256 _amount) external; /// @notice Deposits all USDC held in this contract into the strategy function deposit() external; /// @return Returns the USDC balance in this contract function balanceOf() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.10; pragma experimental ABIEncoderV2; import { ILendingPoolAddressesProvider } from './ILendingPoolAddressesProvider.sol'; import { DataTypes } from './DataTypes.sol'; interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.10; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.10; pragma experimental ABIEncoderV2; import { IAaveDistributionManager } from './IAaveDistributionManager.sol'; interface IAaveIncentivesController is IAaveDistributionManager { event RewardsAccrued(address indexed user, uint256 amount); event RewardsClaimed( address indexed user, address indexed to, address indexed claimer, uint256 amount ); event ClaimerSet(address indexed user, address indexed claimer); /** * @dev Whitelists an address to claim the rewards on behalf of another address * @param user The address of the user * @param claimer The address of the claimer */ function setClaimer(address user, address claimer) external; /** * @dev Returns the whitelisted claimer for a certain address (0x0 if not set) * @param user The address of the user * @return The claimer address */ function getClaimer(address user) external view returns (address); /** * @dev Configure assets for a certain rewards emission * @param assets The assets to incentivize * @param emissionsPerSecond The emission for each asset */ function configureAssets(address[] calldata assets, uint256[] calldata emissionsPerSecond) external; /** * @dev Called by the corresponding asset on any update that affects the rewards distribution * @param asset The address of the user * @param userBalance The balance of the user of the asset in the lending pool * @param totalSupply The total supply of the asset in the lending pool **/ function handleAction( address asset, uint256 userBalance, uint256 totalSupply ) external; /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must * be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager * @param amount Amount of rewards to claim * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to ) external returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); /** * @dev for backward compatibility with previous implementation of the Incentives controller */ function REWARD_TOKEN() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.8.10; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IStakeAave is IERC20 { function cooldown() external; function claimRewards(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function getTotalRewardsBalance(address staker) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.10; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import './IAaveIncentivesController.sol'; interface IAToken is IERC20 { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param value The amount being * @param index The new liquidity index of the reserve **/ event Mint(address indexed from, uint256 value, uint256 index); /** * @dev Mints `amount` aTokens to `user` * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted after aTokens are burned * @param from The owner of the aTokens, getting them burned * @param target The address that will receive the underlying * @param value The amount being burned * @param index The new liquidity index of the reserve **/ event Burn(address indexed from, address indexed target, uint256 value, uint256 index); /** * @dev Emitted during the transfer action * @param from The user whose tokens are being transferred * @param to The recipient * @param value The amount being transferred * @param index The new liquidity index of the reserve **/ event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index); /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external; /** * @dev Mints aTokens to the reserve treasury * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external; /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external; /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param user The recipient of the underlying * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address user, uint256 amount) external returns (uint256); /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.8.10; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import '../ISherlock.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IManager { // An address or other value passed in is equal to zero (and shouldn't be) error ZeroArgument(); // Occurs when a value already holds the desired property, or is not whitelisted error InvalidArgument(); // If a required condition for executing the function is not met, it reverts and throws this error error InvalidConditions(); // Throws if the msg.sender is not the required address error InvalidSender(); event SherlockCoreSet(ISherlock sherlock); /// @notice Set sherlock core address where premiums should be send too /// @param _sherlock Current core contract /// @dev Only deployer is able to set core address on all chains except Hardhat network /// @dev One time function, will revert once `sherlock` != address(0) /// @dev This contract will be deployed first, passed on as argument in core constuctor /// @dev ^ that's needed for tvl accounting, once core is deployed this function is called /// @dev emits `SherlockCoreSet` function setSherlockCoreAddress(ISherlock _sherlock) external; /// @notice Pause external functions in contract function pause() external; /// @notice Unpause external functions in contract function unpause() external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.8.10; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import './ISherlockStake.sol'; import './ISherlockGov.sol'; import './ISherlockPayout.sol'; import './ISherlockStrategy.sol'; interface ISherlock is ISherlockStake, ISherlockGov, ISherlockPayout, ISherlockStrategy, IERC721 { // msg.sender is not authorized to call this function error Unauthorized(); // An address or other value passed in is equal to zero (and shouldn't be) error ZeroArgument(); // Occurs when a value already holds the desired property, or is not whitelisted error InvalidArgument(); // Required conditions are not true/met error InvalidConditions(); // If the SHER tokens held in a contract are not the value they are supposed to be error InvalidSherAmount(uint256 expected, uint256 actual); // Checks the ERC-721 functions _exists() to see if an NFT ID actually exists and errors if not error NonExistent(); event ArbRestaked(uint256 indexed tokenID, uint256 reward); event Restaked(uint256 indexed tokenID); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.8.10; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ /// @title Sherlock core interface for stakers /// @author Evert Kors interface ISherlockStake { /// @notice View the current lockup end timestamp of `_tokenID` /// @return Timestamp when NFT position unlocks function lockupEnd(uint256 _tokenID) external view returns (uint256); /// @notice View the current SHER reward of `_tokenID` /// @return Amount of SHER rewarded to owner upon reaching the end of the lockup function sherRewards(uint256 _tokenID) external view returns (uint256); /// @notice View the current token balance claimable upon reaching end of the lockup /// @return Amount of tokens assigned to owner when unstaking position function tokenBalanceOf(uint256 _tokenID) external view returns (uint256); /// @notice View the current TVL for all stakers /// @return Total amount of tokens staked /// @dev Adds principal + strategy + premiums /// @dev Will calculate the most up to date value for each piece function totalTokenBalanceStakers() external view returns (uint256); /// @notice Stakes `_amount` of tokens and locks up for `_period` seconds, `_receiver` will receive the NFT receipt /// @param _amount Amount of tokens to stake /// @param _period Period of time, in seconds, to lockup your funds /// @param _receiver Address that will receive the NFT representing the position /// @return _id ID of the position /// @return _sher Amount of SHER tokens to be released to this ID after `_period` ends /// @dev `_period` needs to be whitelisted function initialStake( uint256 _amount, uint256 _period, address _receiver ) external returns (uint256 _id, uint256 _sher); /// @notice Redeem NFT `_id` and receive `_amount` of tokens /// @param _id TokenID of the position /// @return _amount Amount of tokens (USDC) owed to NFT ID /// @dev Only the owner of `_id` will be able to redeem their position /// @dev The SHER rewards are sent to the NFT owner /// @dev Can only be called after lockup `_period` has ended function redeemNFT(uint256 _id) external returns (uint256 _amount); /// @notice Owner restakes position with ID: `_id` for `_period` seconds /// @param _id ID of the position /// @param _period Period of time, in seconds, to lockup your funds /// @return _sher Amount of SHER tokens to be released to owner address after `_period` ends /// @dev Only the owner of `_id` will be able to restake their position using this call /// @dev `_period` needs to be whitelisted /// @dev Can only be called after lockup `_period` has ended function ownerRestake(uint256 _id, uint256 _period) external returns (uint256 _sher); /// @notice Allows someone who doesn't own the position (an arbitrager) to restake the position for 26 weeks (ARB_RESTAKE_PERIOD) /// @param _id ID of the position /// @return _sher Amount of SHER tokens to be released to position owner on expiry of the 26 weeks lockup /// @return _arbReward Amount of tokens (USDC) sent to caller (the arbitrager) in return for calling the function /// @dev Can only be called after lockup `_period` is more than 2 weeks in the past (assuming ARB_RESTAKE_WAIT_TIME is 2 weeks) /// @dev Max 20% (ARB_RESTAKE_MAX_PERCENTAGE) of tokens associated with a position are used to incentivize arbs (x) /// @dev During a 2 week period the reward ratio will move from 0% to 100% (* x) function arbRestake(uint256 _id) external returns (uint256 _sher, uint256 _arbReward); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.8.10; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import './managers/ISherDistributionManager.sol'; import './managers/ISherlockProtocolManager.sol'; import './managers/ISherlockClaimManager.sol'; import './managers/IStrategyManager.sol'; /// @title Sherlock core interface for governance /// @author Evert Kors interface ISherlockGov { event ClaimPayout(address receiver, uint256 amount); event YieldStrategyUpdateWithdrawAllError(bytes error); event YieldStrategyUpdated(IStrategyManager previous, IStrategyManager current); event ProtocolManagerUpdated(ISherlockProtocolManager previous, ISherlockProtocolManager current); event ClaimManagerUpdated(ISherlockClaimManager previous, ISherlockClaimManager current); event NonStakerAddressUpdated(address previous, address current); event SherDistributionManagerUpdated( ISherDistributionManager previous, ISherDistributionManager current ); event StakingPeriodEnabled(uint256 period); event StakingPeriodDisabled(uint256 period); /// @notice Allows stakers to stake for `_period` of time /// @param _period Period of time, in seconds, /// @dev should revert if already enabled function enableStakingPeriod(uint256 _period) external; /// @notice Disallow stakers to stake for `_period` of time /// @param _period Period of time, in seconds, /// @dev should revert if already disabled function disableStakingPeriod(uint256 _period) external; /// @notice View if `_period` is a valid period /// @return Boolean indicating if period is valid function stakingPeriods(uint256 _period) external view returns (bool); /// @notice Update SHER distribution manager contract /// @param _sherDistributionManager New adddress of the manager function updateSherDistributionManager(ISherDistributionManager _sherDistributionManager) external; /// @notice Deletes the SHER distribution manager altogether (if Sherlock decides to no longer pay out SHER rewards) function removeSherDistributionManager() external; /// @notice Read SHER distribution manager /// @return Address of current SHER distribution manager function sherDistributionManager() external view returns (ISherDistributionManager); /// @notice Update address eligible for non staker rewards from protocol premiums /// @param _nonStakers Address eligible for non staker rewards function updateNonStakersAddress(address _nonStakers) external; /// @notice View current non stakers address /// @return Current non staker address /// @dev Is able to pull funds out of the contract function nonStakersAddress() external view returns (address); /// @notice View current address able to manage protocols /// @return Protocol manager implemenation function sherlockProtocolManager() external view returns (ISherlockProtocolManager); /// @notice Transfer protocol manager implementation address /// @param _protocolManager new implementation address function updateSherlockProtocolManager(ISherlockProtocolManager _protocolManager) external; /// @notice View current address able to pull payouts /// @return Address able to pull payouts function sherlockClaimManager() external view returns (ISherlockClaimManager); /// @notice Transfer claim manager role to different address /// @param _claimManager New address of claim manager function updateSherlockClaimManager(ISherlockClaimManager _claimManager) external; /// @notice Update yield strategy /// @param _yieldStrategy New address of the strategy /// @dev try a yieldStrategyWithdrawAll() on old, ignore failure function updateYieldStrategy(IStrategyManager _yieldStrategy) external; /// @notice Update yield strategy ignoring current state /// @param _yieldStrategy New address of the strategy /// @dev tries a yieldStrategyWithdrawAll() on old strategy, ignore failure function updateYieldStrategyForce(IStrategyManager _yieldStrategy) external; /// @notice Read current strategy /// @return Address of current strategy /// @dev can never be address(0) function yieldStrategy() external view returns (IStrategyManager); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.8.10; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ /// @title Sherlock interface for payout manager /// @author Evert Kors interface ISherlockPayout { /// @notice Initiate a payout of `_amount` to `_receiver` /// @param _receiver Receiver of payout /// @param _amount Amount to send /// @dev only payout manager should call this /// @dev should pull money out of strategy function payoutClaim(address _receiver, uint256 _amount) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.8.10; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import './managers/IStrategyManager.sol'; /// @title Sherlock core interface for yield strategy /// @author Evert Kors interface ISherlockStrategy { /// @notice Deposit `_amount` into active strategy /// @param _amount Amount of tokens /// @dev gov only function yieldStrategyDeposit(uint256 _amount) external; /// @notice Withdraw `_amount` from active strategy /// @param _amount Amount of tokens /// @dev gov only function yieldStrategyWithdraw(uint256 _amount) external; /// @notice Withdraw all funds from active strategy /// @dev gov only function yieldStrategyWithdrawAll() external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.8.10; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import './IManager.sol'; interface ISherDistributionManager is IManager { // anyone can just send token to this contract to fund rewards event Initialized(uint256 maxRewardsEndTVL, uint256 zeroRewardsStartTVL, uint256 maxRewardRate); /// @notice Caller will receive `_sher` SHER tokens based on `_amount` and `_period` /// @param _amount Amount of tokens (in USDC) staked /// @param _period Period of time for stake, in seconds /// @param _id ID for this NFT position /// @param _receiver Address that will be linked to this position /// @return _sher Amount of SHER tokens sent to Sherlock core contract /// @dev Calling contract will depend on before + after balance diff and return value /// @dev INCLUDES stake in calculation, function expects the `_amount` to be deposited already /// @dev If tvl=50 and amount=50, this means it is calculating SHER rewards for the first 50 tokens going in function pullReward( uint256 _amount, uint256 _period, uint256 _id, address _receiver ) external returns (uint256 _sher); /// @notice Calculates how many `_sher` SHER tokens are owed to a stake position based on `_amount` and `_period` /// @param _tvl TVL to use for reward calculation (pre-stake TVL) /// @param _amount Amount of tokens (USDC) staked /// @param _period Stake period (in seconds) /// @return _sher Amount of SHER tokens owed to this stake position /// @dev EXCLUDES `_amount` of stake, this will be added on top of TVL (_tvl is excluding _amount) /// @dev If tvl=0 and amount=50, it would calculate for the first 50 tokens going in (different from pullReward()) function calcReward( uint256 _tvl, uint256 _amount, uint256 _period ) external view returns (uint256 _sher); /// @notice Function used to check if this is the current active distribution manager /// @return Boolean indicating it's active /// @dev If inactive the owner can pull all ERC20s and ETH /// @dev Will be checked by calling the sherlock contract function isActive() external view returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.8.10; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import './IManager.sol'; /// @title Sherlock core interface for protocols /// @author Evert Kors interface ISherlockProtocolManager is IManager { // msg.sender is not authorized to call this function error Unauthorized(); // If a protocol was never instantiated or was removed and the claim deadline has passed, this error is returned error ProtocolNotExists(bytes32 protocol); // When comparing two arrays and the lengths are not equal (but are supposed to be equal) error UnequalArrayLength(); // If there is not enough balance in the contract for the amount requested (after any requirements are met), this is returned error InsufficientBalance(bytes32 protocol); event MinBalance(uint256 previous, uint256 current); event AccountingError(bytes32 indexed protocol, uint256 amount, uint256 insufficientTokens); event ProtocolAdded(bytes32 indexed protocol); event ProtocolRemovedByArb(bytes32 indexed protocol, address arb, uint256 profit); event ProtocolRemoved(bytes32 indexed protocol); event ProtocolUpdated( bytes32 indexed protocol, bytes32 coverage, uint256 nonStakers, uint256 coverageAmount ); event ProtocolAgentTransfer(bytes32 indexed protocol, address from, address to); event ProtocolBalanceDeposited(bytes32 indexed protocol, uint256 amount); event ProtocolBalanceWithdrawn(bytes32 indexed protocol, uint256 amount); event ProtocolPremiumChanged(bytes32 indexed protocol, uint256 oldPremium, uint256 newPremium); /// @notice View current amount of all premiums that are owed to stakers /// @return Premiums claimable /// @dev Will increase every block /// @dev base + (now - last_settled) * ps function claimablePremiums() external view returns (uint256); /// @notice Transfer current claimable premiums (for stakers) to core Sherlock address /// @dev Callable by everyone /// @dev Funds will be transferred to Sherlock core contract function claimPremiumsForStakers() external; /// @notice View current protocolAgent of `_protocol` /// @param _protocol Protocol identifier /// @return Address able to submit claims function protocolAgent(bytes32 _protocol) external view returns (address); /// @notice View current premium of protocol /// @param _protocol Protocol identifier /// @return Amount of premium `_protocol` pays per second function premium(bytes32 _protocol) external view returns (uint256); /// @notice View current active balance of covered protocol /// @param _protocol Protocol identifier /// @return Active balance /// @dev Accrued debt is subtracted from the stored active balance function activeBalance(bytes32 _protocol) external view returns (uint256); /// @notice View seconds of coverage left for `_protocol` before it runs out of active balance /// @param _protocol Protocol identifier /// @return Seconds of coverage left function secondsOfCoverageLeft(bytes32 _protocol) external view returns (uint256); /// @notice Add a new protocol to Sherlock /// @param _protocol Protocol identifier /// @param _protocolAgent Address able to submit a claim on behalf of the protocol /// @param _coverage Hash referencing the active coverage agreement /// @param _nonStakers Percentage of premium payments to nonstakers, scaled by 10**18 /// @param _coverageAmount Max amount claimable by this protocol /// @dev Adding a protocol allows the `_protocolAgent` to submit a claim /// @dev Coverage is not started yet as the protocol doesn't pay a premium at this point /// @dev `_nonStakers` is scaled by 10**18 /// @dev Only callable by governance function protocolAdd( bytes32 _protocol, address _protocolAgent, bytes32 _coverage, uint256 _nonStakers, uint256 _coverageAmount ) external; /// @notice Update info regarding a protocol /// @param _protocol Protocol identifier /// @param _coverage Hash referencing the active coverage agreement /// @param _nonStakers Percentage of premium payments to nonstakers, scaled by 10**18 /// @param _coverageAmount Max amount claimable by this protocol /// @dev Only callable by governance function protocolUpdate( bytes32 _protocol, bytes32 _coverage, uint256 _nonStakers, uint256 _coverageAmount ) external; /// @notice Remove a protocol from coverage /// @param _protocol Protocol identifier /// @dev Before removing a protocol the premium must be 0 /// @dev Removing a protocol basically stops the `_protocolAgent` from being active (can still submit claims until claim deadline though) /// @dev Pays off debt + sends remaining balance to protocol agent /// @dev This call should be subject to a timelock /// @dev Only callable by governance function protocolRemove(bytes32 _protocol) external; /// @notice Remove a protocol with insufficient active balance /// @param _protocol Protocol identifier function forceRemoveByActiveBalance(bytes32 _protocol) external; /// @notice Removes a protocol with insufficent seconds of coverage left /// @param _protocol Protocol identifier function forceRemoveBySecondsOfCoverage(bytes32 _protocol) external; /// @notice View minimal balance needed before liquidation can start /// @return Minimal balance needed function minActiveBalance() external view returns (uint256); /// @notice Sets the minimum active balance before an arb can remove a protocol /// @param _minActiveBalance Minimum balance needed (in USDC) /// @dev Only gov function setMinActiveBalance(uint256 _minActiveBalance) external; /// @notice Set premium of `_protocol` to `_premium` /// @param _protocol Protocol identifier /// @param _premium Amount of premium `_protocol` pays per second /// @dev The value 0 would mean inactive coverage /// @dev Only callable by governance function setProtocolPremium(bytes32 _protocol, uint256 _premium) external; /// @notice Set premium of multiple protocols /// @param _protocol Array of protocol identifiers /// @param _premium Array of premium amounts protocols pay per second /// @dev The value 0 would mean inactive coverage /// @dev Only callable by governance function setProtocolPremiums(bytes32[] calldata _protocol, uint256[] calldata _premium) external; /// @notice Deposits `_amount` of token to the active balance of `_protocol` /// @param _protocol Protocol identifier /// @param _amount Amount of tokens to deposit /// @dev Approval should be made before calling function depositToActiveBalance(bytes32 _protocol, uint256 _amount) external; /// @notice Withdraws `_amount` of token from the active balance of `_protocol` /// @param _protocol Protocol identifier /// @param _amount Amount of tokens to withdraw /// @dev Only protocol agent is able to withdraw /// @dev Balance can be withdrawn up until 7 days worth of active balance function withdrawActiveBalance(bytes32 _protocol, uint256 _amount) external; /// @notice Transfer protocol agent role /// @param _protocol Protocol identifier /// @param _protocolAgent Account able to submit a claim on behalf of the protocol /// @dev Only the active protocolAgent is able to transfer the role function transferProtocolAgent(bytes32 _protocol, address _protocolAgent) external; /// @notice View the amount nonstakers can claim from this protocol /// @param _protocol Protocol identifier /// @return Amount of tokens claimable by nonstakers /// @dev this reads from a storage variable + (now-lastsettled) * premiums function nonStakersClaimable(bytes32 _protocol) external view returns (uint256); /// @notice Choose an `_amount` of tokens that nonstakers (`_receiver` address) will receive from `_protocol` /// @param _protocol Protocol identifier /// @param _amount Amount of tokens /// @param _receiver Address to receive tokens /// @dev Only callable by nonstakers role function nonStakersClaim( bytes32 _protocol, uint256 _amount, address _receiver ) external; /// @param _protocol Protocol identifier /// @return current and previous are the current and previous coverage amounts for this protocol function coverageAmounts(bytes32 _protocol) external view returns (uint256 current, uint256 previous); /// @notice Function used to check if this is the current active protocol manager /// @return Boolean indicating it's active /// @dev If inactive the owner can pull all ERC20s and ETH /// @dev Will be checked by calling the sherlock contract function isActive() external view returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.8.10; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import './callbacks/ISherlockClaimManagerCallbackReceiver.sol'; import '../UMAprotocol/OptimisticRequester.sol'; import './IManager.sol'; interface ISherlockClaimManager is IManager, OptimisticRequester { // Doesn't allow a new claim to be submitted by a protocol agent if a claim is already active for that protocol error ClaimActive(); // If the current state of a claim does not match the expected state, this error is thrown error InvalidState(); event ClaimCreated( uint256 claimID, bytes32 indexed protocol, uint256 amount, address receiver, bool previousCoverageUsed ); event CallbackAdded(ISherlockClaimManagerCallbackReceiver callback); event CallbackRemoved(ISherlockClaimManagerCallbackReceiver callback); event ClaimStatusChanged(uint256 indexed claimID, State previousState, State currentState); event ClaimPayout(uint256 claimID, address receiver, uint256 amount); event ClaimHalted(uint256 claimID); event UMAHORenounced(); enum State { NonExistent, // Claim doesn't exist (this is the default state on creation) SpccPending, // Claim is created, SPCC is able to set state to valid SpccApproved, // Final state, claim is valid SpccDenied, // Claim denied by SPCC, claim can be escalated within 4 weeks UmaPriceProposed, // Price is proposed but not escalated ReadyToProposeUmaDispute, // Price is proposed, callback received, ready to submit dispute UmaDisputeProposed, // Escalation is done, waiting for confirmation UmaPending, // Claim is escalated, in case Spcc denied or didn't act within 7 days. UmaApproved, // Final state, claim is valid, claim can be enacted after 1 day, umaHaltOperator has 1 day to change to denied UmaDenied, // Final state, claim is invalid Halted, // UMAHO can halt claim if state is UmaApproved Cleaned // Claim is removed by protocol agent } struct Claim { uint256 created; uint256 updated; address initiator; bytes32 protocol; uint256 amount; address receiver; uint32 timestamp; State state; bytes ancillaryData; } // requestAndProposePriceFor() --> proposer = sherlockCore (address to receive BOND if UMA denies claim) // disputePriceFor() --> disputer = protocolAgent // priceSettled will be the the callback that contains the main data // Assume BOND = 9600, UMA's final fee = 1500. // Claim initiator (Sherlock) has to pay 22.2k to dispute a claim, // so we will execute a safeTransferFrom(claimInitiator, address(this), 22.2k). // We need to approve the contract 22.2k as it will be transferred from address(this). // The 22.2k consists of 2 * (BOND + final fee charged by UMA), as follows: // 1. On requestAndProposePriceFor(), the fee will be 10k: 9600 BOND + 1500 UMA's final fee; // 2. On disputePriceFor(), the fee will be the same 10k. // note that half of the BOND (4800) + UMA's final fee (1500) is "burnt" and sent to UMA // UMA's final fee can be changed in the future, which may result in lower or higher required staked amounts for escalating a claim. // On settle, either the protocolAgent (dispute success) or sherlockCore (dispute failure) // will receive 9600 + 4800 + 1500 = 15900. In addition, the protocolAgent will be entitled to // the claimAmount if the dispute is successful/ // lastClaimID <-- starts with 0, so initial id = 1 // have claim counter, easy to identify certain claims by their number // but use hash(callback.request.propose + callback.timestamp) as the internal UUID to handle the callbacks // So SPCC and UMAHO are hardcoded (UMAHO can be renounced) // In case these need to be updated, deploy different contract and upgrade it on the sherlock gov side. // On price proposed callback --> call disputePriceFor with callbackdata + sherlock.strategyManager() and address(this) /// @notice `SHERLOCK_CLAIM` in utf8 function UMA_IDENTIFIER() external view returns (bytes32); function sherlockProtocolClaimsCommittee() external view returns (address); /// @notice operator is able to deny approved UMA claims function umaHaltOperator() external view returns (address); /// @notice gov is able to renounce the role function renounceUmaHaltOperator() external; function claim(uint256 _claimID) external view returns (Claim memory); /// @notice Initiate a claim for a specific protocol as the protocol agent /// @param _protocol protocol ID (different from the internal or public claim ID fields) /// @param _amount amount of USDC which is being claimed by the protocol /// @param _receiver address to receive the amount of USDC being claimed /// @param _timestamp timestamp at which the exploit first occurred /// @param ancillaryData other data associated with the claim, such as the coverage agreement /// @dev The protocol agent that starts a claim will be the protocol agent during the claims lifecycle /// @dev Even if the protocol agent role is tranferred during the lifecycle function startClaim( bytes32 _protocol, uint256 _amount, address _receiver, uint32 _timestamp, bytes memory ancillaryData ) external; function spccApprove(uint256 _claimID) external; function spccRefuse(uint256 _claimID) external; /// @notice Callable by protocol agent /// @param _claimID Public claim ID /// @param _amount Bond amount sent by protocol agent /// @dev Use hardcoded USDC address /// @dev Use hardcoded bond amount /// @dev Use hardcoded liveness 7200 (2 hours) /// @dev proposedPrice = _amount function escalate(uint256 _claimID, uint256 _amount) external; /// @notice Execute claim, storage will be removed after /// @param _claimID Public ID of the claim /// @dev Needs to be SpccApproved or UmaApproved && >UMAHO_TIME /// @dev Funds will be pulled from core function payoutClaim(uint256 _claimID) external; /// @notice UMAHO is able to execute a halt if the state is UmaApproved and state was updated less than UMAHO_TIME ago function executeHalt(uint256 _claimID) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.8.10; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ interface ISherlockClaimManagerCallbackReceiver { /// @notice Calls this function on approved contracts and passes args /// @param _protocol The protocol that is receiving the payout /// @param _claimID The claim ID that is receiving the payout /// @param _amount The amount of USDC being paid out for this claim function PreCorePayoutCallback( bytes32 _protocol, uint256 _claimID, uint256 _amount ) external; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import './SkinnyOptimisticOracleInterface.sol'; /** * @title Optimistic Requester. * @notice Optional interface that requesters can implement to receive callbacks. * @dev This contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ interface OptimisticRequester { /** * @notice Callback for proposals. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param request request params after proposal. */ function priceProposed( bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, SkinnyOptimisticOracleInterface.Request memory request ) external; /** * @notice Callback for disputes. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param request request params after dispute. */ function priceDisputed( bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, SkinnyOptimisticOracleInterface.Request memory request ) external; /** * @notice Callback for settlement. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param request request params after settlement. */ function priceSettled( bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, SkinnyOptimisticOracleInterface.Request memory request ) external; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import './OptimisticOracleInterface.sol'; /** * @title Interface for the gas-cost-reduced version of the OptimisticOracle. * @notice Differences from normal OptimisticOracle: * - refundOnDispute: flag is removed, by default there are no refunds on disputes. * - customizing request parameters: In the OptimisticOracle, parameters like `bond` and `customLiveness` can be reset * after a request is already made via `requestPrice`. In the SkinnyOptimisticOracle, these parameters can only be * set in `requestPrice`, which has an expanded input set. * - settleAndGetPrice: Replaced by `settle`, which can only be called once per settleable request. The resolved price * can be fetched via the `Settle` event or the return value of `settle`. * - general changes to interface: Functions that interact with existing requests all require the parameters of the * request to modify to be passed as input. These parameters must match with the existing request parameters or the * function will revert. This change reflects the internal refactor to store hashed request parameters instead of the * full request struct. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract SkinnyOptimisticOracleInterface { event RequestPrice( address indexed requester, bytes32 indexed identifier, uint32 timestamp, bytes ancillaryData, Request request ); event ProposePrice( address indexed requester, bytes32 indexed identifier, uint32 timestamp, bytes ancillaryData, Request request ); event DisputePrice( address indexed requester, bytes32 indexed identifier, uint32 timestamp, bytes ancillaryData, Request request ); event Settle( address indexed requester, bytes32 indexed identifier, uint32 timestamp, bytes ancillaryData, Request request ); // Struct representing a price request. Note that this differs from the OptimisticOracleInterface's Request struct // in that refundOnDispute is removed. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses // to accept a price request made with ancillary data length over a certain size. uint256 public constant ancillaryBytesLimit = 8192; /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @param bond custom proposal bond to set for request. If set to 0, defaults to the final fee. * @param customLiveness custom proposal liveness to set for request. * @return totalBond default bond + final fee that the proposer and disputer will be required to pay. */ function requestPrice( bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward, uint256 bond, uint256 customLiveness ) external virtual returns (uint256 totalBond); /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param request price request parameters whose hash must match the request that the caller wants to * propose a price for. * @param proposer address to set as the proposer. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address requester, bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, Request memory request, address proposer, int256 proposedPrice ) public virtual returns (uint256 totalBond); /** * @notice Proposes a price value where caller is the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param request price request parameters whose hash must match the request that the caller wants to * propose a price for. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, Request memory request, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Combines logic of requestPrice and proposePrice while taking advantage of gas savings from not having to * overwrite Request params that a normal requestPrice() => proposePrice() flow would entail. Note: The proposer * will receive any rewards that come from this proposal. However, any bonds are pulled from the caller. * @dev The caller is the requester, but the proposer can be customized. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @param bond custom proposal bond to set for request. If set to 0, defaults to the final fee. * @param customLiveness custom proposal liveness to set for request. * @param proposer address to set as the proposer. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function requestAndProposePriceFor( bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward, uint256 bond, uint256 customLiveness, address proposer, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param request price request parameters whose hash must match the request that the caller wants to * dispute. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePriceFor( bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, Request memory request, address disputer, address requester ) public virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal where caller is the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param request price request parameters whose hash must match the request that the caller wants to * dispute. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, Request memory request ) external virtual returns (uint256 totalBond); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param request price request parameters whose hash must match the request that the caller wants to * settle. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. * @return resolvedPrice the price that the request settled to. */ function settle( address requester, bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, Request memory request ) external virtual returns (uint256 payout, int256 resolvedPrice); /** * @notice Computes the current state of a price request. See the State enum for more details. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param request price request parameters. * @return the State. */ function getState( address requester, bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, Request memory request ) external virtual returns (OptimisticOracleInterface.State); /** * @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param request price request parameters. The hash of these parameters must match with the request hash that is * associated with the price request unique ID {requester, identifier, timestamp, ancillaryData}, or this method * will revert. * @return boolean indicating true if price exists and false if not. */ function hasPrice( address requester, bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, Request memory request ) public virtual returns (bool); /** * @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute. * @param ancillaryData ancillary data of the price being requested. * @param requester sender of the initial price request. * @return the stamped ancillary bytes. */ function stampAncillaryData(bytes memory ancillaryData, address requester) public pure virtual returns (bytes memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OptimisticOracleInterface { // Struct representing the state of a price request. enum State { Invalid, // Never requested. Requested, // Requested, no other actions taken. Proposed, // Proposed, but not expired or disputed yet. Expired, // Proposed, not disputed, past liveness. Disputed, // Disputed, but no DVM price returned yet. Resolved, // Disputed and DVM price is available. Settled // Final price has been set in the contract (can get here from Expired or Resolved). } // Struct representing a price request. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. bool refundOnDispute; // True if the requester should be refunded their reward on dispute. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses // to accept a price request made with ancillary data length over a certain size. uint256 public constant ancillaryBytesLimit = 8192; /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external virtual returns (uint256 totalBond); /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external virtual returns (uint256 totalBond); /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual; /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external virtual; /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public virtual returns (uint256 totalBond); /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was value (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public virtual returns (uint256 totalBond); /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 totalBond); /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (int256); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 payout); /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (Request memory); /** * @notice Returns the state of a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State enum value. */ function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (State); /** * @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return true if price has resolved or settled, false otherwise. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (bool); function stampAncillaryData(bytes memory ancillaryData, address requester) public view virtual returns (bytes memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.10; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode { NONE, STABLE, VARIABLE } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.10; pragma experimental ABIEncoderV2; library DistributionTypes { struct AssetConfigInput { uint104 emissionPerSecond; uint256 totalStaked; address underlyingAsset; } struct UserStakeInput { address underlyingAsset; uint256 stakedByUser; uint256 totalStaked; } } interface IAaveDistributionManager { event AssetConfigUpdated(address indexed asset, uint256 emission); event AssetIndexUpdated(address indexed asset, uint256 index); event UserIndexUpdated(address indexed user, address indexed asset, uint256 index); event DistributionEndUpdated(uint256 newDistributionEnd); /** * @dev Sets the end date for the distribution * @param distributionEnd The end date timestamp **/ function setDistributionEnd(uint256 distributionEnd) external; /** * @dev Gets the end date for the distribution * @return The end of the distribution **/ function getDistributionEnd() external view returns (uint256); /** * @dev for backwards compatibility with the previous DistributionManager used * @return The end of the distribution **/ function DISTRIBUTION_END() external view returns (uint256); /** * @dev Returns the data of an user on a distribution * @param user Address of the user * @param asset The address of the reference asset of the distribution * @return The new index **/ function getUserAssetData(address user, address asset) external view returns (uint256); /** * @dev Returns the configuration of the distribution for a certain asset * @param asset The address of the reference asset of the distribution * @return The asset index, the emission per second and the last updated timestamp **/ function getAssetData(address asset) external view returns ( uint256, uint256, uint256 ); }
Sherlock core interface for governance Evert Kors
interface ISherlockGov { event ClaimPayout(address receiver, uint256 amount); event YieldStrategyUpdateWithdrawAllError(bytes error); event YieldStrategyUpdated(IStrategyManager previous, IStrategyManager current); event ProtocolManagerUpdated(ISherlockProtocolManager previous, ISherlockProtocolManager current); event ClaimManagerUpdated(ISherlockClaimManager previous, ISherlockClaimManager current); event NonStakerAddressUpdated(address previous, address current); event SherDistributionManagerUpdated( ISherDistributionManager previous, ISherDistributionManager current ); event StakingPeriodEnabled(uint256 period); event StakingPeriodDisabled(uint256 period); function enableStakingPeriod(uint256 _period) external; function disableStakingPeriod(uint256 _period) external; function stakingPeriods(uint256 _period) external view returns (bool); function updateSherDistributionManager(ISherDistributionManager _sherDistributionManager) external; function removeSherDistributionManager() external; function sherDistributionManager() external view returns (ISherDistributionManager); function updateNonStakersAddress(address _nonStakers) external; function nonStakersAddress() external view returns (address); function sherlockProtocolManager() external view returns (ISherlockProtocolManager); function updateSherlockProtocolManager(ISherlockProtocolManager _protocolManager) external; function sherlockClaimManager() external view returns (ISherlockClaimManager); function updateSherlockClaimManager(ISherlockClaimManager _claimManager) external; function updateYieldStrategy(IStrategyManager _yieldStrategy) external; function updateYieldStrategyForce(IStrategyManager _yieldStrategy) external; function yieldStrategy() external view returns (IStrategyManager); } pragma solidity 0.8.10; }
1,145,863
pragma solidity ^0.4.24; import "./Owned.sol"; import "./Stash.sol"; import "./StashFactory.sol"; import "./RedeemAgent.sol"; import "./PledgeAgent.sol"; contract Bank is Owned {// Regulator node (MAS) should be the owner function Bank() { owner = msg.sender; } StashFactory public sf; RedeemAgent public redeemAgent; PledgeAgent public pledgeAgent; function setExternalContracts(address _sf, address _pa, address _ra) onlyOwner { sf = StashFactory(_sf); pledgeAgent = PledgeAgent(_pa); redeemAgent = RedeemAgent(_ra); } /* salt tracking */ bytes16 public currentSalt; // used to retrieve shielded balance bytes16 public nettingSalt; // used to cache result salt after LSM calculation mapping(address => bytes32) public acc2stash; // @pseudo-public function registerStash(address _acc, string _stashName) onlyOwner { _registerStash(_acc, stringToBytes32(_stashName)); } function _registerStash(address _acc, bytes32 _stashName) onlyOwner { acc2stash[_acc] = _stashName; } function getStash(address _acc) view returns (string){ return bytes32ToString(_getStash(_acc)); } function _getStash(address _acc) view returns (bytes32){ return acc2stash[_acc]; } /* @pseudo-public during LSM / confirming pmt: banks and cb will call this to set their current salt @private for: [pledger] during pledge / redeem: MAS-regulator / cb will invoke this function */ function setCurrentSalt(bytes16 _salt) { bytes32 _stashName = acc2stash[msg.sender]; require(checkOwnedStash(_stashName), "not owned stash"); // non-owner will not update salt if (acc2stash[msg.sender] != centralBank) {// when banks are setting salt, cb should not update its salt require(msg.sender == owner || !isCentralBankNode()); // unless it invoked by MAS-regulator } else { require(isCentralBankNode()); // when cb are setting salt, banks should not update its salt } currentSalt = _salt; } /* @pseudo-public */ function setNettingSalt(bytes16 _salt) { bytes32 _stashName = acc2stash[msg.sender]; require(checkOwnedStash(_stashName), "not owned stash"); // non-owner will not update salt if (acc2stash[msg.sender] != centralBank) {// when banks are setting salt, cb should not update its salt require(msg.sender == owner || !isCentralBankNode()); // unless it invoked by MAS-regulator } else { require(isCentralBankNode()); // when cb are setting salt, banks should not update its salt } nettingSalt = _salt; } function updateCurrentSalt2NettingSalt() external { currentSalt = nettingSalt; } function updateCurrentSalt(bytes16 salt) external { currentSalt = salt; } // @pseudo-public, all the banks besides cb will not execute this action function setCentralBankCurrentSalt(bytes16 _salt) onlyCentralBank { if (isCentralBankNode()) { currentSalt = _salt; } } function getCurrentSalt() view returns (bytes16) { require(msg.sender == owner || checkOwnedStash(acc2stash[msg.sender])); return currentSalt; } /* set up central bank */ bytes32 public centralBank; function setCentralBank(bytes32 _stashName) onlyOwner { centralBank = _stashName; } modifier onlyCentralBank() {require(acc2stash[msg.sender] == centralBank); _;} /* Suspend bank / stash */ mapping(bytes32 => bool) public suspended; function suspendStash(bytes32 _stashName) onlyOwner { suspended[_stashName] = true; } function unSuspendStash(bytes32 _stashName) onlyOwner { suspended[_stashName] = false; } function isSuspended(bytes32 _stashName) external returns (bool){ return suspended[_stashName]; } //modifier notSuspended(bytes32 _stashName) { require(suspended[_stashName] == false); _; } event statusCode(int errorCode); // statusCode added to handle returns upon exceptions - Laks function emitStatusCode(int errorCode){ emit statusCode(errorCode); } // workaround to handle exception as require/throw do not return errors - need to refactor - Laks modifier notSuspended(bytes32 _stashName) { if (suspended[_stashName]) { emitStatusCode(100); return; } _; } /* @live: privateFor == MAS and owner node This method is set to onlyonwer as pledge include off-chain process */ function pledge(bytes32 _txRef, bytes32 _stashName, int _amount) // onlyCentralBank notSuspended(_stashName) { if (_stashName != centralBank || isCentralBankNode()) { sf.credit(_stashName, _amount); pledgeAgent.pledge(_txRef, _stashName, _amount); } } /* @live: privateFor = MAS and owner node */ function redeem(bytes32 _txRef, bytes32 _stashName, int _amount) //onlyCentralBank notSuspended(_stashName) { if (_stashName != centralBank || isCentralBankNode()) { sf.debit(_stashName, _amount); redeemAgent.redeem(_txRef, _stashName, _amount); } } function checkOwnedStash(bytes32 _stashName) view private returns (bool){ return sf.checkOwnedStash(_stashName, msg.sender); } function getOwnedStash() view returns (bytes32) { if (isCentralBankNode()) return centralBank; return sf.getOwnedStash(); } // Central bank controls all the stashes function isCentralBankNode() view returns (bool) { return sf.isCentralBankNode(); } function clear() external { } }
Central bank controls all the stashes
function isCentralBankNode() view returns (bool) { return sf.isCentralBankNode(); }
13,102,813
./partial_match/5/0x7106619Bb2c60ab9d4DAF5FC4941d46cba6Aa4Ed/sources/OOF.sol
Calculates floor(x y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 with further edits by Uniswap Labs also under MIT license./ 512-bit multiply [prod1 prod0] = x y. Compute the product mod 2^256 and mod 2^256 - 1, then use use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 variables such that product = prod1 2^256 + prod0. Handle non-overflow cases, 256 by 256 division. Compute remainder using mulmod. Subtract 256 bit number from 512 bit number. Divide denominator by twos. Divide [prod1 prod0] by twos. Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { unchecked { assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } if (prod1 == 0) { return prod0 / denominator; } assembly { remainder := mulmod(x, y, denominator) prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } assembly { denominator := div(denominator, twos) prod0 := div(prod0, twos) twos := add(div(sub(0, twos), twos), 1) } return result; } }
16,847,089
// SPDX-License-Identifier: UNLICENSED /* $$$$$$$\ $$\ $$\ $$\ $$\ $$$$$$$$\ $$\ $$ __$$\ $$ | $$ | \__| $$ | $$ _____|\__| $$ | $$ | $$$$$$\ $$$$$$$\ $$$$$$$\ $$\ $$$$$$\ $$ | $$\ $$$$$$$\ $$$$$$\ $$$$$$$\ $$$$$$$\ $$$$$$\ $$$$$$$ | \____$$\ $$ __$$\ $$ __$$\ $$ |\_$$ _| $$$$$\ $$ |$$ __$$\ \____$$\ $$ __$$\ $$ _____|$$ __$$\ $$ __$$< $$$$$$$ |$$ | $$ |$$ | $$ |$$ | $$ | $$ __| $$ |$$ | $$ | $$$$$$$ |$$ | $$ |$$ / $$$$$$$$ | $$ | $$ |$$ __$$ |$$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ | $$ |$$ | $$ |$$ __$$ |$$ | $$ |$$ | $$ ____| $$ | $$ |\$$$$$$$ |$$$$$$$ |$$$$$$$ |$$ | \$$$$ | $$ | $$ |$$ | $$ |\$$$$$$$ |$$ | $$ |\$$$$$$$\ \$$$$$$$\ \__| \__| \_______|\_______/ \_______/ \__| \____/ \__| \__|\__| \__| \_______|\__| \__| \_______| \_______| RabbitFinance.io */ pragma solidity ^0.6.0; // Part: BankConfig interface BankConfig { function getInterestRate(uint256 debt, uint256 floating) external view returns (uint256); function getReserveBps() external view returns (uint256); function getLiquidateBps() external view returns (uint256); function isStable(address goblin) external view returns (bool); } // Part: ERC20Interface interface ERC20Interface { function balanceOf(address user) external view returns (uint); } // Part: Goblin interface Goblin { /// @dev Work on a (potentially new) position. Optionally send surplus token back to Bank. function work(uint256 id, address user, address borrowToken, uint256 borrow, uint256 debt, bytes calldata data) external payable; /// @dev Return the amount of ETH wei to get back if we are to liquidate the position. function health(uint256 id, address borrowToken) external view returns (uint256); /// @dev Liquidate the given position to token need. Send all ETH back to Bank. function liquidate(uint256 id, address user, address borrowToken) external; } // Part: Initializable /** * @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. */ 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) { // 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); uint cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { 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; } } // Part: Governable contract Governable is Initializable { address public governor; // The current governor. address public pendingGovernor; // The address pending to become the governor once accepted. modifier onlyGov() { require(msg.sender == governor, 'not the governor'); _; } /// @dev Initialize the bank smart contract, using msg.sender as the first governor. function __Governable__init() internal initializer { governor = msg.sender; pendingGovernor = address(0); } /// @dev Set the pending governor, which will be the governor once accepted. /// @param _pendingGovernor The address to become the pending governor. function setPendingGovernor(address _pendingGovernor) external onlyGov { pendingGovernor = _pendingGovernor; } /// @dev Accept to become the new governor. Must be called by the pending governor. function acceptGovernor() external { require(msg.sender == pendingGovernor, 'not the pending governor'); pendingGovernor = address(0); governor = msg.sender; } } // Part: OpenZeppelin/[email protected]/ERC20 /** * @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() override public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) override 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) override public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) override 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) override 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) override 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)); } } // Part: ReentrancyGuardUpgradeSafe /** * @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. */ contract ReentrancyGuardUpgradeSafe is Initializable { // counter to allow mutex lock with only one SSTORE operation uint private _guardCounter; function __ReentrancyGuardUpgradeSafe__init() internal initializer { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint localCounter = _guardCounter; _; require(localCounter == _guardCounter, 'ReentrancyGuard: reentrant call'); } uint[50] private ______gap; } // Part: SafeToken library SafeToken { function myBalance(address token) internal view returns (uint256) { return ERC20Interface(token).balanceOf(address(this)); } function balanceOf(address token, address user) internal view returns (uint256) { return ERC20Interface(token).balanceOf(user); } function safeApprove(address token, address to, uint256 value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "!safeApprove"); } function safeTransfer(address token, address to, uint256 value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "!safeTransfer"); } function safeTransferFrom(address token, address from, address to, uint256 value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "!safeTransferFrom"); } function safeTransferETH(address to, uint256 val) internal { (bool success, ) = to.call{value:val}(new bytes(0)); require(success, "!safeTransferETH"); } } 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. * * 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; } } pragma solidity ^0.6.0; contract IBToken is ERC20, Ownable { using SafeToken for address; using SafeMath for uint256; string public name = ""; string public symbol = ""; uint8 public decimals = 18; event Mint(address sender, address account, uint amount); event Burn(address sender, address account, uint amount); constructor(string memory _symbol) public { name = _symbol; symbol = _symbol; } function mint(address account, uint256 amount) public onlyOwner { _mint(account, amount); emit Mint(msg.sender, account, amount); } function burn(address account, uint256 value) public onlyOwner { _burn(account, value); emit Burn(msg.sender, account, value); } } contract IBTokenFactory { function genIBToken(string memory _symbol) public returns(address) { return address(new IBToken(_symbol)); } } pragma experimental ABIEncoderV2; contract Bank is Initializable, ReentrancyGuardUpgradeSafe, Governable,IBTokenFactory { /// @notice Libraries using SafeToken for address; using SafeMath for uint; /// @notice Events event AddDebt(uint indexed id, uint debtShare); event RemoveDebt(uint indexed id, uint debtShare); event Work(uint256 indexed id, uint256 debt, uint back); event Kill(uint256 indexed id, address indexed killer, uint256 prize, uint256 left); uint256 constant GLO_VAL = 10000; struct TokenBank { address tokenAddr; address ibTokenAddr; bool isOpen; bool canDeposit; bool canWithdraw; uint256 totalVal; uint256 totalDebt; uint256 totalDebtShare; uint256 totalReserve; uint256 lastInterestTime; } struct Production { address coinToken; address currencyToken; address borrowToken; bool isOpen; bool canBorrow; address goblin; uint256 minDebt; uint256 maxDebt; uint256 openFactor; uint256 liquidateFactor; } struct Position { address owner; uint256 productionId; uint256 debtShare; } BankConfig public config; mapping(address => TokenBank) public banks; mapping(uint256 => Production) public productions; uint256 public currentPid; mapping(uint256 => Position) public positions; uint256 public currentPos; mapping(address => uint256[]) public userPosition; struct Pos{ uint256 posid; address token0; address token1; address borrowToken; uint256 positionsValue; uint256 totalValue; address goblin; } mapping(address => bool) public killWhitelist; address public devAddr; function initialize(BankConfig _config) external initializer { __Governable__init(); __ReentrancyGuardUpgradeSafe__init(); config = _config; currentPid = 1; currentPos = 1; } /// @dev Require that the caller must be an EOA account to avoid flash loans. modifier onlyEOA() { require(msg.sender == tx.origin, 'not eoa'); _; } function getUserPosition(address user) view external returns(Pos[] memory){ uint256[] memory userPos = userPosition[user]; Pos[] memory p = new Pos[](userPos.length); for (uint256 i = 0;i<userPos.length;i++){ p[i] = getPos(userPos[i]); } return p; } function getAllPosition()view external returns(Pos[] memory){ Pos[] memory p = new Pos[](currentPos); uint256 index; for (uint256 i = 0;i<p.length;i++){ if(positions[i+1].debtShare > 0){ p[index] = getPos(i+1); index = index.add(1); } } return p; } function getPos(uint256 posid) view internal returns(Pos memory){ Position memory pos = positions[posid]; Production memory pro = productions[pos.productionId]; (, uint256 asset, uint256 loan, ) = positionInfo(posid); return Pos({ posid:posid, token0:pro.coinToken, token1:pro.currencyToken, borrowToken:pro.borrowToken, positionsValue:asset, totalValue:loan, goblin:pro.goblin }); } /// @dev Return the BNB debt value given the debt share. Be careful of unaccrued interests. /// @param debtShare The debt share to be converted. function debtShareToVal(address token, uint256 debtShare) public view returns (uint256) { TokenBank storage bank = banks[token]; require(bank.isOpen, 'token not exists'); if (bank.totalDebtShare == 0) return debtShare; return debtShare.mul(bank.totalDebt).div(bank.totalDebtShare); } /// @dev Return the debt share for the given debt value. Be careful of unaccrued interests. /// @param debtVal The debt value to be converted. function debtValToShare(address token, uint256 debtVal) public view returns (uint256) { TokenBank storage bank = banks[token]; require(bank.isOpen, 'token not exists'); if (bank.totalDebt == 0) return debtVal; return debtVal.mul(bank.totalDebtShare).div(bank.totalDebt); } function totalToken(address token) public view returns (uint256) { TokenBank storage bank = banks[token]; require(bank.isOpen, 'token not exists'); uint balance = token == address(0) ? address(this).balance : SafeToken.myBalance(token); balance = bank.totalVal < balance? bank.totalVal: balance; return balance.add(bank.totalDebt).sub(bank.totalReserve); } function positionInfo(uint256 posId) public view returns (uint256, uint256, uint256, address) { Position storage pos = positions[posId]; Production storage prod = productions[pos.productionId]; return (pos.productionId, Goblin(prod.goblin).health(posId, prod.borrowToken), debtShareToVal(prod.borrowToken, pos.debtShare), pos.owner); } function deposit(address token, uint256 amount) external payable nonReentrant { TokenBank storage bank = banks[token]; require(bank.isOpen && bank.canDeposit, 'Token not exist or cannot deposit'); calInterest(token); if (token == address(0)) { amount = msg.value; } else { SafeToken.safeTransferFrom(token, msg.sender, address(this), amount); } bank.totalVal = bank.totalVal.add(amount); uint256 total = totalToken(token).sub(amount); uint256 ibTotal = IBToken(bank.ibTokenAddr).totalSupply(); uint256 ibAmount = (total == 0 || ibTotal == 0) ? amount: amount.mul(ibTotal).div(total); IBToken(bank.ibTokenAddr).mint(msg.sender, ibAmount); } function withdraw(address token, uint256 pAmount) external nonReentrant { TokenBank storage bank = banks[token]; require(bank.isOpen && bank.canWithdraw, 'Token not exist or cannot withdraw'); calInterest(token); uint256 amount = pAmount.mul(totalToken(token)).div(IBToken(bank.ibTokenAddr).totalSupply()); bank.totalVal = bank.totalVal.sub(amount); IBToken(bank.ibTokenAddr).burn(msg.sender, pAmount); if (token == address(0)) { SafeToken.safeTransferETH(msg.sender, amount); } else { SafeToken.safeTransfer(token, msg.sender, amount); } } function work(uint256 posId, uint256 pid, uint256 borrow, bytes calldata data) external payable onlyEOA nonReentrant { if (posId == 0) { posId = currentPos; currentPos ++; positions[posId].owner = msg.sender; positions[posId].productionId = pid; positions[posId].debtShare = 0; userPosition[msg.sender].push(posId); } else { require(posId < currentPos, "bad position id"); require(positions[posId].owner == msg.sender, "not position owner"); pid = positions[posId].productionId; } Production storage production = productions[pid]; require(production.isOpen, 'Production not exists'); require(borrow == 0 || production.canBorrow, "Production can not borrow"); calInterest(production.borrowToken); uint256 debt = _removeDebt(posId, production).add(borrow); bool isBorrowBNB = production.borrowToken == address(0); uint256 sendBNB = msg.value; uint256 beforeToken = 0; if (isBorrowBNB) { sendBNB = sendBNB.add(borrow); require(sendBNB <= address(this).balance && debt <= banks[production.borrowToken].totalVal, "insufficient BNB in the bank"); beforeToken = address(this).balance.sub(sendBNB); } else { beforeToken = SafeToken.myBalance(production.borrowToken); require(borrow <= beforeToken && debt <= banks[production.borrowToken].totalVal, "insufficient borrowToken in the bank"); beforeToken = beforeToken.sub(borrow); SafeToken.safeApprove(production.borrowToken, production.goblin, borrow); } Goblin(production.goblin).work{value:sendBNB}(posId, msg.sender, production.borrowToken, borrow, debt, data); uint256 backToken = isBorrowBNB? (address(this).balance.sub(beforeToken)) : SafeToken.myBalance(production.borrowToken).sub(beforeToken); if(backToken > debt) { backToken = backToken.sub(debt); debt = 0; isBorrowBNB? SafeToken.safeTransferETH(msg.sender, backToken): SafeToken.safeTransfer(production.borrowToken, msg.sender, backToken); }else if (debt > backToken) { debt = debt.sub(backToken); backToken = 0; require(debt >= production.minDebt && debt <= production.maxDebt, "Debt scale is out of scope"); uint256 health = Goblin(production.goblin).health(posId, production.borrowToken); require(config.isStable(production.goblin),"!goblin"); require(health.mul(production.openFactor) >= debt.mul(GLO_VAL), "bad work factor"); _addDebt(posId, production, debt); } emit Work(posId, debt, backToken); } function kill(uint256 posId) external payable onlyEOA nonReentrant { require(killWhitelist[msg.sender],"Not Whitelist"); Position storage pos = positions[posId]; require(pos.debtShare > 0, "no debt"); Production storage production = productions[pos.productionId]; uint256 debt = _removeDebt(posId, production); uint256 health = Goblin(production.goblin).health(posId, production.borrowToken); require(config.isStable(production.goblin),"!goblin"); require(health.mul(production.liquidateFactor) < debt.mul(GLO_VAL), "can't liquidate"); bool isBNB = production.borrowToken == address(0); uint256 before = isBNB? address(this).balance: SafeToken.myBalance(production.borrowToken); Goblin(production.goblin).liquidate(posId, pos.owner, production.borrowToken); uint256 back = isBNB? address(this).balance: SafeToken.myBalance(production.borrowToken); back = back.sub(before); uint256 prize = back.mul(config.getLiquidateBps()).div(GLO_VAL); uint256 rest = back.sub(prize); uint256 left = 0; if (prize > 0) { isBNB? SafeToken.safeTransferETH(devAddr, prize): SafeToken.safeTransfer(production.borrowToken, devAddr, prize); } if (rest > debt) { left = rest.sub(debt); isBNB? SafeToken.safeTransferETH(pos.owner, left): SafeToken.safeTransfer(production.borrowToken, pos.owner, left); } else { banks[production.borrowToken].totalVal = banks[production.borrowToken].totalVal.sub(debt).add(rest); } emit Kill(posId, msg.sender, prize, left); } function _addDebt(uint256 posId, Production storage production, uint256 debtVal) internal { if (debtVal == 0) { return; } TokenBank storage bank = banks[production.borrowToken]; Position storage pos = positions[posId]; uint256 debtShare = debtValToShare(production.borrowToken, debtVal); pos.debtShare = pos.debtShare.add(debtShare); bank.totalVal = bank.totalVal.sub(debtVal); bank.totalDebtShare = bank.totalDebtShare.add(debtShare); bank.totalDebt = bank.totalDebt.add(debtVal); emit AddDebt(posId, debtShare); } function _removeDebt(uint256 posId, Production storage production) internal returns (uint256) { TokenBank storage bank = banks[production.borrowToken]; Position storage pos = positions[posId]; uint256 debtShare = pos.debtShare; if (debtShare > 0) { uint256 debtVal = debtShareToVal(production.borrowToken, debtShare); pos.debtShare = 0; bank.totalVal = bank.totalVal.add(debtVal); bank.totalDebtShare = bank.totalDebtShare.sub(debtShare); bank.totalDebt = bank.totalDebt.sub(debtVal); emit RemoveDebt(posId, debtShare); return debtVal; } else { return 0; } } function updateConfig(BankConfig _config) external onlyGov { config = _config; } function addBank(address token, string calldata _symbol) external onlyGov { TokenBank storage bank = banks[token]; require(!bank.isOpen, 'token already exists'); bank.isOpen = true; address ibToken = genIBToken(_symbol); bank.tokenAddr = token; bank.ibTokenAddr = ibToken; bank.canDeposit = true; bank.canWithdraw = true; bank.totalVal = 0; bank.totalDebt = 0; bank.totalDebtShare = 0; bank.totalReserve = 0; bank.lastInterestTime = now; } function createProduction( uint256 pid, bool isOpen, bool canBorrow, address coinToken, address currencyToken, address borrowToken, address goblin, uint256 minDebt, uint256 maxDebt, uint256 openFactor, uint256 liquidateFactor ) external onlyGov { if(pid == 0){ pid = currentPid; currentPid ++; } else { require(pid < currentPid, "bad production id"); } Production storage production = productions[pid]; production.isOpen = isOpen; production.canBorrow = canBorrow; production.coinToken = coinToken; production.currencyToken = currencyToken; production.borrowToken = borrowToken; production.goblin = goblin; production.minDebt = minDebt; production.maxDebt = maxDebt; production.openFactor = openFactor; production.liquidateFactor = liquidateFactor; } function calInterest(address token) public { TokenBank storage bank = banks[token]; require(bank.isOpen, 'token not exists'); if (now > bank.lastInterestTime) { uint256 timePast = now.sub(bank.lastInterestTime); uint256 totalDebt = bank.totalDebt; uint256 totalBalance = totalToken(token); uint256 ratePerSec = config.getInterestRate(totalDebt, totalBalance); uint256 interest = ratePerSec.mul(timePast).mul(totalDebt).div(1e18); uint256 toReserve = interest.mul(config.getReserveBps()).div(GLO_VAL); bank.totalReserve = bank.totalReserve.add(toReserve); bank.totalDebt = bank.totalDebt.add(interest); bank.lastInterestTime = now; } } function withdrawReserve(address token, address to, uint256 value) external onlyGov nonReentrant { TokenBank storage bank = banks[token]; require(bank.isOpen, 'token not exists'); uint balance = token == address(0)? address(this).balance: SafeToken.myBalance(token); if(balance >= bank.totalVal.add(value)) { } else { bank.totalReserve = bank.totalReserve.sub(value); } if (token == address(0)) { SafeToken.safeTransferETH(to, value); } else { SafeToken.safeTransfer(token, to, value); } } function ibTokenCalculation(address token, uint256 amount) view external returns(uint256){ TokenBank memory bank = banks[token]; uint256 total = totalToken(token).sub(amount); uint256 ibTotal = IBToken(bank.ibTokenAddr).totalSupply(); return (total == 0 || ibTotal == 0) ? amount: amount.mul(ibTotal).div(total); } function createkillWhitelist(address addr,bool status) external onlyGov { require(addr != address(0)); killWhitelist[addr] = status; } function setDevAddr(address addr) external onlyGov{ require(addr != address(0)); devAddr = addr; } receive() external payable {} }
See `IERC20.approve`. Requirements: - `spender` cannot be the zero address./
function approve(address spender, uint256 value) override public returns (bool) { _approve(msg.sender, spender, value); return true; }
7,242,168
./full_match/43113/0x30F86EF7DE7970d01fb81cB7c4Ef73230DBAD984/sources/contracts/test.sol
require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
function tokenURI(uint256 tokenId) public view override returns (string memory) { if (!_exists(tokenId)) { return notRevealedUri; } if (revealed == false) { return notRevealedUri; } return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), baseExtension)) : ""; }
7,205,960
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; library ECStructs { struct ECDSASig { uint8 v; bytes32 r; bytes32 s; } } contract ILotteryForCoke { struct Ticket { address payable ticketAddress; uint256 period; address payable buyer; uint256 amount; uint256 salt; } function buy(Ticket memory ticket, ECStructs.ECDSASig memory serverSig) public returns (bool); function calcTicketPrice(Ticket memory ticket) public view returns (uint256 cokeAmount); } contract IPledgeForCoke { struct DepositRequest { address payable depositAddress; address payable from; uint256 cokeAmount; uint256 endBlock; bytes32 billSeq; bytes32 salt; } //the buyer should approve enough coke and then call this function //or use 'approveAndCall' in Coke.sol in 1 request function deposit(DepositRequest memory request, ECStructs.ECDSASig memory ecdsaSig) payable public returns (bool); function depositCheck(DepositRequest memory request, ECStructs.ECDSASig memory ecdsaSig) public view returns (uint256); } library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath, mul"); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath, div"); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath, sub"); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath, add"); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath, mod"); return a % b; } } contract IRequireUtils { function requireCode(uint256 code) external pure; function interpret(uint256 code) public pure returns (string memory); } interface IERC20 { 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 ); } contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor() internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "nonReentrant"); } } contract ERC20 is IERC20, ReentrancyGuard { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0), "ERC20 approve, spender can not be 0x00"); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } //be careful, this is 'internal' function, //you must add control permission to manipulate this function function approveFrom(address owner, address spender, uint256 value) internal returns (bool) { require(spender != address(0), "ERC20 approveFrom, spender can not be 0x00"); _allowed[owner][spender] = value; emit Approval(owner, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _allowed[from][msg.sender], "ERC20 transferFrom, allowance not enough"); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0), "ERC20 increaseAllowance, spender can not be 0x00"); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0), "ERC20 decreaseAllowance, spender can not be 0x00"); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from], "ERC20 _transfer, not enough balance"); require(to != address(0), "ERC20 _transfer, to address can not be 0x00"); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0), "ERC20 _mint, account can not be 0x00"); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20 _burn, account can not be 0x00"); require(value <= _balances[account], "ERC20 _burn, not enough balance"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender], "ERC20 _burnFrom, allowance not enough"); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } contract Coke is ERC20{ using SafeMath for uint256; IRequireUtils rUtils; //1 Coke = 10^18 Tin string public name = "COKE"; string public symbol = "COKE"; uint256 public decimals = 18; //1:1 address public cokeAdmin;// admin has rights to mint and burn and etc. mapping(address => bool) public gameMachineRecords;// game machine has permission to mint coke uint256 public stagePercent; uint256 public step; uint256 public remain; uint256 public currentDifficulty;//starts from 0 uint256 public currentStageEnd; address team; uint256 public teamRemain; uint256 public unlockAllBlockNumber; uint256 unlockNumerator; uint256 unlockDenominator; event Reward(address indexed account, uint256 amount, uint256 rawAmount); event UnlockToTeam(address indexed account, uint256 amount, uint256 rawReward); constructor (IRequireUtils _rUtils, address _cokeAdmin, uint256 _cap, address _team, uint256 _toTeam, uint256 _unlockAllBlockNumber, address _bounty, uint256 _toBounty, uint256 _stagePercent, uint256 _unlockNumerator, uint256 _unlockDenominator) /*ERC20Capped(_cap) */public { rUtils = _rUtils; cokeAdmin = _cokeAdmin; unlockAllBlockNumber = _unlockAllBlockNumber; team = _team; teamRemain = _toTeam; _mint(address(this), _toTeam); _mint(_bounty, _toBounty); stagePercent = _stagePercent; step = _cap * _stagePercent / 100; remain = _cap.sub(_toTeam).sub(_toBounty); _mint(address(this), remain); unlockNumerator = _unlockNumerator; unlockDenominator=_unlockDenominator; if (remain - step > 0) { currentStageEnd = remain - step; } else { currentStageEnd = 0; } currentDifficulty = 0; } function approveAndCall(address spender, uint256 value, bytes memory data) public nonReentrant returns (bool) { require(approve(spender, value)); (bool success, bytes memory returnData) = spender.call(data); rUtils.requireCode(success ? 0 : 501); return true; } function approveAndBuyLottery(ILotteryForCoke.Ticket memory ticket, ECStructs.ECDSASig memory serverSig) public nonReentrant returns (bool){ rUtils.requireCode(approve(ticket.ticketAddress, ILotteryForCoke(ticket.ticketAddress).calcTicketPrice(ticket)) ? 0 : 506); rUtils.requireCode(ILotteryForCoke(ticket.ticketAddress).buy(ticket, serverSig) ? 0 : 507); return true; } function approveAndPledgeCoke(IPledgeForCoke.DepositRequest memory depositRequest, ECStructs.ECDSASig memory serverSig) public nonReentrant returns (bool){ rUtils.requireCode(approve(depositRequest.depositAddress, depositRequest.cokeAmount) ? 0 : 508); rUtils.requireCode(IPledgeForCoke(depositRequest.depositAddress).deposit(depositRequest, serverSig) ? 0 : 509); return true; } function betReward(address _account, uint256 _amount) public mintPermission returns (uint256 minted){ uint256 input = _amount; uint256 totalMint = 0; while (input > 0) { uint256 factor = 2 ** currentDifficulty; uint256 discount = input / factor; if (input % factor != 0) { discount ++; } if (discount > remain - currentStageEnd) { uint256 toMint = remain - currentStageEnd; totalMint += toMint; input = input - toMint * factor; remain = currentStageEnd; } else { totalMint += discount; input = 0; remain = remain - discount; } //update to next stage if (remain == currentStageEnd) { if (currentStageEnd != 0) { currentDifficulty = currentDifficulty + 1; if (remain - step > 0) { currentStageEnd = remain - step; } else { currentStageEnd = 0; } } else { input = 0; } } } _transfer(address(this), _account, totalMint); emit Reward(_account, totalMint, _amount); uint256 mintToTeam = totalMint * unlockDenominator / unlockNumerator; if (teamRemain >= mintToTeam) { teamRemain = teamRemain - mintToTeam; _transfer(address(this), team, mintToTeam); emit UnlockToTeam(team, mintToTeam, totalMint); } return totalMint; } function setGameMachineRecords(address _input, bool _isActivated) public onlyCokeAdmin { gameMachineRecords[_input] = _isActivated; } function unlockAllTeamCoke() public onlyCokeAdmin { if (block.number > unlockAllBlockNumber) { _transfer(address(this), team, teamRemain); teamRemain = 0; emit UnlockToTeam(team, teamRemain, 0); } } modifier onlyCokeAdmin(){ rUtils.requireCode(msg.sender == cokeAdmin ? 0 : 503); _; } modifier mintPermission(){ rUtils.requireCode(gameMachineRecords[msg.sender] == true ? 0 : 505); _; } }
Internal function that mints an amount of the token and assigns it to an account. This encapsulates the modification of balances such that the proper events are emitted. account The account that will receive the created tokens. value The amount that will be created./
function _mint(address account, uint256 value) internal { require(account != address(0), "ERC20 _mint, account can not be 0x00"); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); }
7,326,961
./full_match/1/0x8235Ed3eAaE46846d6a97726b69F2953d1cd21d9/sources/contracts/Claimer.sol
DANGER: this will block all claims that use this asset.
function withdraw(IERC20 asset) external onlyOwner { SafeERC20.safeTransfer( asset, msg.sender, asset.balanceOf(address(this)) ); }
16,450,190
// SPDX-License-Identifier: MIT /** * @authors: [*@epiqueras, @shotaronowhere] * @reviewers: [] * @auditors: [] * @bounties: [] * @deployments: [ ] */ pragma solidity ^0.4.24; /** * @title DualSortitionSumTreeFactory * @author Shotaro - <[email protected]> * @dev A factory of dual trees that keep track of staked values for sortition. */ library DualSortitionSumTreeFactory { /* Structs */ struct SortitionSumTree { uint K; // The maximum number of childs per node. // We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around. uint[] stack; uint[] nodes; // Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node. mapping(bytes32 => uint) IDsToNodeIndexes; mapping(uint => bytes32) nodeIndexesToIDs; } /* Storage */ struct DualSortitionSumTrees { mapping(bytes32 => SortitionSumTree) sortitionSumDrawTrees; mapping(bytes32 => SortitionSumTree) sortitionSumSetTrees; uint threshold; uint lastThresholdUpdate; } /* Public */ /** * @dev Create a sortition sum tree at the specified key. * @param _key The key of the new tree. * @param _K_draw The number of children each node in the draw tree should have. * @param _K_set The number of children each node in the draw tree should have. */ function createTree(DualSortitionSumTrees storage self, bytes32 _key, uint _K_draw,uint _K_set) public { SortitionSumTree storage treeDraw = self.sortitionSumDrawTrees[_key]; SortitionSumTree storage treeSet = self.sortitionSumSetTrees[_key]; self.threshold = uint(-1); self.lastThresholdUpdate = 0; require(treeDraw.K == 0, "Tree already exists."); require(treeSet.K == 0, "Tree already exists."); require(_K_draw > 1, "K must be greater than one."); require(_K_set > 1, "K must be greater than one."); treeDraw.K = _K_draw; treeDraw.stack.length = 0; treeDraw.nodes.length = 0; treeDraw.nodes.push(0); treeSet.K = _K_set; treeSet.stack.length = 0; treeSet.nodes.length = 0; treeSet.nodes.push(0); } /** * @dev Set a value of a tree. * @param _key The key of the tree. * @param _value The new value. * @param _ID The ID of the value. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function set(DualSortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) public { SortitionSumTree storage treeSet = self.sortitionSumSetTrees[_key]; SortitionSumTree storage treeDraw = self.sortitionSumDrawTrees[_key]; if (self.lastThresholdUpdate > 2*(treeSet.nodes[0]+treeDraw.nodes[0]) || 2*self.lastThresholdUpdate < treeSet.nodes[0]+treeDraw.nodes[0]){ uint startIndex = 0; for (uint i = 0; i < treeSet.nodes.length; i++) { if ((treeSet.K * i) + 1 >= treeSet.nodes.length) { startIndex = i; if (i == 0) startIndex = 1; break; } } for (i = 0; i < treeDraw.nodes.length; i++) { if ((treeDraw.K * i) + 1 >= treeDraw.nodes.length) { if (i == 0){ startIndex = startIndex +1; } else{ startIndex = startIndex + i; } break; } } uint numTreeElements = treeDraw.nodes.length + treeSet.nodes.length - startIndex; self.threshold = (treeSet.nodes[0]+treeDraw.nodes[0])/numTreeElements; if(self.threshold == 0){ self.threshold = uint(-1); } self.lastThresholdUpdate = treeSet.nodes[0]+treeDraw.nodes[0]; } uint treeIndex = treeSet.IDsToNodeIndexes[_ID]; bool plusOrMinus; uint plusOrMinusValue; if (treeIndex != 0){//set tree if (_value == 0) { // Zero value. // Remove. // Remember value and set to 0. remove(treeSet, treeIndex, _value, _ID); } else if (_value != treeSet.nodes[treeIndex]) { // New, non zero value. // Set. if (_value > self.threshold){// SortionSumSetTree -> SortitionSumDrawTree // Remove from SortionSumSetTree // Remember value and set to 0. remove(treeSet, treeIndex, _value, _ID); insert(treeDraw, _value, _ID); } else { plusOrMinus = treeSet.nodes[treeIndex] <= _value; plusOrMinusValue = plusOrMinus ? _value - treeSet.nodes[treeIndex] : treeSet.nodes[treeIndex] - _value; treeSet.nodes[treeIndex] = _value; updateParents(treeSet, treeIndex, plusOrMinus, plusOrMinusValue); } } } else { // draw tree or DNE treeIndex = treeDraw.IDsToNodeIndexes[_ID]; if (treeIndex != 0){// draw tree if (_value == 0) { // Zero value. // Remove. // Remember value and set to 0. remove(treeDraw, treeIndex, _value, _ID); } else if (_value != treeDraw.nodes[treeIndex]) { // New, non zero value. // Set. if (_value < self.threshold){// SortionSumDrawTree -> SortitionSumSetTree // Remove from SortionSumSetTree remove(treeDraw, treeIndex, _value, _ID); insert(treeSet, _value, _ID); } else{ plusOrMinus = treeDraw.nodes[treeIndex] <= _value; plusOrMinusValue = plusOrMinus ? _value - treeDraw.nodes[treeIndex] : treeDraw.nodes[treeIndex] - _value; treeDraw.nodes[treeIndex] = _value; updateParents(treeDraw, treeIndex, plusOrMinus, plusOrMinusValue); } } } else{ // new _ID if (_value != 0) { // Non zero value. if (_value < self.threshold){ insert(treeSet, _value, _ID); } else { insert(treeDraw, _value, _ID); } } } } } function insert(SortitionSumTree storage tree, uint _value, bytes32 _ID) private { uint treeIndex; if (tree.stack.length == 0) { // No vacant spots. // Get the index and append the value. treeIndex = tree.nodes.length; tree.nodes.push(_value); // Potentially append a new node and make the parent a sum node. if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; } } else { // Some vacant spot. // Pop the stack and append the value. treeIndex = tree.stack[tree.stack.length - 1]; tree.stack.length--; tree.nodes[treeIndex] = _value; } // Add label. tree.IDsToNodeIndexes[_ID] = treeIndex; tree.nodeIndexesToIDs[treeIndex] = _ID; updateParents(tree, treeIndex, true, _value); } function remove(SortitionSumTree storage tree, uint _treeIndex, uint _value, bytes32 _ID) private { tree.nodes[_treeIndex] = 0; // Push to stack. tree.stack.push(_treeIndex); // Clear label. delete tree.IDsToNodeIndexes[_ID]; delete tree.nodeIndexesToIDs[_treeIndex]; updateParents(tree, _treeIndex, false, _value); } /* Public Views */ /** * @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned. * @param _key The key of the tree to get the leaves from. * @param _cursor The pagination cursor. * @param _count The number of items to return. * @return startIndex The index at which leaves start. * @return values The values of the returned leaves. * @return hasMore Whether there are more for pagination. * `O(n)` where * `n` is the maximum number of nodes ever appended. */ function queryLeafs( DualSortitionSumTrees storage self, bytes32 _key, uint _cursor, uint _count, bool isSumTree ) public view returns(uint startIndex, uint[] values, bool hasMore) { SortitionSumTree storage tree = isSumTree ? self.sortitionSumSetTrees[_key] : self.sortitionSumDrawTrees[_key]; // Find the start index. for (uint i = 0; i < tree.nodes.length; i++) { if ((tree.K * i) + 1 >= tree.nodes.length) { startIndex = i; break; } } // Get the values. uint loopStartIndex = startIndex + _cursor; values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count); uint valuesIndex = 0; for (uint j = loopStartIndex; j < tree.nodes.length; j++) { if (valuesIndex < _count) { values[valuesIndex] = tree.nodes[j]; valuesIndex++; } else { hasMore = true; break; } } } /** * @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0. * @param _key The key of the tree. * @param _drawnNumber The drawn number. * @return ID The drawn ID. * `O(k * log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function draw(DualSortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) public view returns(bytes32 ID) { SortitionSumTree storage tree = self.sortitionSumDrawTrees[_key]; SortitionSumTree storage treeSet = self.sortitionSumSetTrees[_key]; uint treeIndex = 0; uint currentDrawnNumber = _drawnNumber % (tree.nodes[0]+treeSet.nodes[0]); if(currentDrawnNumber > tree.nodes[0]){ currentDrawnNumber -= tree.nodes[0]; tree = treeSet; } while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children. for (uint i = 1; i <= tree.K; i++) { // Loop over children. uint nodeIndex = (tree.K * treeIndex) + i; uint nodeValue = tree.nodes[nodeIndex]; if (currentDrawnNumber >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child. else { // Pick this child. treeIndex = nodeIndex; break; } } ID = tree.nodeIndexesToIDs[treeIndex]; } /** @dev Gets a specified ID's associated value. * @param _key The key of the tree. * @param _ID The ID of the value. * @return value The associated value. */ function stakeOf(DualSortitionSumTrees storage self, bytes32 _key, bytes32 _ID) public view returns(uint value) { // check set first SortitionSumTree storage tree = self.sortitionSumSetTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) { // check draw second tree = self.sortitionSumDrawTrees[_key]; treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) value = 0; else value = tree.nodes[treeIndex]; } else { value = tree.nodes[treeIndex]; } } /* Private */ /** * @dev Update all the parents of a node. * @param _treeIndex The index of the node to start from. * @param _plusOrMinus Wether to add (true) or substract (false). * @param _value The value to add or substract. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function updateParents(SortitionSumTree storage tree, uint _treeIndex, bool _plusOrMinus, uint _value) private { uint parentIndex = _treeIndex; while (parentIndex != 0) { parentIndex = (parentIndex - 1) / tree.K; tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value; } } }
Set a value of a tree. _key The key of the tree. _value The new value. _ID The ID of the value. `O(log_k(n))` where `k` is the maximum number of childs per node in the tree, and `n` is the maximum number of nodes ever appended./
function set(DualSortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) public { SortitionSumTree storage treeSet = self.sortitionSumSetTrees[_key]; SortitionSumTree storage treeDraw = self.sortitionSumDrawTrees[_key]; if (self.lastThresholdUpdate > 2*(treeSet.nodes[0]+treeDraw.nodes[0]) || 2*self.lastThresholdUpdate < treeSet.nodes[0]+treeDraw.nodes[0]){ uint startIndex = 0; for (uint i = 0; i < treeSet.nodes.length; i++) { if ((treeSet.K * i) + 1 >= treeSet.nodes.length) { startIndex = i; if (i == 0) startIndex = 1; break; } } for (i = 0; i < treeDraw.nodes.length; i++) { if ((treeDraw.K * i) + 1 >= treeDraw.nodes.length) { if (i == 0){ startIndex = startIndex +1; } else{ startIndex = startIndex + i; } break; } } uint numTreeElements = treeDraw.nodes.length + treeSet.nodes.length - startIndex; self.threshold = (treeSet.nodes[0]+treeDraw.nodes[0])/numTreeElements; if(self.threshold == 0){ self.threshold = uint(-1); } self.lastThresholdUpdate = treeSet.nodes[0]+treeDraw.nodes[0]; } uint treeIndex = treeSet.IDsToNodeIndexes[_ID]; bool plusOrMinus; uint plusOrMinusValue; insert(treeDraw, _value, _ID); plusOrMinus = treeSet.nodes[treeIndex] <= _value; plusOrMinusValue = plusOrMinus ? _value - treeSet.nodes[treeIndex] : treeSet.nodes[treeIndex] - _value; treeSet.nodes[treeIndex] = _value; updateParents(treeSet, treeIndex, plusOrMinus, plusOrMinusValue); }
6,369,290
// SPDX-License-Identifier: MIT pragma solidity 0.8.12; import './interface/ComptrollerInterface.sol'; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; error MarketNotList(); error InsufficientLiquidity(); error PriceError(); error NotLiquidatePosition(); error AdminOnly(); error ProtocolPaused(); contract Comptroller is ComptrollerInterface { event NewAurumController(AurumControllerInterface oldAurumController, AurumControllerInterface newAurumController); event NewComptrollerCalculation(ComptrollerCalculation oldComptrollerCalculation, ComptrollerCalculation newComptrollerCalculation); event NewTreasuryGuardian(address oldTreasuryGuardian, address newTreasuryGuardian); event NewTreasuryAddress(address oldTreasuryAddress, address newTreasuryAddress); event NewTreasuryPercent(uint oldTreasuryPercent, uint newTreasuryPercent); event ARMGranted(address recipient, uint amount); event NewPendingAdmin (address oldPendingAdmin,address newPendingAdmin); event NewAdminConfirm (address oldAdmin, address newAdmin); event DistributedGOLDVault(uint amount); // Variables declaration // address public admin; address public pendingAdmin; ComptrollerStorage public compStorage; ComptrollerCalculation public compCalculate; AurumControllerInterface public aurumController; address public treasuryGuardian; //Guardian of the treasury address public treasuryAddress; //Wallet Address uint256 public treasuryPercent; //Fee in percent of accrued interest with decimal 18 , This value is used in liquidate function of each LendToken bool internal locked; // reentrancy Guardian constructor(ComptrollerStorage compStorage_) { admin = msg.sender; compStorage = compStorage_; //Bind storage to the comptroller contract. locked = false; // reentrancyGuard Variable } // // Get parameters function // function isComptroller() external pure returns(bool){ // double check the contract return true; } function isProtocolPaused() external view returns(bool) { return compStorage.protocolPaused(); } function getMintedGOLDs(address minter) external view returns(uint) { // The ledger of user's AURUM minted is stored in ComptrollerStorage contract. return compStorage.getMintedGOLDs(minter); } function getComptrollerOracleAddress() external view returns(address) { return address(compStorage.oracle()); } function getAssetsIn(address account) external view returns (LendTokenInterface[] memory) { return compStorage.getAssetsIn(account); } function getGoldMintRate() external view returns (uint) { return compStorage.goldMintRate(); } function addToMarket(LendTokenInterface lendToken) external{ compStorage.addToMarket(lendToken, msg.sender); } function exitMarket(address lendTokenAddress) external{ LendTokenInterface lendToken = LendTokenInterface(lendTokenAddress); /* Get sender tokensHeld and borrowBalance from the lendToken */ (uint tokensHeld, uint borrowBalance, ) = lendToken.getAccountSnapshot(msg.sender); /* Fail if the sender has a borrow balance */ if (borrowBalance != 0) { revert(); } // if All of user's tokensHeld allowed to redeem, then it's allowed to UNCOLLATERALIZED. this.redeemAllowed(lendTokenAddress, msg.sender, tokensHeld); // Execute change of state variable in ComptrollerStorage. compStorage.exitMarket(lendTokenAddress, msg.sender); } /*** Policy Hooks ***/ // Check if the account be allowed to mint tokens // This check only // 1. Protocol not pause // 2. The lendToken is listed // Then update the reward SupplyIndex function mintAllowed(address lendToken, address minter) external{ bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } // Pausing is a very serious situation - we revert to sound the alarms require(!compStorage.getMintGuardianPaused(lendToken), "mint is paused"); if (!compStorage.isMarketListed(lendToken)) { revert MarketNotList(); } // Keep the flywheel moving compStorage.updateARMSupplyIndex(lendToken); compStorage.distributeSupplierARM(lendToken, minter); } // // Redeem allowed will check // 1. is the asset is list in market ? // 2. had the redeemer entered the market ? // 3. predict the value after redeem and check. if the loan is over (shortfall) then user can't redeem. // 4. if all pass then redeem is allowed. // function redeemAllowed(address lendToken, address redeemer, uint redeemTokens) external{ // bool protocolPaused = compStorage.protocolPaused(); // if(protocolPaused){ revert ProtocolPaused(); } if (!compStorage.isMarketListed(lendToken)) { //Can't redeem the asset which not list in market. revert MarketNotList(); } /* If the redeemer is not 'in' the market (this token not in collateral calculation), then we can bypass the liquidity check */ if (!compStorage.checkMembership(redeemer, LendTokenInterface(lendToken)) ) { return ; } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (, uint shortfall) = compCalculate.getHypotheticalAccountLiquidity(redeemer, lendToken, redeemTokens, 0); if (shortfall != 0) { revert InsufficientLiquidity(); } compStorage.updateARMSupplyIndex(lendToken); compStorage.distributeSupplierARM(lendToken, redeemer); } // // Borrow allowed will check // 1. is the asset listed in market ? // 2. if borrower not yet listed in market.accountMembership --> add the borrower in // 3. Check the price of oracle (is it still in normal status ?) // 4.1 Check borrow cap (if borrowing amount more than cap it's not allowed) // 4.2 Predict the loan after borrow. if the loan is over (shortfall) then user can't borrow. // 5. if all pass, return no ERROR. // function borrowAllowed(address lendToken, address borrower, uint borrowAmount) external{ bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } // Pausing is a very serious situation - we revert to sound the alarms require(!compStorage.getBorrowGuardianPaused(lendToken)); if (!compStorage.isMarketListed(lendToken)) { revert MarketNotList(); } if (!compStorage.checkMembership(borrower, LendTokenInterface(lendToken)) ) { // previously we check that 'lendToken' is one of the verify LendToken, so make sure that this function is called by the verified lendToken not ATTACKER wallet. require(msg.sender == lendToken, "sender must be lendToken"); // the borrow token automatically addToMarket. compStorage.addToMarket(LendTokenInterface(lendToken), borrower); } if (compStorage.oracle().getUnderlyingPrice(LendTokenInterface(lendToken)) == 0) { revert PriceError(); } uint borrowCap = compStorage.getBorrowCaps(lendToken); // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = LendTokenInterface(lendToken).totalBorrows(); uint nextTotalBorrows = totalBorrows + borrowAmount; require(nextTotalBorrows < borrowCap, "borrow cap reached"); // if total borrow + pending borrow reach borrow cap --> error } uint shortfall; (, shortfall) = compCalculate.getHypotheticalAccountLiquidity(borrower, lendToken, 0, borrowAmount); if (shortfall != 0) { revert InsufficientLiquidity(); } // Keep the flywheel moving uint borrowIndex = LendTokenInterface(lendToken).borrowIndex(); compStorage.updateARMBorrowIndex(lendToken, borrowIndex); compStorage.distributeBorrowerARM(lendToken, borrower, borrowIndex); } // // repay is mostly allowed. except the market is closed. // function repayBorrowAllowed(address lendToken, address borrower) external{ bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } if (!compStorage.isMarketListed(lendToken) ) { revert MarketNotList(); } // Keep the flywheel moving uint borrowIndex = LendTokenInterface(lendToken).borrowIndex(); compStorage.updateARMBorrowIndex(lendToken, borrowIndex); compStorage.distributeBorrowerARM(lendToken, borrower, borrowIndex); } // // Liquidate allowed will check // 1. is market listed ? // 2. is the borrower currently shortfall ? (run predict function without borrowing or redeeming) // 3. calculate the max repayAmount by formula borrowBalance * closeFactorMantissa (%) // 4. check if repayAmount > maximumClose then revert. // 5. if all pass => allowed // function liquidateBorrowAllowed(address lendTokenBorrowed, address lendTokenCollateral, address borrower, uint repayAmount) external view{ bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } if (!(compStorage.isMarketListed(lendTokenBorrowed) || address(lendTokenBorrowed) == address(aurumController)) || !compStorage.isMarketListed(lendTokenCollateral) ) { revert MarketNotList(); } /* The borrower must have shortfall in order to be liquidatable */ (, uint shortfall) = compCalculate.getHypotheticalAccountLiquidity(borrower, address(0), 0, 0); if (shortfall == 0) { revert NotLiquidatePosition(); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance; if (address(lendTokenBorrowed) != address(aurumController)) { //aurumController is GOLD aurum minting control borrowBalance = LendTokenInterface(lendTokenBorrowed).borrowBalanceStored(borrower); } else { borrowBalance = compStorage.getMintedGOLDs(borrower); } uint maxClose = compStorage.closeFactorMantissa() * borrowBalance / 1e18; if (repayAmount > maxClose) { revert InsufficientLiquidity(); } } // // SeizeAllowed will check // 1. check the lendToken Borrow and Collateral both are listed in market (aurumController also can be lendTokenBorrowed address) // // 2. lendToken Borrow and Collateral are in the same market (Comptroller) // 3. if all pass => (allowed). // // lendTokenBorrowed is the called LendToken or aurumController. function seizeAllowed(address lendTokenCollateral, address lendTokenBorrowed, address liquidator, address borrower) external{ bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } // Pausing is a very serious situation - we revert to sound the alarms require(!compStorage.seizeGuardianPaused()); // We've added aurumController as a borrowed token list check for seize if (!compStorage.isMarketListed(lendTokenCollateral) || !(compStorage.isMarketListed(lendTokenBorrowed) || address(lendTokenBorrowed) == address(aurumController))) { revert MarketNotList(); } // Check Borrow and Collateral in the same market (comptroller). if (LendTokenInterface(lendTokenCollateral).comptroller() != LendTokenInterface(lendTokenBorrowed).comptroller()) { revert(); } // Keep the flywheel moving compStorage.updateARMSupplyIndex(lendTokenCollateral); compStorage.distributeSupplierARM(lendTokenCollateral, borrower); compStorage.distributeSupplierARM(lendTokenCollateral, liquidator); } // // TransferAllowed is simply automatic allowed when redeeming is allowed (redeeming then transfer) // So just check if this token is redeemable ? // function transferAllowed(address lendToken, address src, address dst, uint transferTokens) external{ bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } // Pausing is a very serious situation - we revert to sound the alarms require(!compStorage.transferGuardianPaused()); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens this.redeemAllowed(lendToken, src, transferTokens); // Keep the flywheel moving compStorage.updateARMSupplyIndex(lendToken); compStorage.distributeSupplierARM(lendToken, src); compStorage.distributeSupplierARM(lendToken, dst); } /*** Liquidity/Liquidation Calculations ***/ // Calculating function in ComptrollerCalculation contract function liquidateCalculateSeizeTokens(address lendTokenBorrowed, address lendTokenCollateral, uint actualRepayAmount) external view returns (uint) { return compCalculate.liquidateCalculateSeizeTokens(lendTokenBorrowed, lendTokenCollateral, actualRepayAmount); } function liquidateGOLDCalculateSeizeTokens(address lendTokenCollateral, uint actualRepayAmount) external view returns (uint) { return compCalculate.liquidateGOLDCalculateSeizeTokens(lendTokenCollateral, actualRepayAmount); } // /*** Admin Functions ***/ // function _setPendingAdmin(address newPendingAdmin) external { if(msg.sender != admin) { revert AdminOnly();} address oldPendingAdmin = pendingAdmin; pendingAdmin = newPendingAdmin; emit NewPendingAdmin (oldPendingAdmin, newPendingAdmin); } function _confirmNewAdmin() external { if(msg.sender != admin) { revert AdminOnly();} address oldAdmin = admin; address newAdmin = pendingAdmin; require(newAdmin != address(0), "Set pending admin first"); admin = pendingAdmin; pendingAdmin = address(0); //Also set ComptrollerStorage's new admin to the same as comptroller. compStorage._setNewStorageAdmin(newAdmin); emit NewAdminConfirm (oldAdmin, newAdmin); } function _setAurumController(AurumControllerInterface aurumController_) external{ if(msg.sender != admin) { revert AdminOnly();} AurumControllerInterface oldRate = aurumController; aurumController = aurumController_; emit NewAurumController(oldRate, aurumController_); } function _setTreasuryData(address newTreasuryGuardian, address newTreasuryAddress, uint newTreasuryPercent) external{ if (!(msg.sender == admin || msg.sender == treasuryGuardian)) { revert AdminOnly(); } require(newTreasuryPercent < 1e18, "treasury percent cap overflow"); address oldTreasuryGuardian = treasuryGuardian; address oldTreasuryAddress = treasuryAddress; uint oldTreasuryPercent = treasuryPercent; treasuryGuardian = newTreasuryGuardian; treasuryAddress = newTreasuryAddress; treasuryPercent = newTreasuryPercent; emit NewTreasuryGuardian(oldTreasuryGuardian, newTreasuryGuardian); emit NewTreasuryAddress(oldTreasuryAddress, newTreasuryAddress); emit NewTreasuryPercent(oldTreasuryPercent, newTreasuryPercent); } function _setComptrollerCalculation (ComptrollerCalculation newCompCalculate) external { if(msg.sender != admin) { revert AdminOnly();} ComptrollerCalculation oldCompCalculate = compCalculate; compCalculate = newCompCalculate; emit NewComptrollerCalculation (oldCompCalculate, newCompCalculate); } // Claim ARM function function claimARMAllMarket(address holder) external { return claimARM(holder, compStorage.getAllMarkets()); } function claimARM(address holder, LendTokenInterface[] memory lendTokens) public { this.claimARM(holder, lendTokens, true, true); } function claimARM(address holder, LendTokenInterface[] memory lendTokens, bool borrowers, bool suppliers) external { require (locked == false,"No reentrance"); //Reentrancy guard locked = true; for (uint i = 0; i < lendTokens.length; i++) { LendTokenInterface lendToken = lendTokens[i]; require(compStorage.isMarketListed(address(lendToken))); uint armAccrued; if (borrowers) { // Update the borrow index of each lendToken in the storage of comptroller // Borrow index is the multiplier which gradually increase by the amount of interest (borrowRate) uint borrowIndex = lendToken.borrowIndex(); compStorage.updateARMBorrowIndex(address(lendToken), borrowIndex); compStorage.distributeBorrowerARM(address(lendToken), holder, borrowIndex); armAccrued = compStorage.getArmAccrued(holder); compStorage.grantARM(holder, armAccrued); //reward the user then set user's armAccrued to 0; } if (suppliers) { compStorage.updateARMSupplyIndex(address(lendToken)); compStorage.distributeSupplierARM(address(lendToken), holder); armAccrued = compStorage.getArmAccrued(holder); compStorage.grantARM(holder, armAccrued); } } locked = false; } /*** Aurum Distribution Admin ***/ function _setAurumSpeed(LendTokenInterface lendToken, uint aurumSpeed) external { if(msg.sender != admin) { revert AdminOnly();} uint borrowIndex = lendToken.borrowIndex(); compStorage.updateARMSupplyIndex(address(lendToken)); compStorage.updateARMBorrowIndex(address(lendToken), borrowIndex); uint currentAurumSpeed = compStorage.getAurumSpeeds(address(lendToken)); if (currentAurumSpeed == 0 && aurumSpeed != 0) { // Initialize compStorage.addARMdistributionMarket(lendToken); } if (currentAurumSpeed != aurumSpeed) { compStorage.setAurumSpeed(lendToken, aurumSpeed); } } //Set the amount of GOLD had minted, this should be called by aurumController contract function setMintedGOLDOf(address owner, uint amount) external { require(msg.sender == address(aurumController)); bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } bool mintGOLDGuardianPaused = compStorage.mintGOLDGuardianPaused(); require(!mintGOLDGuardianPaused, "Mint GOLD is paused"); compStorage.setMintedGOLD(owner,amount); } } contract ComptrollerCalculation { // no admin setting in this contract, ComptrollerStorage compStorage; constructor(ComptrollerStorage _compStorage) { compStorage = _compStorage; } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `lendTokenBalance` is the number of lendTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint lendTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; uint goldOraclePriceMantissa; uint tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return 1. account liquidity in excess of collateral requirements, * 2. account shortfall below collateral requirements) */ function getAccountLiquidity(address account) external view returns (uint, uint) { (uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, LendTokenInterface(address(0)), 0, 0); return (liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param lendTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ // // This function will simulate the user's account after interact with a specify LendToken when increasing loan (Borrowing and Redeeming) // How much liquidity left OR How much shortage will return. // 1. get each aset that the account participate in the market // 2. Sum up Collateral value (+), Borrow (-), Effect[BorrowMore, RedeemMore, Gold Minted] (-) // 3. Return liquidity if positive, Return shortage if negative. // function getHypotheticalAccountLiquidity(address account, address lendTokenModify, uint redeemTokens, uint borrowAmount) external view returns (uint, uint) { (uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, LendTokenInterface(lendTokenModify), redeemTokens, borrowAmount); return (liquidity, shortfall); } function isShortage(address account) external view returns(bool){ // This function will be called by the front-end Liquidator query. the LendTokenInterface(msg.sender) is the dummy parameter, it's not use for calculation. (,uint shortfall) = getHypotheticalAccountLiquidityInternal(account, LendTokenInterface(msg.sender), 0, 0); if(shortfall > 0){ return true; } else { return false; } } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param lendTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral lendToken using stored data, * without calculating accumulated interest. * @return (hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, LendTokenInterface lendTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results vars.goldOraclePriceMantissa = compStorage.oracle().getGoldPrice(); if (vars.goldOraclePriceMantissa == 0) { revert ("Gold price error"); } // For each asset the account is in LendTokenInterface[] memory assets = compStorage.getAssetsIn(account); for (uint i = 0; i < assets.length; i++) { LendTokenInterface asset = assets[i]; // Read the balances and exchange rate from the lendToken // As noted above, if no one interact with the LendToken, the 'accrueInterest' function not called for long time. // May lead to outdated exchangeRate. (vars.lendTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); uint collateralFactorMantissa = compStorage.getMarketCollateralFactorMantissa(address(asset)); // Get the normalized price of the asset vars.oraclePriceMantissa = compStorage.oracle().getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { revert("Oracle error"); } // Pre-compute a conversion factor // Unit compensate = 1e18 :: (e18*e18 / e18) *e18 / e18 vars.tokensToDenom = (collateralFactorMantissa * vars.exchangeRateMantissa / 1e18) * vars.oraclePriceMantissa / 1e18; // sumCollateral += tokensToDenom * lendTokenBalance // Unit compensate = 1e18 :: (e18*e18 / e18) vars.sumCollateral += (vars.tokensToDenom * vars.lendTokenBalance / 1e18); // sumBorrowPlusEffects += oraclePrice * borrowBalance // Unit compensate = 1e18 :: (e18*e18 /e18) vars.sumBorrowPlusEffects += (vars.oraclePriceMantissa * vars.borrowBalance / 1e18); // Calculate effects of interacting with lendTokenModify if (asset == lendTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens // Unit compensate = 1e18 vars.sumBorrowPlusEffects += (vars.tokensToDenom * redeemTokens / 1e18); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount // Unit compensate = 1e18 vars.sumBorrowPlusEffects += (vars.oraclePriceMantissa * borrowAmount / 1e18); } } //---------------------- This formula modified from VAI minted of venus contract to => GoldMinted * GoldOraclePrice------------------ // sumBorrowPlusEffects += GoldMinted * GoldOraclePrice vars.sumBorrowPlusEffects += (vars.goldOraclePriceMantissa * compStorage.getMintedGOLDs(account) / 1e18); // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { //Return remaining liquidity. return (vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { //Return shortfall amount. return (0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in lendToken.liquidateBorrowFresh) * @param lendTokenBorrowed The address of the borrowed lendToken * @param lendTokenCollateral The address of the collateral lendToken * @param actualRepayAmount The amount of underlying token that liquidator had paid. * @return number of lendTokenCollateral tokens to be seized in a liquidation */ function liquidateCalculateSeizeTokens(address lendTokenBorrowed, address lendTokenCollateral, uint actualRepayAmount) external view returns (uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = compStorage.oracle().getUnderlyingPrice(LendTokenInterface(lendTokenBorrowed)); uint priceCollateralMantissa = compStorage.oracle().getUnderlyingPrice(LendTokenInterface(lendTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { revert ("Oracle price error"); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = LendTokenInterface(lendTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; // Numerator is 1e54 // *1e18 for calculating ratio into 1e18 uint numerator = compStorage.liquidationIncentiveMantissa() * priceBorrowedMantissa * 1e18; // Denominator is 1e36 uint denominator = priceCollateralMantissa * exchangeRateMantissa; // Ratio is 1e18 uint ratioMantissa = numerator / denominator; seizeTokens = ratioMantissa * actualRepayAmount / 1e18; return seizeTokens; } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation. Called by AurumController contract * @param lendTokenCollateral The address of the collateral lendToken * @param actualRepayAmount The amount of AURUM that liquidator had paid. * @return number of lendTokenCollateral tokens to be seized in a liquidation */ function liquidateGOLDCalculateSeizeTokens(address lendTokenCollateral, uint actualRepayAmount) external view returns (uint) { /* Read oracle prices for borrowed and collateral markets */ //The different to the previous function is only Borrow price oracle is GOLD price uint priceBorrowedMantissa = compStorage.oracle().getGoldPrice(); // get the current gold price feeding from oracle uint priceCollateralMantissa = compStorage.oracle().getUnderlyingPrice(LendTokenInterface(lendTokenCollateral)); if (priceCollateralMantissa == 0 || priceBorrowedMantissa == 0) { revert ("Oracle price error"); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = LendTokenInterface(lendTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; // Numerator is 1e54 // *1e18 for calculating ratio into 1e18 uint numerator = compStorage.liquidationIncentiveMantissa() * priceBorrowedMantissa * 1e18; // Denominator is 1e36 uint denominator = priceCollateralMantissa * exchangeRateMantissa; // Ratio is 1e18 uint ratioMantissa = numerator / denominator; seizeTokens = ratioMantissa * actualRepayAmount / 1e18; return seizeTokens; } struct ARMAccrued { uint supplierIndex; uint borrowerIndex; uint supplyStateIndex; uint borrowStateIndex; uint supplierTokens; uint borrowerAmount; uint aurumSpeed; } // // Front-end function // core function is getUpdateARMAccrued // input of timestamp in Javascript should be divided by 1000 // function getUpdateARMSupplyIndex(address lendToken, uint currentTime) internal view returns(uint) { (uint supplyStateIndex, uint supplyStateTimestamp) = compStorage.armSupplyState(lendToken); uint supplySpeed = compStorage.aurumSpeeds(lendToken); uint deltaTime = currentTime - supplyStateTimestamp; if (deltaTime > 0 && supplySpeed > 0) { uint supplyTokens = LendTokenInterface(lendToken).totalSupply(); uint armAcc = deltaTime * supplySpeed; uint addingValue; if (supplyTokens > 0){ addingValue = armAcc * 1e36 / supplyTokens; // calculate index and stored in Double } else { addingValue = 0; } return supplyStateIndex + addingValue; } else { return supplyStateIndex; } } function getUpdateARMBorrowIndex(address lendToken, uint currentTime) internal view returns(uint) { (uint borrowStateIndex, uint borrowStateTimestamp) = compStorage.armBorrowState(lendToken); uint borrowSpeed = compStorage.aurumSpeeds(lendToken); uint deltaTime = currentTime - borrowStateTimestamp; uint marketBorrowIndex = LendTokenInterface(lendToken).borrowIndex(); if (deltaTime > 0 && borrowSpeed > 0) { uint borrowTokens = LendTokenInterface(lendToken).totalBorrows() * 1e18 / marketBorrowIndex; uint armAcc = deltaTime * borrowSpeed; // addingValue is e36 uint addingValue; if (borrowTokens > 0){ addingValue = armAcc * 1e36 / borrowTokens; // calculate index and stored in Double } else { addingValue = 0; } return borrowStateIndex + addingValue; } else { return borrowStateIndex; } } // This function called by front-end dApp to get real-time reward function getUpdateARMAccrued(address user, uint currentTime) external view returns(uint) { LendTokenInterface[] memory lendToken = compStorage.getAllMarkets(); ARMAccrued memory vars; uint priorARMAccrued = compStorage.getArmAccrued(user); uint i; uint deltaIndex; uint marketBorrowIndex; for(i=0;i<lendToken.length; i++){ vars.supplierIndex = compStorage.aurumSupplierIndex(address(lendToken[i]) , user); vars.borrowerIndex = compStorage.aurumBorrowerIndex(address(lendToken[i]) , user); vars.supplyStateIndex = getUpdateARMSupplyIndex(address(lendToken[i]), currentTime); vars.borrowStateIndex = getUpdateARMBorrowIndex(address(lendToken[i]), currentTime); marketBorrowIndex = lendToken[i].borrowIndex(); vars.aurumSpeed = compStorage.aurumSpeeds(address(lendToken[i])); //Supply Accrued if (vars.supplierIndex == 0 && vars.supplyStateIndex > 0) { vars.supplierIndex = 1e36; } deltaIndex = vars.supplyStateIndex - vars.supplierIndex; vars.supplierTokens = lendToken[i].balanceOf(user); priorARMAccrued += vars.supplierTokens * deltaIndex / 1e36; //Borrow Accrued if (vars.borrowerIndex > 0) { deltaIndex = vars.borrowStateIndex - vars.borrowerIndex; vars.borrowerAmount = lendToken[i].borrowBalanceStored(user) * 1e18 / marketBorrowIndex; priorARMAccrued += vars.borrowerAmount * deltaIndex / 1e36; } } return priorARMAccrued; } } contract ComptrollerStorage { event MarketListed(LendTokenInterface lendToken); event MarketEntered(LendTokenInterface lendToken, address account); event MarketExited(LendTokenInterface lendToken, address account); event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); event NewCollateralFactor(LendTokenInterface lendToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); event AurumSpeedUpdated(LendTokenInterface indexed lendToken, uint newSpeed); event DistributedSupplierARM(LendTokenInterface indexed lendToken, address indexed supplier, uint aurumDelta, uint aurumSupplyIndex); event DistributedBorrowerARM(LendTokenInterface indexed lendToken, address indexed borrower, uint aurumDelta, uint aurumBorrowIndex); event NewGOLDMintRate(uint oldGOLDMintRate, uint newGOLDMintRate); event ActionProtocolPaused(bool state); event ActionTransferPaused(bool state); event ActionSeizePaused(bool state); event ActionMintPaused(address lendToken, bool state); event ActionBorrowPaused(address lendToken, bool state); event NewGuardianAddress(address oldGuardian, address newGuardian); event NewBorrowCap(LendTokenInterface indexed lendToken, uint newBorrowCap); event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); event MintGOLDPause(bool state); address public armAddress; address public comptrollerAddress; address public admin; address public guardian; //Guardian address, can only stop protocol PriceOracle public oracle; //stored contract of current PriceOracle (can be changed by _setPriceOracle function) function getARMAddress() external view returns(address) {return armAddress;} // // Liquidation variables // //Close factor is the % (in 1e18 value) of borrowing asset can be liquidate //e.g. if set 50% --> borrow 1000 USD, position can be liquidate maximum of 500 USD uint public closeFactorMantissa; //calculate the maximum repayAmount when liquidating a borrow --> can be set by _setCloseFactor(uint) uint public liquidationIncentiveMantissa; //multiplier that liquidator will receive after successful liquidate ; venus comptroller set up = 1100000000000000000 (1.1e18) // // Pause variables // /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing can only be paused globally, not by market. */ bool public protocolPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; function getMintGuardianPaused(address lendTokenAddress) external view returns(bool){ return mintGuardianPaused[lendTokenAddress];} mapping(address => bool) public borrowGuardianPaused; function getBorrowGuardianPaused(address lendTokenAddress) external view returns(bool){ return borrowGuardianPaused[lendTokenAddress];} bool public mintGOLDGuardianPaused; mapping(address => uint) public armAccrued; //ARM accrued but not yet transferred to each user function getArmAccrued(address user) external view returns (uint) {return armAccrued[user];} // // Aurum Gold controller 'AURUM token' // mapping(address => uint) public mintedGOLDs; //minted Aurum GOLD amount to each user function getMintedGOLDs(address user) external view returns(uint) {return mintedGOLDs[user];} uint16 public goldMintRate; //GOLD Mint Rate (percentage) value with two decimals 0-10000, 100 = 1%, 1000 = 10%, // // ARM distribution variables // mapping(address => uint) public aurumSpeeds; //The portion of aurumRate that each market currently receives function getAurumSpeeds(address lendToken) external view returns(uint) { return aurumSpeeds[lendToken];} // // Borrow cap // mapping(address => uint) public borrowCaps; //borrowAllowed for each lendToken address. Defaults to zero which corresponds to unlimited borrowing. function getBorrowCaps(address lendTokenAddress) external view returns (uint) { return borrowCaps[lendTokenAddress];} // // Market variables // mapping(address => LendTokenInterface[]) public accountAssets; //stored each account's assets. function getAssetsIn(address account) external view returns (LendTokenInterface[] memory) {return accountAssets[account];} struct Market { bool isListed; //Listed = true, Not listed = false /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint collateralFactorMantissa; mapping(address => bool) accountMembership; //Each market mapping of "accounts in this asset" similar to 'accountAssets' variable but the market side. } /** * @notice Official mapping of lendTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; //Can be set by _supportMarket admin function. function checkMembership(address account, LendTokenInterface lendToken) external view returns (bool) {return markets[address(lendToken)].accountMembership[account];} function isMarketListed(address lendTokenAddress) external view returns (bool) {return markets[lendTokenAddress].isListed;} function getMarketCollateralFactorMantissa(address lendTokenAddress) external view returns (uint) {return markets[lendTokenAddress].collateralFactorMantissa;} struct TheMarketState { /// @notice The market's last updated aurumBorrowIndex or aurumSupplyIndex // index variable is in Double (1e36) stored the last update index uint index; /// @notice The block number the index was last updated at uint lastTimestamp; } LendTokenInterface[] public allMarkets; //A list of all markets function getAllMarkets() external view returns(LendTokenInterface[] memory) {return allMarkets;} mapping(address => TheMarketState) public armSupplyState; //market supply state for each market mapping(address => TheMarketState) public armBorrowState; //market borrow state for each market //Individual index variables will update once individual check allowed function (will lastly call distributeSupplier / distributeBorrower function) to the current market's index. mapping(address => mapping(address => uint)) public aurumSupplierIndex; //supply index of each market for each supplier as of the last time they accrued ARM mapping(address => mapping(address => uint)) public aurumBorrowerIndex; //borrow index of each market for each borrower as of the last time they accrued ARM /// @notice The portion of ARM that each contributor receives per block mapping(address => uint) public aurumContributorSpeeds; /// @notice Last block at which a contributor's ARM rewards have been allocated mapping(address => uint) public lastContributorBlock; /// @notice The initial Aurum index for a market uint224 constant armInitialIndex = 1e36; // // CloseFactorMantissa guide // uint public constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must be strictly greater than this value ** MIN 5% uint public constant closeFactorMaxMantissa = 0.9e18; // 0.9 // closeFactorMantissa must not exceed this value ** MAX 90% uint public constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value constructor(address _armAddress) { admin = msg.sender; armAddress = _armAddress; closeFactorMantissa = 0.5e18; liquidationIncentiveMantissa = 1.1e18; } // // Comptroller parameter change function // Require comptroller is msg.sender // modifier onlyComptroller { require (msg.sender == comptrollerAddress, "Only comptroller"); _; } function _setNewStorageAdmin(address newAdmin) external onlyComptroller { admin = newAdmin; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param lendToken The market to enter * @param borrower The address of the account to modify */ function addToMarket(LendTokenInterface lendToken, address borrower) external onlyComptroller { Market storage marketToJoin = markets[address(lendToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join revert ("MARKET_NOT_LISTED"); } if (marketToJoin.accountMembership[borrower]) { // already joined return ; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(lendToken); emit MarketEntered(lendToken, borrower); } // To exitMarket.. Checking condition // --user must not borrowing this asset, // --user is allowed to redeem all the tokens (no excess loan when hypotheticalLiquidityCheck) // Action // 1.trigger boolean of user address of market's accountMembership to false // 2.delete userAssetList to this market. // function exitMarket(address lendTokenAddress, address user) external onlyComptroller{ LendTokenInterface lendToken = LendTokenInterface(lendTokenAddress); Market storage marketToExit = markets[address(lendToken)]; /* Return out if the sender is not ‘in’ the market */ if (!marketToExit.accountMembership[user]) { return ; //the state variable had changed in redeemAllowed function (updateARMSupplyIndex, distributeSupplierARM) } /* Set lendToken account membership to false */ delete marketToExit.accountMembership[user]; /* Delete lendToken from the account’s list of assets */ // In order to delete lendToken, copy last item in list to location of item to be removed, reduce length by 1 LendTokenInterface[] storage userAssetList = accountAssets[user]; uint len = userAssetList.length; uint i; for (i=0 ; i < len ; i++) { if (userAssetList[i] == lendToken) { // found the deleting array userAssetList[i] = userAssetList[len - 1]; // move the last parameter in array to the deleting array userAssetList.pop(); //this function remove the last parameter and also reduce array length by 1 break; //break before i++ so if there is the asset list, 'i' must always lesser than 'len' } } // We *must* have found the asset in the list or our redundant data structure is broken assert(i < len); emit MarketExited(lendToken, user); } function setAurumSpeed(LendTokenInterface lendToken, uint aurumSpeed) external onlyComptroller { // This function called by comptroller's _setAurumSpeed //Update the aurumSpeeds state variable. aurumSpeeds[address(lendToken)] = aurumSpeed; emit AurumSpeedUpdated(lendToken, aurumSpeed); } // This function is called by _setAurumSpeed admin function when FIRST TIME starting distribute ARM reward (from aurumSpeed 0) // it will check the MarketState of this lendToken and set to InitialIndex function addARMdistributionMarket(LendTokenInterface lendToken) external onlyComptroller { // Add the ARM market Market storage market = markets[address(lendToken)]; require(market.isListed == true, "aurum market is not listed"); // // These Lines of code is modified from Venus // If someone had mint lendToken or Allowed function is called, the timestamp would be change and not equal to zero // /* if (armSupplyState[address(lendToken)].index == 0 && armSupplyState[address(lendToken)].lastTimestamp == 0) { armSupplyState[address(lendToken)] = TheMarketState({ index: armInitialIndex, lastTimestamp: block.timestamp }); } if (armBorrowState[address(lendToken)].index == 0 && armBorrowState[address(lendToken)].lastTimestamp == 0) { armBorrowState[address(lendToken)] = TheMarketState({ index: armInitialIndex, lastTimestamp: block.timestamp }); } */ // // We remove the timeStamp == 0 , once distribution is initiated the index will not back to zero again. // This prevent over-reward of ARM if someone is pre-supply before the reward is initiating distribution. // if (armSupplyState[address(lendToken)].index == 0) { armSupplyState[address(lendToken)] = TheMarketState({ index: armInitialIndex, lastTimestamp: block.timestamp }); } if (armBorrowState[address(lendToken)].index == 0) { armBorrowState[address(lendToken)] = TheMarketState({ index: armInitialIndex, lastTimestamp: block.timestamp }); } } //Update the ARM distribute to Supplier //This function update the armSupplyState function updateARMSupplyIndex(address lendToken) external onlyComptroller { TheMarketState storage supplyState = armSupplyState[lendToken]; uint supplySpeed = aurumSpeeds[lendToken]; uint currentTime = block.timestamp; uint deltaTime = currentTime - supplyState.lastTimestamp; if (deltaTime > 0 && supplySpeed > 0) { uint supplyTokens = LendTokenInterface(lendToken).totalSupply(); uint armAcc = deltaTime * supplySpeed; // addingValue is e36 uint addingValue; if (supplyTokens > 0){ addingValue = armAcc * 1e36 / supplyTokens; // calculate index and stored in Double } else { addingValue = 0; } uint newindex = supplyState.index + addingValue; armSupplyState[lendToken] = TheMarketState({ index: newindex, // setting new updated index lastTimestamp: currentTime //and also timestamp }); } else if (deltaTime > 0) { supplyState.lastTimestamp = currentTime; } } //Update the ARM distribute to Borrower //same as above function but interact with Borrower variables function updateARMBorrowIndex(address lendToken, uint marketBorrowIndex) external onlyComptroller { TheMarketState storage borrowState = armBorrowState[lendToken]; uint borrowSpeed = aurumSpeeds[lendToken]; uint currentTime = block.timestamp; uint deltaTime = currentTime - borrowState.lastTimestamp; if (deltaTime > 0 && borrowSpeed > 0) { //borrowAmount is 1e18 :: e18 * 1e18 / e18 uint borrowAmount = LendTokenInterface(lendToken).totalBorrows() * 1e18 / marketBorrowIndex; uint armAcc = deltaTime * borrowSpeed; uint addingValue; if (borrowAmount > 0){ addingValue = armAcc * 1e36 / borrowAmount; // calculate index and stored in Double } else { addingValue = 0; } uint newindex = borrowState.index + addingValue; armBorrowState[lendToken] = TheMarketState({ index: newindex, // setting new updated index lastTimestamp: currentTime //and also timestamp }); } else if (deltaTime > 0) { borrowState.lastTimestamp = currentTime; } } //Distribute function will update armAccrued depends on the State.index which update by updateARM function //armAccrued will later claim by claimARM function function distributeSupplierARM(address lendToken, address supplier) external onlyComptroller { TheMarketState storage supplyState = armSupplyState[lendToken]; uint supplyIndex = supplyState.index; // stored in 1e36 uint supplierIndex = aurumSupplierIndex[lendToken][supplier]; // stored in 1e36 aurumSupplierIndex[lendToken][supplier] = supplyIndex; // update the user's index to the current state if (supplierIndex == 0 && supplyIndex > 0) { //This happen when first time using Allowed function after initialized reward distribution (Mint/Redeem/Seize) //or receiving a lendToken but currently don't have this token (transferAllowed function) supplierIndex = armInitialIndex; // 1e36 } //Calculate the new accrued arm since last update uint deltaIndex = supplyIndex - supplierIndex; uint supplierTokens = LendTokenInterface(lendToken).balanceOf(supplier); //e18 //If first time Mint/receive transfer LendToken, the balanceOf should be 0 uint supplierDelta = supplierTokens * deltaIndex / 1e36; //e18 :: e18*e36/ 1e36 uint supplierAccrued = armAccrued[supplier] + supplierDelta; armAccrued[supplier] = supplierAccrued; emit DistributedSupplierARM(LendTokenInterface(lendToken), supplier, supplierDelta, supplyIndex); } function distributeBorrowerARM(address lendToken, address borrower, uint marketBorrowIndex) external onlyComptroller { TheMarketState storage borrowState = armBorrowState[lendToken]; uint borrowIndex = borrowState.index; // stored in 1e36 uint borrowerIndex = aurumBorrowerIndex[lendToken][borrower]; // stored in 1e36 aurumBorrowerIndex[lendToken][borrower] = borrowIndex; // update the user's index to the current state if (borrowerIndex > 0) { uint deltaIndex = borrowIndex - borrowerIndex; // e36 // Let explain in diagram // [p] = principal // [i] = interest // [/i] = interest not yet record in accountBorrows[user] // [p][p][p][p][i] principal with interest (accountBorrows[user] stored 1. principal and 2.interestIndex multiplier) // [p][p][p][p] principal / interestIndex // [p][p][p][p][/i][/i] principal / interestIndex * marketBorrowIndex (this is what borrowBalanceStored function returns); // We need only principal amount to be calculated. uint borrowerAmount = LendTokenInterface(lendToken).borrowBalanceStored(borrower) * 1e18 / marketBorrowIndex; // e18 //This result uint borrowerDelta = borrowerAmount * deltaIndex / 1e36; // e18 :: e18 * e36 / 1e36 uint borrowerAccrued = armAccrued[borrower] + borrowerDelta; armAccrued[borrower] = borrowerAccrued; emit DistributedBorrowerARM(LendTokenInterface(lendToken), borrower, borrowerDelta, borrowIndex); } } //called by claimARM function //This function execute change of state variable 'armAccrued' and transfer ARM token to user. //returns the pending reward after claim. by the way it's not necessory. function grantARM(address user, uint amount) external onlyComptroller returns (uint) { IERC20 arm = IERC20(armAddress); uint armRemaining = arm.balanceOf(address(this)); // when the ARM reward pool is nearly empty, admin should manually turn aurum speed to 0 //Treasury reserves will be used when there is human error in reward process. if (amount > 0 && amount <= armRemaining) { armAccrued[user] = 0; arm.transfer(user, amount); return 0; } return amount; } function setMintedGOLD(address owner, uint amount) external onlyComptroller{ mintedGOLDs[owner] = amount; } // // Admin function // function _setComptrollerAddress (address newComptroller) external { require(msg.sender == admin, "Only admin"); comptrollerAddress = newComptroller; } // Maximum % of borrowing position can be liquidated (stored in 1e18) function _setCloseFactor(uint newCloseFactorMantissa) external { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, newCloseFactorMantissa); } function _setCollateralFactor(LendTokenInterface lendToken, uint newCollateralFactorMantissa) external{ // Check caller is admin require(msg.sender == admin, "Only admin"); // Verify market is listed Market storage market = markets[address(lendToken)]; if (!market.isListed) { revert ("Market not listed"); } // Check collateral factor <= 0.9 uint highLimit = collateralFactorMaxMantissa; require (highLimit > newCollateralFactorMantissa); // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(lendToken) == 0) { revert ("Fail price oracle"); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(lendToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); } // LiquidativeIncentive is > 1.00 // if set 1.1e18 means liquidator get 10% of liquidated position function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external{ // Check caller is admin require(msg.sender == admin, "Only admin"); require(newLiquidationIncentiveMantissa >= 1e18,"value must greater than 1e18"); // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); } // Add the market to the markets mapping and set it as listed function _supportMarket(LendTokenInterface lendToken) external{ require(msg.sender == admin, "Only admin"); if (markets[address(lendToken)].isListed) { revert ("Already list"); } require (lendToken.isLendToken(),"Not lendToken"); // Sanity check to make sure its really a LendTokenInterface markets[address(lendToken)].isListed = true; markets[address(lendToken)].collateralFactorMantissa = 0; for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != lendToken, "Already added"); } allMarkets.push(lendToken); emit MarketListed(lendToken); } //Set borrowCaps function _setMarketBorrowCaps(LendTokenInterface[] calldata lendTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin, "Only admin"); uint numMarkets = lendTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(lendTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(lendTokens[i], newBorrowCaps[i]); } } /** * Set whole protocol pause/unpause state */ function _setGuardianAddress(address newGuardian) external { require(msg.sender == admin, "No Auth"); address oldGuardian = guardian; guardian = newGuardian; emit NewGuardianAddress(oldGuardian, newGuardian); } //Guardians can pause protocol but can't unpause function _setProtocolPaused(bool state) external { require(msg.sender == admin || (msg.sender == guardian && state == true), "No Auth"); protocolPaused = state; emit ActionProtocolPaused(state); } function _setTransferPaused(bool state) external { require(msg.sender == admin || (msg.sender == guardian && state == true), "No Auth"); transferGuardianPaused = state; emit ActionTransferPaused(state); } function _setSeizePaused(bool state) external { require(msg.sender == admin || (msg.sender == guardian && state == true), "No Auth"); seizeGuardianPaused = state; emit ActionSeizePaused(state); } function _setMintPaused(address lendToken, bool state) external { require(msg.sender == admin || (msg.sender == guardian && state == true), "No Auth"); mintGuardianPaused[lendToken] = state; emit ActionMintPaused(lendToken, state); } function _setBorrowPaused(address lendToken, bool state) external { require(msg.sender == admin || (msg.sender == guardian && state == true), "No Auth"); borrowGuardianPaused[lendToken] = state; emit ActionBorrowPaused(lendToken, state); } function _setMintGoldPause(bool state) external { require(msg.sender == admin || (msg.sender == guardian && state == true), "No Auth"); mintGOLDGuardianPaused = state; emit MintGOLDPause(state); } function _setGOLDMintRate(uint16 newGOLDMintRate) external{ require(msg.sender == admin, "Only admin"); // Input: 0-10000, percentage with 2 decimals // 1 = 0.01% // 100 = 1% // 10000 = 100% // Check caller is admin require (newGOLDMintRate > 0 && newGOLDMintRate <= 10000,"Mintable GOLD rate must value 0-10000"); uint oldGOLDMintRate = goldMintRate; goldMintRate = newGOLDMintRate; emit NewGOLDMintRate(oldGOLDMintRate, newGOLDMintRate); } /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle */ function _setPriceOracle(PriceOracle newOracle) external{ // Check caller is admin require(msg.sender == admin, "Only admin"); // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); } }
The Pause Guardian can pause certain actions as a safety mechanism. Actions which allow users to remove their own assets cannot be paused. Liquidation / seizing can only be paused globally, not by market./
function getMintGuardianPaused(address lendTokenAddress) external view returns(bool){ return mintGuardianPaused[lendTokenAddress];}
15,849,546
pragma solidity ^0.4.25; contract BalanceHolder { mapping(address => uint256) public balanceOf; event LogWithdraw( address indexed user, uint256 amount ); function withdraw() public { uint256 bal = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; msg.sender.transfer(bal); emit LogWithdraw(msg.sender, bal); } } contract IBalanceHolder { mapping(address => uint256) public balanceOf; function withdraw() public { } } contract IRealitio is IBalanceHolder { struct Question { bytes32 content_hash; address arbitrator; uint32 opening_ts; uint32 timeout; uint32 finalize_ts; bool is_pending_arbitration; uint256 bounty; bytes32 best_answer; bytes32 history_hash; uint256 bond; } // Stored in a mapping indexed by commitment_id, a hash of commitment hash, question, bond. struct Commitment { uint32 reveal_ts; bool is_revealed; bytes32 revealed_answer; } // Only used when claiming more bonds than fits into a transaction // Stored in a mapping indexed by question_id. struct Claim { address payee; uint256 last_bond; uint256 queued_funds; } uint256 nextTemplateID = 0; mapping(uint256 => uint256) public templates; mapping(uint256 => bytes32) public template_hashes; mapping(bytes32 => Question) public questions; mapping(bytes32 => Claim) public question_claims; mapping(bytes32 => Commitment) public commitments; mapping(address => uint256) public arbitrator_question_fees; /// @notice Function for arbitrator to set an optional per-question fee. /// @dev The per-question fee, charged when a question is asked, is intended as an anti-spam measure. /// @param fee The fee to be charged by the arbitrator when a question is asked function setQuestionFee(uint256 fee) external { } /// @notice Create a reusable template, which should be a JSON document. /// Placeholders should use gettext() syntax, eg %s. /// @dev Template data is only stored in the event logs, but its block number is kept in contract storage. /// @param content The template content /// @return The ID of the newly-created template, which is created sequentially. function createTemplate(string content) public returns (uint256) { } /// @notice Create a new reusable template and use it to ask a question /// @dev Template data is only stored in the event logs, but its block number is kept in contract storage. /// @param content The template content /// @param question A string containing the parameters that will be passed into the template to make the question /// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute /// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer /// @param opening_ts If set, the earliest time it should be possible to answer the question. /// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question. /// @return The ID of the newly-created template, which is created sequentially. function createTemplateAndAskQuestion( string content, string question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce ) // stateNotCreated is enforced by the internal _askQuestion public payable returns (bytes32) { } /// @notice Ask a new question and return the ID /// @dev Template data is only stored in the event logs, but its block number is kept in contract storage. /// @param template_id The ID number of the template the question will use /// @param question A string containing the parameters that will be passed into the template to make the question /// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute /// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer /// @param opening_ts If set, the earliest time it should be possible to answer the question. /// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question. /// @return The ID of the newly-created question, created deterministically. function askQuestion(uint256 template_id, string question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce) // stateNotCreated is enforced by the internal _askQuestion public payable returns (bytes32) { } /// @notice Add funds to the bounty for a question /// @dev Add bounty funds after the initial question creation. Can be done any time until the question is finalized. /// @param question_id The ID of the question you wish to fund function fundAnswerBounty(bytes32 question_id) external payable { } /// @notice Submit an answer for a question. /// @dev Adds the answer to the history and updates the current "best" answer. /// May be subject to front-running attacks; Substitute submitAnswerCommitment()->submitAnswerReveal() to prevent them. /// @param question_id The ID of the question /// @param answer The answer, encoded into bytes32 /// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction. function submitAnswer(bytes32 question_id, bytes32 answer, uint256 max_previous) external payable { } /// @notice Submit the hash of an answer, laying your claim to that answer if you reveal it in a subsequent transaction. /// @dev Creates a hash, commitment_id, uniquely identifying this answer, to this question, with this bond. /// The commitment_id is stored in the answer history where the answer would normally go. /// Does not update the current best answer - this is left to the later submitAnswerReveal() transaction. /// @param question_id The ID of the question /// @param answer_hash The hash of your answer, plus a nonce that you will later reveal /// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction. /// @param _answerer If specified, the address to be given as the question answerer. Defaults to the sender. /// @dev Specifying the answerer is useful if you want to delegate the commit-and-reveal to a third-party. function submitAnswerCommitment(bytes32 question_id, bytes32 answer_hash, uint256 max_previous, address _answerer) external payable { } /// @notice Submit the answer whose hash you sent in a previous submitAnswerCommitment() transaction /// @dev Checks the parameters supplied recreate an existing commitment, and stores the revealed answer /// Updates the current answer unless someone has since supplied a new answer with a higher bond /// msg.sender is intentionally not restricted to the user who originally sent the commitment; /// For example, the user may want to provide the answer+nonce to a third-party service and let them send the tx /// NB If we are pending arbitration, it will be up to the arbitrator to wait and see any outstanding reveal is sent /// @param question_id The ID of the question /// @param answer The answer, encoded as bytes32 /// @param nonce The nonce that, combined with the answer, recreates the answer_hash you gave in submitAnswerCommitment() /// @param bond The bond that you paid in your submitAnswerCommitment() transaction function submitAnswerReveal(bytes32 question_id, bytes32 answer, uint256 nonce, uint256 bond) external { } /// @notice Notify the contract that the arbitrator has been paid for a question, freezing it pending their decision. /// @dev The arbitrator contract is trusted to only call this if they've been paid, and tell us who paid them. /// @param question_id The ID of the question /// @param requester The account that requested arbitration /// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction. function notifyOfArbitrationRequest(bytes32 question_id, address requester, uint256 max_previous) external { } /// @notice Submit the answer for a question, for use by the arbitrator. /// @dev Doesn't require (or allow) a bond. /// If the current final answer is correct, the account should be whoever submitted it. /// If the current final answer is wrong, the account should be whoever paid for arbitration. /// However, the answerer stipulations are not enforced by the contract. /// @param question_id The ID of the question /// @param answer The answer, encoded into bytes32 /// @param answerer The account credited with this answer for the purpose of bond claims function submitAnswerByArbitrator(bytes32 question_id, bytes32 answer, address answerer) external { } /// @notice Report whether the answer to the specified question is finalized /// @param question_id The ID of the question /// @return Return true if finalized function isFinalized(bytes32 question_id) view public returns (bool) { } /// @notice (Deprecated) Return the final answer to the specified question, or revert if there isn't one /// @param question_id The ID of the question /// @return The answer formatted as a bytes32 function getFinalAnswer(bytes32 question_id) external view returns (bytes32) { } /// @notice Return the final answer to the specified question, or revert if there isn't one /// @param question_id The ID of the question /// @return The answer formatted as a bytes32 function resultFor(bytes32 question_id) external view returns (bytes32) { } /// @notice Return the final answer to the specified question, provided it matches the specified criteria. /// @dev Reverts if the question is not finalized, or if it does not match the specified criteria. /// @param question_id The ID of the question /// @param content_hash The hash of the question content (template ID + opening time + question parameter string) /// @param arbitrator The arbitrator chosen for the question (regardless of whether they are asked to arbitrate) /// @param min_timeout The timeout set in the initial question settings must be this high or higher /// @param min_bond The bond sent with the final answer must be this high or higher /// @return The answer formatted as a bytes32 function getFinalAnswerIfMatches( bytes32 question_id, bytes32 content_hash, address arbitrator, uint32 min_timeout, uint256 min_bond ) external view returns (bytes32) { } /// @notice Assigns the winnings (bounty and bonds) to everyone who gave the accepted answer /// Caller must provide the answer history, in reverse order /// @dev Works up the chain and assign bonds to the person who gave the right answer /// If someone gave the winning answer earlier, they must get paid from the higher bond /// That means we can't pay out the bond added at n until we have looked at n-1 /// The first answer is authenticated by checking against the stored history_hash. /// One of the inputs to history_hash is the history_hash before it, so we use that to authenticate the next entry, etc /// Once we get to a null hash we'll know we're done and there are no more answers. /// Usually you would call the whole thing in a single transaction, but if not then the data is persisted to pick up later. /// @param question_id The ID of the question /// @param history_hashes Second-last-to-first, the hash of each history entry. (Final one should be empty). /// @param addrs Last-to-first, the address of each answerer or commitment sender /// @param bonds Last-to-first, the bond supplied with each answer or commitment /// @param answers Last-to-first, each answer supplied, or commitment ID if the answer was supplied with commit->reveal function claimWinnings( bytes32 question_id, bytes32[] history_hashes, address[] addrs, uint256[] bonds, bytes32[] answers ) public { } /// @notice Convenience function to assign bounties/bonds for multiple questions in one go, then withdraw all your funds. /// Caller must provide the answer history for each question, in reverse order /// @dev Can be called by anyone to assign bonds/bounties, but funds are only withdrawn for the user making the call. /// @param question_ids The IDs of the questions you want to claim for /// @param lengths The number of history entries you will supply for each question ID /// @param hist_hashes In a single list for all supplied questions, the hash of each history entry. /// @param addrs In a single list for all supplied questions, the address of each answerer or commitment sender /// @param bonds In a single list for all supplied questions, the bond supplied with each answer or commitment /// @param answers In a single list for all supplied questions, each answer supplied, or commitment ID function claimMultipleAndWithdrawBalance( bytes32[] question_ids, uint256[] lengths, bytes32[] hist_hashes, address[] addrs, uint256[] bonds, bytes32[] answers ) public { } /// @notice Returns the questions's content hash, identifying the question content /// @param question_id The ID of the question function getContentHash(bytes32 question_id) public view returns(bytes32) { } /// @notice Returns the arbitrator address for the question /// @param question_id The ID of the question function getArbitrator(bytes32 question_id) public view returns(address) { } /// @notice Returns the timestamp when the question can first be answered /// @param question_id The ID of the question function getOpeningTS(bytes32 question_id) public view returns(uint32) { } /// @notice Returns the timeout in seconds used after each answer /// @param question_id The ID of the question function getTimeout(bytes32 question_id) public view returns(uint32) { } /// @notice Returns the timestamp at which the question will be/was finalized /// @param question_id The ID of the question function getFinalizeTS(bytes32 question_id) public view returns(uint32) { } /// @notice Returns whether the question is pending arbitration /// @param question_id The ID of the question function isPendingArbitration(bytes32 question_id) public view returns(bool) { } /// @notice Returns the current total unclaimed bounty /// @dev Set back to zero once the bounty has been claimed /// @param question_id The ID of the question function getBounty(bytes32 question_id) public view returns(uint256) { } /// @notice Returns the current best answer /// @param question_id The ID of the question function getBestAnswer(bytes32 question_id) public view returns(bytes32) { } /// @notice Returns the history hash of the question /// @param question_id The ID of the question /// @dev Updated on each answer, then rewound as each is claimed function getHistoryHash(bytes32 question_id) public view returns(bytes32) { } /// @notice Returns the highest bond posted so far for a question /// @param question_id The ID of the question function getBond(bytes32 question_id) public view returns(uint256) { } } /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string memory self) internal pure returns (slice memory) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-terminated utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal pure returns (slice memory ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice memory self) internal pure returns (slice memory) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice memory self) internal pure returns (string memory) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice memory self) internal pure returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about uint ptr = self._ptr - 31; uint end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice memory self) internal pure returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice memory self, slice memory other) internal pure returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; uint selfptr = self._ptr; uint otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint256 mask = uint256(-1); // 0xffff... if(shortest < 32) { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice memory self, slice memory other) internal pure returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint l; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { l = 1; } else if(b < 0xE0) { l = 2; } else if(b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice memory self) internal pure returns (slice memory ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice memory self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if(b < 0xE0) { ret = b & 0x1F; length = 2; } else if(b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice memory self) internal pure returns (bytes32 ret) { assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } uint selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } uint selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly { ptrdata := and(mload(ptr), mask) } } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice memory self, slice memory needle) internal pure returns (slice memory token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice memory self, slice memory needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice memory self, slice memory needle) internal pure returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice memory self, slice memory other) internal pure returns (string memory) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice memory self, slice[] memory parts) internal pure returns (string memory) { if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) length += parts[i]._len; string memory ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } contract ICash{} contract IMarket { function getWinningPayoutNumerator(uint256 _outcome) public view returns (uint256); function isFinalized() public view returns (bool); function isInvalid() public view returns (bool); } contract IUniverse { function getWinningChildUniverse() public view returns (IUniverse); function createYesNoMarket(uint256 _endTime, uint256 _feePerEthInWei, ICash _denominationToken, address _designatedReporterAddress, bytes32 _topic, string _description, string _extraInfo) public payable returns (IMarket _newMarket); } contract RealitioAugurArbitrator is BalanceHolder { using strings for *; IRealitio public realitio; uint256 public template_id; uint256 dispute_fee; ICash public market_token; IUniverse public latest_universe; bytes32 constant REALITIO_INVALID = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; bytes32 constant REALITIO_YES = 0x0000000000000000000000000000000000000000000000000000000000000001; bytes32 constant REALITIO_NO = 0x0000000000000000000000000000000000000000000000000000000000000000; uint256 constant AUGUR_YES_INDEX = 1; uint256 constant AUGUR_NO_INDEX = 0; string constant REALITIO_DELIMITER = '␟'; event LogRequestArbitration( bytes32 indexed question_id, uint256 fee_paid, address requester, uint256 remaining ); struct RealitioQuestion { uint256 bounty; address disputer; IMarket augur_market; address owner; } mapping(bytes32 => RealitioQuestion) public realitio_questions; modifier onlyInitialized() { require(dispute_fee > 0, "The contract cannot be used until a dispute fee has been set"); _; } modifier onlyUninitialized() { require(dispute_fee == 0, "The contract can only be initialized once"); _; } /// @notice Initialize a new contract /// @param _realitio The address of the realitio contract you arbitrate for /// @param _template_id The ID of the realitio template we support. /// @param _dispute_fee The fee this contract will charge for resolution /// @param _genesis_universe The earliest supported Augur universe /// @param _market_token The token used by the market we create, typically Augur's wrapped ETH function initialize(IRealitio _realitio, uint256 _template_id, uint256 _dispute_fee, IUniverse _genesis_universe, ICash _market_token) onlyUninitialized external { require(_dispute_fee > 0, "You must provide a dispute fee"); require(_realitio != IRealitio(0x0), "You must provide a realitio address"); require(_genesis_universe != IUniverse(0x0), "You must provide a genesis universe"); require(_market_token != ICash(0x0), "You must provide an augur cash token"); dispute_fee = _dispute_fee; template_id = _template_id; realitio = _realitio; latest_universe = _genesis_universe; market_token = _market_token; } /// @notice Register a new child universe after a fork /// @dev Anyone can create Augur universes but the "correct" ones should be in a single line from the official genesis universe /// @dev If a universe goes into a forking state, someone will need to call this before you can create new markets. function addForkedUniverse() onlyInitialized external { IUniverse child_universe = IUniverse(latest_universe).getWinningChildUniverse(); latest_universe = child_universe; } /// @notice Trim the realitio question content to the part before the initial delimiter. /// @dev The Realitio question is a list of parameters for a template. /// @dev We throw away the subsequent parameters of the question. /// @dev The first item in the (supported) template must be the title. /// @dev Subsequent items (category, lang) aren't needed in Augur. /// @dev This does not support more complex templates, eg selects which also need a list of answrs. function _trimQuestion(string q) internal pure returns (string) { return q.toSlice().split(REALITIO_DELIMITER.toSlice()).toString(); } function _callAugurMarketCreate(bytes32 question_id, string question, address designated_reporter) internal { realitio_questions[question_id].augur_market = latest_universe.createYesNoMarket.value(msg.value)( now, 0, market_token, designated_reporter, 0x0, _trimQuestion(question), ""); realitio_questions[question_id].owner = msg.sender; } /// @notice Create a market in Augur and store the creator as its owner /// @dev Anyone can call this, and calling this will give them the rights to claim the bounty /// @dev They will need have sent this contract some REP for the no-show bond. /// @param question The question content (a delimited parameter list) /// @param timeout The timeout between rounds, set when the question was created /// @param opening_ts The opening timestamp for the question, set when the question was created /// @param asker The address that created the question, ie the msg.sender of the original realitio.askQuestion call /// @param nonce The nonce for the question, set when the question was created /// @param designated_reporter The Augur designated reporter. We let the market creator choose this, if it's bad the Augur dispute resolution should sort it out function createMarket( string question, uint32 timeout, uint32 opening_ts, address asker, uint256 nonce, address designated_reporter ) onlyInitialized external payable { // Reconstruct the question ID from the content bytes32 question_id = keccak256(keccak256(template_id, opening_ts, question), this, timeout, asker, nonce); require(realitio_questions[question_id].bounty > 0, "Arbitration must have been requested (paid for)"); require(realitio_questions[question_id].augur_market == IMarket(0x0), "The market must not have been created yet"); // Create a market in Augur _callAugurMarketCreate(question_id, question, designated_reporter); } /// @notice Return data needed to verify the last history item /// @dev Filters the question struct from Realitio to stuff we need /// @dev Broken out into its own function to avoid stack depth limitations /// @param question_id The realitio question /// @param last_history_hash The history hash when you gave your answer /// @param last_answer_or_commitment_id The last answer given, or its commitment ID if it was a commitment /// @param last_bond The bond paid in the last answer given /// @param last_answerer The account that submitted the last answer (or its commitment) /// @param is_commitment Whether the last answer was submitted with commit->reveal function _verifyInput( bytes32 question_id, bytes32 last_history_hash, bytes32 last_answer_or_commitment_id, uint256 last_bond, address last_answerer, bool is_commitment ) internal view returns (bool, bytes32) { require(realitio.isPendingArbitration(question_id), "The question must be pending arbitration in realitio"); bytes32 history_hash = realitio.getHistoryHash(question_id); require(history_hash == keccak256(last_history_hash, last_answer_or_commitment_id, last_bond, last_answerer, is_commitment), "The history parameters supplied must match the history hash in the realitio contract"); } /// @notice Given the last history entry, get whether they had a valid answer if so what it was /// @dev These just need to be fetched from Realitio, but they can't be fetched directly because we don't store them to save gas /// @dev To get the final answer, we need to reconstruct the final answer using the history hash /// @dev TODO: This should probably be in a library offered by Realitio /// @param question_id The ID of the realitio question /// @param last_history_hash The history hash when you gave your answer /// @param last_answer_or_commitment_id The last answer given, or its commitment ID if it was a commitment /// @param last_bond The bond paid in the last answer given /// @param last_answerer The account that submitted the last answer (or its commitment) /// @param is_commitment Whether the last answer was submitted with commit->reveal function _answerData( bytes32 question_id, bytes32 last_history_hash, bytes32 last_answer_or_commitment_id, uint256 last_bond, address last_answerer, bool is_commitment ) internal view returns (bool, bytes32) { bool is_pending_arbitration; bytes32 history_hash; // If the question hasn't been answered, nobody is ever right if (last_bond == 0) { return (false, bytes32(0)); } bytes32 last_answer; bool is_answered; if (is_commitment) { uint256 reveal_ts; bool is_revealed; bytes32 revealed_answer; (reveal_ts, is_revealed, revealed_answer) = realitio.commitments(last_answer_or_commitment_id); if (is_revealed) { last_answer = revealed_answer; is_answered = true; } else { // Shouldn't normally happen, but if the last answerer might still reveal when we are called, bail out and wait for them. require(reveal_ts < uint32(now), "Arbitration cannot be done until the last answerer has had time to reveal their commitment"); is_answered = false; } } else { last_answer = last_answer_or_commitment_id; is_answered = true; } return (is_answered, last_answer); } /// @notice Get the answer from the Augur market and map it to a Realitio value /// @param market The Augur market function realitioAnswerFromAugurMarket( IMarket market ) onlyInitialized public view returns (bytes32) { bytes32 answer; if (market.isInvalid()) { answer = REALITIO_INVALID; } else { uint256 no_val = market.getWinningPayoutNumerator(AUGUR_NO_INDEX); uint256 yes_val = market.getWinningPayoutNumerator(AUGUR_YES_INDEX); if (yes_val == no_val) { answer = REALITIO_INVALID; } else { if (yes_val > no_val) { answer = REALITIO_YES; } else { answer = REALITIO_NO; } } } return answer; } /// @notice Report the answer from a finalized Augur market to a Realitio contract with a question awaiting arbitration /// @dev Pays the arbitration bounty to whoever created the Augur market. Probably the same person will call this function, but they don't have to. /// @dev We need to know who gave the final answer and what it was, as they need to be supplied as the arbitration winner if the last answer is right /// @dev These just need to be fetched from Realitio, but they can't be fetched directly because to save gas, Realitio doesn't store them /// @dev To get the final answer, we need to reconstruct the final answer using the history hash /// @param question_id The ID of the question you're reporting on /// @param last_history_hash The history hash when you gave your answer /// @param last_answer_or_commitment_id The last answer given, or its commitment ID if it was a commitment /// @param last_bond The bond paid in the last answer given /// @param last_answerer The account that submitted the last answer (or its commitment) /// @param is_commitment Whether the last answer was submitted with commit->reveal function reportAnswer( bytes32 question_id, bytes32 last_history_hash, bytes32 last_answer_or_commitment_id, uint256 last_bond, address last_answerer, bool is_commitment ) onlyInitialized public { IMarket market = realitio_questions[question_id].augur_market; // There must be an open bounty require(realitio_questions[question_id].bounty > 0, "Arbitration must have been requested for this question"); bool is_answered; // the answer was provided, not just left as an unrevealed commit bytes32 last_answer; _verifyInput(question_id, last_history_hash, last_answer_or_commitment_id, last_bond, last_answerer, is_commitment); (is_answered, last_answer) = _answerData(question_id, last_history_hash, last_answer_or_commitment_id, last_bond, last_answerer, is_commitment); require(market.isFinalized(), "The augur market must have been finalized"); bytes32 answer = realitioAnswerFromAugurMarket(market); address winner; if (is_answered && last_answer == answer) { winner = last_answerer; } else { // If the final answer is wrong, we assign the person who paid for arbitration. // See https://realitio.github.io/docs/html/arbitrators.html for why. winner = realitio_questions[question_id].disputer; } realitio.submitAnswerByArbitrator(question_id, answer, winner); address owner = realitio_questions[question_id].owner; balanceOf[owner] += realitio_questions[question_id].bounty; delete realitio_questions[question_id]; } /// @notice Return the dispute fee for the specified question. 0 indicates that we won't arbitrate it. /// @dev Uses a general default, but can be over-ridden on a question-by-question basis. function getDisputeFee(bytes32) external view returns (uint256) { return dispute_fee; } /// @notice Request arbitration, freezing the question until we send submitAnswerByArbitrator /// @dev The bounty can be paid only in part, in which case the last person to pay will be considered the payer /// @dev Will trigger an error if the notification fails, eg because the question has already been finalized /// @param question_id The question in question /// @param max_previous The highest bond level we should accept (used to check the state hasn't changed) function requestArbitration(bytes32 question_id, uint256 max_previous) onlyInitialized external payable returns (bool) { require(msg.value >= dispute_fee, "The payment must cover the fee"); realitio.notifyOfArbitrationRequest(question_id, msg.sender, max_previous); realitio_questions[question_id].bounty = msg.value; realitio_questions[question_id].disputer = msg.sender; LogRequestArbitration(question_id, msg.value, msg.sender, 0); } }
Submit the answer whose hash you sent in a previous submitAnswerCommitment() transaction Checks the parameters supplied recreate an existing commitment, and stores the revealed answer Updates the current answer unless someone has since supplied a new answer with a higher bond msg.sender is intentionally not restricted to the user who originally sent the commitment; For example, the user may want to provide the answer+nonce to a third-party service and let them send the tx NB If we are pending arbitration, it will be up to the arbitrator to wait and see any outstanding reveal is sent question_id The ID of the question answer The answer, encoded as bytes32 nonce The nonce that, combined with the answer, recreates the answer_hash you gave in submitAnswerCommitment() bond The bond that you paid in your submitAnswerCommitment() transaction
function submitAnswerReveal(bytes32 question_id, bytes32 answer, uint256 nonce, uint256 bond) external { }
1,808,939
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; // OpenZeppelin library for performing math operations without overflows. import "@openzeppelin/contracts/utils/math/SafeMath.sol"; // OpenZeppelin security library for preventing reentrancy attacks. import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; // For checking `supportsInterface`. import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; // For interacting with NFT tokens. import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; contract IMediaModified { mapping(uint256 => address) public tokenCreators; } interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); } interface Royalties { function deposit() external payable; } contract ReserveAuctionV3 is ReentrancyGuard { // Use OpenZeppelin's SafeMath library to prevent overflows. using SafeMath for uint256; // ============ Constants ============ // The minimum amount of time left in an auction after a new bid is created; 15 min. uint16 public constant TIME_BUFFER = 0; // The ETH needed above the current bid for a new bid to be valid; 0.001 ETH. uint8 public constant MIN_BID_INCREMENT_PERCENT = 10; // Interface constant for ERC721, to check values in constructor. bytes4 private constant ERC721_INTERFACE_ID = 0x80ac58cd; // Allows external read `getVersion()` to return a version for the auction. uint256 private constant RESERVE_AUCTION_VERSION = 1; // ============ Immutable Storage ============ // The address of the ERC721 contract for tokens auctioned via this contract. address public immutable nftContract; // The address of the WETH contract, so that ETH can be transferred via // WETH if native ETH transfers fail. address public immutable wethAddress; // The address that initially is able to recover assets. address public immutable adminRecoveryAddress; // ============ Mutable Storage ============ bool private _adminRecoveryEnabled; bool private _paused; // A mapping of all of the auctions currently running. mapping(uint256 => Auction) public auctions; // The address of the creator pool address public creatorPoolAddress; // ============ Structs ============ struct Auction { // The value of the current highest bid. uint256 amount; // The amount of time that the auction should run for, // after the first bid was made. uint256 duration; // The time of the first bid. uint256 firstBidTime; // The minimum price of the first bid. uint256 reservePrice; uint8 curatorFeePercent; // The address of the auction's curator. The curator // can cancel the auction if it hasn't had a bid yet. address curator; // The address of the current highest bid. address payable bidder; // The address that should receive funds once the NFT is sold. address payable fundsRecipient; } // ============ Events ============ // All of the details of a new auction, // with an index created for the tokenId. event AuctionCreated( uint256 indexed tokenId, address nftContractAddress, uint256 duration, uint256 reservePrice, uint8 curatorFeePercent, address curator, address fundsRecipient ); // All of the details of a new bid, // with an index created for the tokenId. event AuctionBid( uint256 indexed tokenId, address nftContractAddress, address sender, uint256 value ); // All of the details of an auction's cancelation, // with an index created for the tokenId. event AuctionCanceled( uint256 indexed tokenId, address nftContractAddress, address curator ); // All of the details of an auction's close, // with an index created for the tokenId. event AuctionEnded( uint256 indexed tokenId, address nftContractAddress, address curator, address winner, uint256 amount, address nftCreator, address payable fundsRecipient ); // When the curator recevies fees, emit the details including the amount, // with an index created for the tokenId. event CuratorFeePercentTransfer( uint256 indexed tokenId, address curator, uint256 amount ); // Emitted in the case that the contract is paused. event Paused(address account); // Emitted when the contract is unpaused. event Unpaused(address account); // ============ Modifiers ============ // Reverts if the sender is not admin, or admin // functionality has been turned off. modifier onlyAdminRecovery() { require( // The sender must be the admin address, and // adminRecovery must be set to true. adminRecoveryAddress == msg.sender && adminRecoveryEnabled(), "Caller does not have admin privileges" ); _; } // Reverts if the sender is not the auction's curator. modifier onlyCurator(uint256 tokenId) { require( auctions[tokenId].curator == msg.sender, "Can only be called by auction curator" ); _; } // Reverts if the contract is paused. modifier whenNotPaused() { require(!paused(), "Contract is paused"); _; } // Reverts if the auction does not exist. modifier auctionExists(uint256 tokenId) { // The auction exists if the curator is not null. require(!auctionCuratorIsNull(tokenId), "Auction doesn't exist"); _; } // Reverts if the auction exists. modifier auctionNonExistant(uint256 tokenId) { // The auction does not exist if the curator is null. require(auctionCuratorIsNull(tokenId), "Auction already exists"); _; } // Reverts if the auction is expired. modifier auctionNotExpired(uint256 tokenId) { require( // Auction is not expired if there's never been a bid, or if the // current time is less than the time at which the auction ends. auctions[tokenId].firstBidTime == 0 || block.timestamp < auctionEnds(tokenId), "Auction expired" ); _; } // Reverts if the auction is not complete. // Auction is complete if there was a bid, and the time has run out. modifier auctionComplete(uint256 tokenId) { require( // Auction is complete if there has been a bid, and the current time // is greater than the auction's end time. auctions[tokenId].firstBidTime > 0 && block.timestamp >= auctionEnds(tokenId), "Auction hasn't completed" ); _; } // ============ Constructor ============ constructor( address nftContract_, address wethAddress_, address adminRecoveryAddress_, address creatorPoolAddress_ ) { require( IERC165(nftContract_).supportsInterface(ERC721_INTERFACE_ID), "Contract at nftContract_ address does not support NFT interface" ); // Initialize immutable memory. nftContract = nftContract_; wethAddress = wethAddress_; adminRecoveryAddress = adminRecoveryAddress_; creatorPoolAddress = creatorPoolAddress_; // Initialize mutable memory. _paused = false; _adminRecoveryEnabled = true; } // ============ Create Auction ============ function createAuction( uint256 tokenId, uint256 duration, uint256 reservePrice, uint8 curatorFeePercent, address curator, address payable fundsRecipient ) external nonReentrant whenNotPaused auctionNonExistant(tokenId) { // Check basic input requirements are reasonable. require(curator != address(0)); require(fundsRecipient != address(0)); require(curatorFeePercent < 100, "Curator fee should be < 100"); // Initialize the auction details, including null values. auctions[tokenId] = Auction({ duration: duration, reservePrice: reservePrice, curatorFeePercent: curatorFeePercent, curator: curator, fundsRecipient: fundsRecipient, amount: 0, firstBidTime: 0, bidder: payable(address(0)) }); // Transfer the NFT into this auction contract, from whoever owns it. IERC721(nftContract).transferFrom( IERC721(nftContract).ownerOf(tokenId), address(this), tokenId ); // Emit an event describing the new auction. emit AuctionCreated( tokenId, nftContract, duration, reservePrice, curatorFeePercent, curator, fundsRecipient ); } // ============ Create Bid ============ function createBid(uint256 tokenId, uint256 amount) external payable nonReentrant whenNotPaused auctionExists(tokenId) auctionNotExpired(tokenId) { // Validate that the user's expected bid value matches the ETH deposit. require(amount == msg.value, "Amount doesn't equal msg.value"); require(amount > 0, "Amount must be greater than 0"); // Check if the current bid amount is 0. if (auctions[tokenId].amount == 0) { // If so, it is the first bid. auctions[tokenId].firstBidTime = block.timestamp; // We only need to check if the bid matches reserve bid for the first bid, // since future checks will need to be higher than any previous bid. require( amount >= auctions[tokenId].reservePrice, "Must bid reservePrice or more" ); } else { // Check that the new bid is sufficiently higher than the previous bid, by // the percentage defined as MIN_BID_INCREMENT_PERCENT. require( amount >= auctions[tokenId].amount.add( // Add 10% of the current bid to the current bid. auctions[tokenId] .amount .mul(MIN_BID_INCREMENT_PERCENT) .div(100) ), "Must bid more than last bid by MIN_BID_INCREMENT_PERCENT amount" ); // Refund the previous bidder. transferETHOrWETH( auctions[tokenId].bidder, auctions[tokenId].amount ); } // Update the current auction. auctions[tokenId].amount = amount; auctions[tokenId].bidder = payable(msg.sender); // Compare the auction's end time with the current time plus the 15 minute extension, // to see whether we're near the auctions end and should extend the auction. if (auctionEnds(tokenId) < block.timestamp.add(TIME_BUFFER)) { // We add onto the duration whenever time increment is required, so // that the auctionEnds at the current time plus the buffer. auctions[tokenId].duration += block.timestamp.add(TIME_BUFFER).sub( auctionEnds(tokenId) ); } // Emit the event that a bid has been made. emit AuctionBid(tokenId, nftContract, msg.sender, amount); } // ============ End Auction ============ function endAuction(uint256 tokenId) external nonReentrant whenNotPaused auctionComplete(tokenId) { // Store relevant auction data in memory for the life of this function. address winner = auctions[tokenId].bidder; uint256 amount = auctions[tokenId].amount; address curator = auctions[tokenId].curator; uint8 curatorFeePercent = auctions[tokenId].curatorFeePercent; address payable fundsRecipient = auctions[tokenId].fundsRecipient; // Remove all auction data for this token from storage. delete auctions[tokenId]; // We don't use safeTransferFrom, to prevent reverts at this point, // which would break the auction. IERC721(nftContract).transferFrom(address(this), winner, tokenId); // First handle the curator's fee. if (curatorFeePercent > 0) { // Determine the curator amount, which is some percent of the total. uint256 curatorAmount = amount.mul(curatorFeePercent).div(100); // Send it to the curator. transferETHOrWETH(curator, curatorAmount); // Subtract the curator amount from the total funds available // to send to the funds recipient and original NFT creator. amount = amount.sub(curatorAmount); // Emit the details of the transfer as an event. emit CuratorFeePercentTransfer(tokenId, curator, curatorAmount); } // Get the address of the original creator, so that we can split shares // if appropriate. address payable nftCreator = payable( address(IMediaModified(nftContract).tokenCreators(tokenId)) ); // Otherwise, we should determine the percent that goes to the creator. // Collect share data from Zora. uint256 creatorAmount = calculatePercentage(amount, 6000); // 60% goes to the creator uint256 poolAmount = calculatePercentage(amount, 300); // 3% to the pool // Send the creator's share to the creator. transferETHOrWETH(nftCreator, creatorAmount); // Send the pools share to the pool transferETHOrWETH(creatorPoolAddress, poolAmount); // Send the remainder of the amount to the funds recipient. transferETHOrWETH(fundsRecipient, amount.sub(creatorAmount).sub(poolAmount)); // Emit an event describing the end of the auction. emit AuctionEnded( tokenId, nftContract, curator, winner, amount, nftCreator, fundsRecipient ); } function calculatePercentage( uint amount, uint bp ) internal pure returns (uint) { return amount * bp / 10000; } // ============ Cancel Auction ============ function cancelAuction(uint256 tokenId) external nonReentrant auctionExists(tokenId) onlyCurator(tokenId) { // Check that there hasn't already been a bid for this NFT. require( uint256(auctions[tokenId].firstBidTime) == 0, "Auction already started" ); // Pull the creator address before removing the auction. address curator = auctions[tokenId].curator; // Remove all data about the auction. delete auctions[tokenId]; // Transfer the NFT back to the curator. IERC721(nftContract).transferFrom(address(this), curator, tokenId); // Emit an event describing that the auction has been canceled. emit AuctionCanceled(tokenId, nftContract, curator); } // ============ Admin Functions ============ // Irrevocably turns off admin recovery. function turnOffAdminRecovery() external onlyAdminRecovery { _adminRecoveryEnabled = false; } function pauseContract() external onlyAdminRecovery { _paused = true; emit Paused(msg.sender); } function unpauseContract() external onlyAdminRecovery { _paused = false; emit Unpaused(msg.sender); } // Allows the admin to transfer any NFT from this contract // to the recovery address. function recoverNFT(uint256 tokenId) external onlyAdminRecovery { IERC721(nftContract).transferFrom( // From the auction contract. address(this), // To the recovery account. adminRecoveryAddress, // For the specified token. tokenId ); } // Allows the admin to transfer any ETH from this contract to the recovery address. function recoverETH(uint256 amount) external onlyAdminRecovery returns (bool success) { // Attempt an ETH transfer to the recovery account, and return true if it succeeds. success = attemptETHTransfer(adminRecoveryAddress, amount); } // ============ Miscellaneous Public and External ============ // Returns true if the contract is paused. function setCreatorPool(address newCreatorPoolAddress) public onlyAdminRecovery { creatorPoolAddress = newCreatorPoolAddress; } // Returns true if the contract is paused. function paused() public view returns (bool) { return _paused; } // Returns true if admin recovery is enabled. function adminRecoveryEnabled() public view returns (bool) { return _adminRecoveryEnabled; } // Returns the version of the deployed contract. function getVersion() external pure returns (uint256 version) { version = RESERVE_AUCTION_VERSION; } // ============ Private Functions ============ // Will attempt to transfer ETH, but will transfer WETH instead if it fails. function transferETHOrWETH(address to, uint256 value) private { // Try to transfer ETH to the given recipient. if (!attemptETHTransfer(to, value)) { // If the transfer fails, wrap and send as WETH, so that // the auction is not impeded and the recipient still // can claim ETH via the WETH contract (similar to escrow). IWETH(wethAddress).deposit{value: value}(); IWETH(wethAddress).transfer(to, value); // At this point, the recipient can unwrap WETH. } } // Sending ETH is not guaranteed complete, and the method used here will return false if // it fails. For example, a contract can block ETH transfer, or might use // an excessive amount of gas, thereby griefing a new bidder. // We should limit the gas used in transfers, and handle failure cases. function attemptETHTransfer(address to, uint256 value) private returns (bool) { // Here increase the gas limit a reasonable amount above the default, and try // to send ETH to the recipient. // NOTE: This might allow the recipient to attempt a limited reentrancy attack. (bool success, ) = to.call{value: value, gas: 30000}(""); return success; } // Returns true if the auction's curator is set to the null address. function auctionCuratorIsNull(uint256 tokenId) private view returns (bool) { // The auction does not exist if the curator is the null address, // since the NFT would not have been transferred in `createAuction`. return auctions[tokenId].curator == address(0); } // Returns the timestamp at which an auction will finish. function auctionEnds(uint256 tokenId) private view returns (uint256) { // Derived by adding the auction's duration to the time of the first bid. // NOTE: duration can be extended conditionally after each new bid is added. return auctions[tokenId].firstBidTime.add(auctions[tokenId].duration); } } // 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; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; }
Sending ETH is not guaranteed complete, and the method used here will return false if it fails. For example, a contract can block ETH transfer, or might use an excessive amount of gas, thereby griefing a new bidder. We should limit the gas used in transfers, and handle failure cases. Here increase the gas limit a reasonable amount above the default, and try to send ETH to the recipient. NOTE: This might allow the recipient to attempt a limited reentrancy attack.
function attemptETHTransfer(address to, uint256 value) private returns (bool) { return success; }
109,255
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; interface IBrincStaking { function totalRewards(address _user) external view returns (uint256); } contract StakedBrincGovToken is ERC20, ERC20Burnable, Ownable { using SafeMath for uint256; mapping(address => bool) public isMinter; IBrincStaking public staking; event Mint(address _to, uint256 amount); event Burn(address _from, uint256 amount); event StakingUpdated(address _staking); event SetMinter(address _minter, bool _isMinter); constructor() public ERC20("StakedBrincGovToken", "sgBRC") { isMinter[msg.sender] = true; } modifier onlyMinter { require(isMinter[msg.sender], "onlyMinter: only minter can call this operation"); _; } /** * @dev mint will create specified number of tokens to specified address. * only a minter will be able to call this method. * * @param _to address to mint tokens to * @param _amount amount of tokens to mint * */ /// #if_succeeds {:msg "mint: The sender must be Minter"} /// isMinter[msg.sender] == true; /// #if_succeeds {:msg "mint: balance of receiving address is correct after mint"} /// this.balanceOf(_to) == old(this.balanceOf(_to) + _amount); function mint(address _to, uint256 _amount) public onlyMinter { _mint(_to, _amount); emit Mint(_to, _amount); } /** * @dev setStaking will set the address of the staking contract. * only the owner will be able to call this method. * * @param _staking address of the staking contract * */ /// #if_succeeds {:msg "setStaking: The sender must be owner"} /// old(msg.sender == this.owner()); function setStaking(IBrincStaking _staking) public onlyOwner { staking = _staking; emit StakingUpdated(address(_staking)); } /** * @dev setMinter will set and allow the specified address to mint sgBRC tokens. * only the owner will be able to call this method. * changing _isMinter to false will revoke minting privileges. * * @param _address address of minter * @param _isMinter bool access * */ /// #if_succeeds {:msg "setMinter: The sender must be owner"} /// old(msg.sender == this.owner()); function setMinter(address _minter, bool _isMinter) public onlyOwner { require(_minter != address(0), "invalid minter address"); isMinter[_minter] = _isMinter; emit SetMinter(_minter, _isMinter); } /** * @dev balanceOf is the override method that will show the number of staked tokens + totalrewards. * the new balanceOf will relect the total sgBRC balance, which will include any accured award that may not have been minted to gBRC yet. * * @return balanceOf(address) */ function balanceOf(address owner) public view virtual override returns (uint256) { require(address(staking) != address(0x0), "staking contract not set"); return super.balanceOf(owner).add(staking.totalRewards(owner)); } function _beforeTokenTransfer( address from, address to, uint256 ) internal override { require(from == address(0x0) || to == address(0x0), "Transfer not allowed between accounts"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @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 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); }
mint will create specified number of tokens to specified address. only a minter will be able to call this method. _to address to mint tokens to _amount amount of tokens to mint/ if_succeeds {:msg "mint: The sender must be Minter"} isMinter[msg.sender] == true; if_succeeds {:msg "mint: balance of receiving address is correct after mint"} this.balanceOf(_to) == old(this.balanceOf(_to) + _amount);
function mint(address _to, uint256 _amount) public onlyMinter { _mint(_to, _amount); emit Mint(_to, _amount); }
1,727,775
./partial_match/43114/0xbcdf6876582C371B53BFA9759388EE3190719EeD/sources/contracts/Ola/Peripheral/PriceOracle/Fixed/FixedPriceOracle.sol
Get the underlying price of a cToken asset asset The asset (Erc20 or native) return The asset price mantissa (scaled by 1e(36 - assetDecimals)). Zero means the price is unavailable./ All fixed prices are scaled by 1e6
function _getPriceForAssetInternal(address asset) internal view returns (uint) { uint storedFixedPrice = prices[asset]; uint8 assetDecimals = assetsDecimals[asset]; if (storedFixedPrice == 0) { return 0; return (mul(1e30, storedFixedPrice) / (10 ** assetDecimals)); } }
3,505,237
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {PercentageMath} from '../protocol/libraries/math/PercentageMath.sol'; import {SafeMath} from '../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IERC20WithPermit} from '../interfaces/IERC20WithPermit.sol'; import {FlashLoanReceiverBase} from '../flashloan/base/FlashLoanReceiverBase.sol'; import {IBaseUniswapAdapter} from './interfaces/IBaseUniswapAdapter.sol'; /** * @title BaseUniswapAdapter * @notice Implements the logic for performing assets swaps in Uniswap V2 * @author Aave **/ abstract contract BaseUniswapAdapter is FlashLoanReceiverBase, IBaseUniswapAdapter, Ownable { using SafeMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; // Max slippage percent allowed uint256 public constant override MAX_SLIPPAGE_PERCENT = 3000; // 30% // FLash Loan fee set in lending pool uint256 public constant override FLASHLOAN_PREMIUM_TOTAL = 9; // USD oracle asset address address public constant override USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96; address public immutable override WETH_ADDRESS; IPriceOracleGetter public immutable override ORACLE; IUniswapV2Router02 public immutable override UNISWAP_ROUTER; constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public FlashLoanReceiverBase(addressesProvider) { ORACLE = IPriceOracleGetter(addressesProvider.getPriceOracle()); UNISWAP_ROUTER = uniswapRouter; WETH_ADDRESS = wethAddress; } /** * @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices * @param amountIn Amount of reserveIn * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount out of the reserveOut * @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function getAmountsOut( uint256 amountIn, address reserveIn, address reserveOut ) external view override returns ( uint256, uint256, uint256, uint256, address[] memory ) { AmountCalc memory results = _getAmountsOutData(reserveIn, reserveOut, amountIn); return ( results.calculatedAmount, results.relativePrice, results.amountInUsd, results.amountOutUsd, results.path ); } /** * @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices * @param amountOut Amount of reserveOut * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount in of the reserveIn * @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function getAmountsIn( uint256 amountOut, address reserveIn, address reserveOut ) external view override returns ( uint256, uint256, uint256, uint256, address[] memory ) { AmountCalc memory results = _getAmountsInData(reserveIn, reserveOut, amountOut); return ( results.calculatedAmount, results.relativePrice, results.amountInUsd, results.amountOutUsd, results.path ); } /** * @dev Swaps an exact `amountToSwap` of an asset to another * @param assetToSwapFrom Origin asset * @param assetToSwapTo Destination asset * @param amountToSwap Exact amount of `assetToSwapFrom` to be swapped * @param minAmountOut the min amount of `assetToSwapTo` to be received from the swap * @return the amount received from the swap */ function _swapExactTokensForTokens( address assetToSwapFrom, address assetToSwapTo, uint256 amountToSwap, uint256 minAmountOut, bool useEthPath ) internal returns (uint256) { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(assetToSwapFrom); uint256 toAssetPrice = _getPrice(assetToSwapTo); uint256 expectedMinAmountOut = amountToSwap .mul(fromAssetPrice.mul(10**toAssetDecimals)) .div(toAssetPrice.mul(10**fromAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(MAX_SLIPPAGE_PERCENT)); require(expectedMinAmountOut < minAmountOut, 'minAmountOut exceed max slippage'); // Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), amountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; } else { path = new address[](2); path[0] = assetToSwapFrom; path[1] = assetToSwapTo; } uint256[] memory amounts = UNISWAP_ROUTER.swapExactTokensForTokens( amountToSwap, minAmountOut, path, address(this), block.timestamp ); emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]); return amounts[amounts.length - 1]; } /** * @dev Receive an exact amount `amountToReceive` of `assetToSwapTo` tokens for as few `assetToSwapFrom` tokens as * possible. * @param assetToSwapFrom Origin asset * @param assetToSwapTo Destination asset * @param maxAmountToSwap Max amount of `assetToSwapFrom` allowed to be swapped * @param amountToReceive Exact amount of `assetToSwapTo` to receive * @return the amount swapped */ function _swapTokensForExactTokens( address assetToSwapFrom, address assetToSwapTo, uint256 maxAmountToSwap, uint256 amountToReceive, bool useEthPath ) internal returns (uint256) { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(assetToSwapFrom); uint256 toAssetPrice = _getPrice(assetToSwapTo); uint256 expectedMaxAmountToSwap = amountToReceive .mul(toAssetPrice.mul(10**fromAssetDecimals)) .div(fromAssetPrice.mul(10**toAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.add(MAX_SLIPPAGE_PERCENT)); require(maxAmountToSwap < expectedMaxAmountToSwap, 'maxAmountToSwap exceed max slippage'); // Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), maxAmountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; } else { path = new address[](2); path[0] = assetToSwapFrom; path[1] = assetToSwapTo; } uint256[] memory amounts = UNISWAP_ROUTER.swapTokensForExactTokens( amountToReceive, maxAmountToSwap, path, address(this), block.timestamp ); emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]); return amounts[0]; } /** * @dev Get the price of the asset from the oracle denominated in eth * @param asset address * @return eth price for the asset */ function _getPrice(address asset) internal view returns (uint256) { return ORACLE.getAssetPrice(asset); } /** * @dev Get the decimals of an asset * @return number of decimals of the asset */ function _getDecimals(address asset) internal view returns (uint256) { return IERC20Detailed(asset).decimals(); } /** * @dev Get the aToken associated to the asset * @return address of the aToken */ function _getReserveData(address asset) internal view returns (DataTypes.ReserveData memory) { return LENDING_POOL.getReserveData(asset); } /** * @dev Pull the ATokens from the user * @param reserve address of the asset * @param reserveAToken address of the aToken of the reserve * @param user address * @param amount of tokens to be transferred to the contract * @param permitSignature struct containing the permit signature */ function _pullAToken( address reserve, address reserveAToken, address user, uint256 amount, PermitSignature memory permitSignature ) internal { if (_usePermit(permitSignature)) { IERC20WithPermit(reserveAToken).permit( user, address(this), permitSignature.amount, permitSignature.deadline, permitSignature.v, permitSignature.r, permitSignature.s ); } // transfer from user to adapter IERC20(reserveAToken).safeTransferFrom(user, address(this), amount); // withdraw reserve LENDING_POOL.withdraw(reserve, amount, address(this)); } /** * @dev Tells if the permit method should be called by inspecting if there is a valid signature. * If signature params are set to 0, then permit won't be called. * @param signature struct containing the permit signature * @return whether or not permit should be called */ function _usePermit(PermitSignature memory signature) internal pure returns (bool) { return !(uint256(signature.deadline) == uint256(signature.v) && uint256(signature.deadline) == 0); } /** * @dev Calculates the value denominated in USD * @param reserve Address of the reserve * @param amount Amount of the reserve * @param decimals Decimals of the reserve * @return whether or not permit should be called */ function _calcUsdValue( address reserve, uint256 amount, uint256 decimals ) internal view returns (uint256) { uint256 ethUsdPrice = _getPrice(USD_ADDRESS); uint256 reservePrice = _getPrice(reserve); return amount.mul(reservePrice).div(10**decimals).mul(ethUsdPrice).div(10**18); } /** * @dev Given an input asset amount, returns the maximum output amount of the other asset * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountIn Amount of reserveIn * @return Struct containing the following information: * uint256 Amount out of the reserveOut * uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * uint256 In amount of reserveIn value denominated in USD (8 decimals) * uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function _getAmountsOutData( address reserveIn, address reserveOut, uint256 amountIn ) internal view returns (AmountCalc memory) { // Subtract flash loan fee uint256 finalAmountIn = amountIn.sub(amountIn.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); if (reserveIn == reserveOut) { uint256 reserveDecimals = _getDecimals(reserveIn); address[] memory path = new address[](1); path[0] = reserveIn; return AmountCalc( finalAmountIn, finalAmountIn.mul(10**18).div(amountIn), _calcUsdValue(reserveIn, amountIn, reserveDecimals), _calcUsdValue(reserveIn, finalAmountIn, reserveDecimals), path ); } address[] memory simplePath = new address[](2); simplePath[0] = reserveIn; simplePath[1] = reserveOut; uint256[] memory amountsWithoutWeth; uint256[] memory amountsWithWeth; address[] memory pathWithWeth = new address[](3); if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) { pathWithWeth[0] = reserveIn; pathWithWeth[1] = WETH_ADDRESS; pathWithWeth[2] = reserveOut; try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, pathWithWeth) returns ( uint256[] memory resultsWithWeth ) { amountsWithWeth = resultsWithWeth; } catch { amountsWithWeth = new uint256[](3); } } else { amountsWithWeth = new uint256[](3); } uint256 bestAmountOut; try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, simplePath) returns ( uint256[] memory resultAmounts ) { amountsWithoutWeth = resultAmounts; bestAmountOut = (amountsWithWeth[2] > amountsWithoutWeth[1]) ? amountsWithWeth[2] : amountsWithoutWeth[1]; } catch { amountsWithoutWeth = new uint256[](2); bestAmountOut = amountsWithWeth[2]; } uint256 reserveInDecimals = _getDecimals(reserveIn); uint256 reserveOutDecimals = _getDecimals(reserveOut); uint256 outPerInPrice = finalAmountIn.mul(10**18).mul(10**reserveOutDecimals).div( bestAmountOut.mul(10**reserveInDecimals) ); return AmountCalc( bestAmountOut, outPerInPrice, _calcUsdValue(reserveIn, amountIn, reserveInDecimals), _calcUsdValue(reserveOut, bestAmountOut, reserveOutDecimals), (bestAmountOut == 0) ? new address[](2) : (bestAmountOut == amountsWithoutWeth[1]) ? simplePath : pathWithWeth ); } /** * @dev Returns the minimum input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return Struct containing the following information: * uint256 Amount in of the reserveIn * uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * uint256 In amount of reserveIn value denominated in USD (8 decimals) * uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function _getAmountsInData( address reserveIn, address reserveOut, uint256 amountOut ) internal view returns (AmountCalc memory) { if (reserveIn == reserveOut) { // Add flash loan fee uint256 amountIn = amountOut.add(amountOut.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); uint256 reserveDecimals = _getDecimals(reserveIn); address[] memory path = new address[](1); path[0] = reserveIn; return AmountCalc( amountIn, amountOut.mul(10**18).div(amountIn), _calcUsdValue(reserveIn, amountIn, reserveDecimals), _calcUsdValue(reserveIn, amountOut, reserveDecimals), path ); } (uint256[] memory amounts, address[] memory path) = _getAmountsInAndPath(reserveIn, reserveOut, amountOut); // Add flash loan fee uint256 finalAmountIn = amounts[0].add(amounts[0].mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); uint256 reserveInDecimals = _getDecimals(reserveIn); uint256 reserveOutDecimals = _getDecimals(reserveOut); uint256 inPerOutPrice = amountOut.mul(10**18).mul(10**reserveInDecimals).div( finalAmountIn.mul(10**reserveOutDecimals) ); return AmountCalc( finalAmountIn, inPerOutPrice, _calcUsdValue(reserveIn, finalAmountIn, reserveInDecimals), _calcUsdValue(reserveOut, amountOut, reserveOutDecimals), path ); } /** * @dev Calculates the input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return uint256[] amounts Array containing the amountIn and amountOut for a swap */ function _getAmountsInAndPath( address reserveIn, address reserveOut, uint256 amountOut ) internal view returns (uint256[] memory, address[] memory) { address[] memory simplePath = new address[](2); simplePath[0] = reserveIn; simplePath[1] = reserveOut; uint256[] memory amountsWithoutWeth; uint256[] memory amountsWithWeth; address[] memory pathWithWeth = new address[](3); if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) { pathWithWeth[0] = reserveIn; pathWithWeth[1] = WETH_ADDRESS; pathWithWeth[2] = reserveOut; try UNISWAP_ROUTER.getAmountsIn(amountOut, pathWithWeth) returns ( uint256[] memory resultsWithWeth ) { amountsWithWeth = resultsWithWeth; } catch { amountsWithWeth = new uint256[](3); } } else { amountsWithWeth = new uint256[](3); } try UNISWAP_ROUTER.getAmountsIn(amountOut, simplePath) returns ( uint256[] memory resultAmounts ) { amountsWithoutWeth = resultAmounts; return (amountsWithWeth[0] < amountsWithoutWeth[0] && amountsWithWeth[0] != 0) ? (amountsWithWeth, pathWithWeth) : (amountsWithoutWeth, simplePath); } catch { return (amountsWithWeth, pathWithWeth); } } /** * @dev Calculates the input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return uint256[] amounts Array containing the amountIn and amountOut for a swap */ function _getAmountsIn( address reserveIn, address reserveOut, uint256 amountOut, bool useEthPath ) internal view returns (uint256[] memory) { address[] memory path; if (useEthPath) { path = new address[](3); path[0] = reserveIn; path[1] = WETH_ADDRESS; path[2] = reserveOut; } else { path = new address[](2); path[0] = reserveIn; path[1] = reserveOut; } return UNISWAP_ROUTER.getAmountsIn(amountOut, path); } /** * @dev Emergency rescue for token stucked on this contract, as failsafe mechanism * - Funds should never remain in this contract more time than during transactions * - Only callable by the owner **/ function rescueTokens(IERC20 token) external onlyOwner { token.transfer(owner(), token.balanceOf(address(this))); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title PercentageMath library * @author Aave * @notice Provides functions to perform percentage calculations * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR * @dev Operations are rounded half up **/ library PercentageMath { uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2; /** * @dev Executes a percentage multiplication * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The percentage of value **/ function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) { if (value == 0 || percentage == 0) { return 0; } require( value <= (type(uint256).max - HALF_PERCENT) / percentage, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; } /** * @dev Executes a percentage division * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The value divided the percentage **/ function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfPercentage = percentage / 2; require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; import {SafeMath} from './SafeMath.sol'; import {Address} from './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)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import './Context.sol'; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() 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; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IUniswapV2Router02 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IPriceOracleGetter interface * @notice Interface for the Aave price oracle. **/ interface IPriceOracleGetter { /** * @dev returns the asset price in ETH * @param asset the address of the asset * @return the ETH price of the asset **/ function getAssetPrice(address asset) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; interface IERC20WithPermit is IERC20 { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {IFlashLoanReceiver} from '../interfaces/IFlashLoanReceiver.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for IERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public immutable override ADDRESSES_PROVIDER; ILendingPool public immutable override LENDING_POOL; constructor(ILendingPoolAddressesProvider provider) public { ADDRESSES_PROVIDER = provider; LENDING_POOL = ILendingPool(provider.getLendingPool()); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {IUniswapV2Router02} from '../../interfaces/IUniswapV2Router02.sol'; interface IBaseUniswapAdapter { event Swapped(address fromAsset, address toAsset, uint256 fromAmount, uint256 receivedAmount); struct PermitSignature { uint256 amount; uint256 deadline; uint8 v; bytes32 r; bytes32 s; } struct AmountCalc { uint256 calculatedAmount; uint256 relativePrice; uint256 amountInUsd; uint256 amountOutUsd; address[] path; } function WETH_ADDRESS() external returns (address); function MAX_SLIPPAGE_PERCENT() external returns (uint256); function FLASHLOAN_PREMIUM_TOTAL() external returns (uint256); function USD_ADDRESS() external returns (address); function ORACLE() external returns (IPriceOracleGetter); function UNISWAP_ROUTER() external returns (IUniswapV2Router02); /** * @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices * @param amountIn Amount of reserveIn * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount out of the reserveOut * @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) * @return address[] The exchange path */ function getAmountsOut( uint256 amountIn, address reserveIn, address reserveOut ) external view returns ( uint256, uint256, uint256, uint256, address[] memory ); /** * @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices * @param amountOut Amount of reserveOut * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount in of the reserveIn * @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) * @return address[] The exchange path */ function getAmountsIn( uint256 amountOut, address reserveIn, address reserveOut ) external view returns ( uint256, uint256, uint256, uint256, address[] memory ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title Errors library * @author Aave * @notice Defines the error messages emitted by the different contracts of the Aave protocol * @dev Error messages prefix glossary: * - VL = ValidationLogic * - MATH = Math libraries * - CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken) * - AT = AToken * - SDT = StableDebtToken * - VDT = VariableDebtToken * - LP = LendingPool * - LPAPR = LendingPoolAddressesProviderRegistry * - LPC = LendingPoolConfiguration * - RL = ReserveLogic * - LPCM = LendingPoolCollateralManager * - P = Pausable */ library Errors { //common errors string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin' string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small //contract specific errors string public constant VL_INVALID_AMOUNT = '1'; // 'Amount must be greater than 0' string public constant VL_NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve' string public constant VL_RESERVE_FROZEN = '3'; // 'Action cannot be performed because the reserve is frozen' string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough' string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance' string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.' string public constant VL_BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled' string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0' string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold' string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow' string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt' string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed' string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve' string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve' string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0' string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral' string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve' string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met' string public constant LP_LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed' string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow' string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.' string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent' string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The caller of the function is not the lending pool configurator' string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28'; string public constant CT_CALLER_MUST_BE_LENDING_POOL = '29'; // 'The caller of this function must be a lending pool' string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself' string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero' string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // 'Reserve has already been initialized' string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = '35'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_CONFIGURATION = '75'; // 'Invalid risk parameters for the reserve' string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = '76'; // 'The caller must be the emergency admin' string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // 'Provider is not registered' string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // 'Health factor is not below the threshold' string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // 'The collateral chosen cannot be liquidated' string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // 'User did not borrow the specified currency' string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // "There isn't enough liquidity available to liquidate" string public constant LPCM_NO_ERRORS = '46'; // 'No errors' string public constant LP_INVALID_FLASHLOAN_MODE = '47'; //Invalid flashloan mode selected string public constant MATH_MULTIPLICATION_OVERFLOW = '48'; string public constant MATH_ADDITION_OVERFLOW = '49'; string public constant MATH_DIVISION_BY_ZERO = '50'; string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128 string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128 string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128 string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128 string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128 string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint string public constant LP_FAILED_REPAY_WITH_COLLATERAL = '57'; string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn string public constant LP_FAILED_COLLATERAL_SWAP = '60'; string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61'; string public constant LP_REENTRANCY_NOT_ALLOWED = '62'; string public constant LP_CALLER_MUST_BE_AN_ATOKEN = '63'; string public constant LP_IS_PAUSED = '64'; // 'Pool is paused' string public constant LP_NO_MORE_RESERVES_ALLOWED = '65'; string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66'; string public constant RC_INVALID_LTV = '67'; string public constant RC_INVALID_LIQ_THRESHOLD = '68'; string public constant RC_INVALID_LIQ_BONUS = '69'; string public constant RC_INVALID_DECIMALS = '70'; string public constant RC_INVALID_RESERVE_FACTOR = '71'; string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72'; string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73'; string public constant LP_INCONSISTENT_PARAMS_LENGTH = '74'; string public constant UL_INVALID_INDEX = '77'; string public constant LP_NOT_CONTRACT = '78'; string public constant SDT_STABLE_DEBT_OVERFLOW = '79'; string public constant SDT_BURN_EXCEEDS_BALANCE = '80'; enum CollateralManagerErrors { NO_ERROR, NO_COLLATERAL_AVAILABLE, COLLATERAL_CANNOT_BE_LIQUIDATED, CURRRENCY_NOT_BORROWED, HEALTH_FACTOR_ABOVE_THRESHOLD, NOT_ENOUGH_LIQUIDITY, NO_ACTIVE_RESERVE, HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD, INVALID_EQUAL_ASSETS_TO_SWAP, FROZEN_RESERVE } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; /** * @title IFlashLoanReceiver interface * @notice Interface for the Aave fee IFlashLoanReceiver. * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external returns (bool); function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider); function LENDING_POOL() external view returns (ILendingPool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; /** * @title UniswapRepayAdapter * @notice Uniswap V2 Adapter to perform a repay of a debt with collateral. * @author Aave **/ contract UniswapRepayAdapter is BaseUniswapAdapter { struct RepayParams { address collateralAsset; uint256 collateralAmount; uint256 rateMode; PermitSignature permitSignature; bool useEthPath; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Uses the received funds from the flash loan to repay a debt on the protocol on behalf of the user. Then pulls * the collateral from the user and swaps it to the debt asset to repay the flash loan. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset, swap it * and repay the flash loan. * Supports only one asset on the flash loan. * @param assets Address of debt asset * @param amounts Amount of the debt to be repaid * @param premiums Fee of the flash loan * @param initiator Address of the user * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset Address of the reserve to be swapped * uint256 collateralAmount Amount of reserve to be swapped * uint256 rateMode Rate modes of the debt to be repaid * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v V param for the permit signature * bytes32 r R param for the permit signature * bytes32 s S param for the permit signature */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); RepayParams memory decodedParams = _decodeParams(params); _swapAndRepay( decodedParams.collateralAsset, assets[0], amounts[0], decodedParams.collateralAmount, decodedParams.rateMode, initiator, premiums[0], decodedParams.permitSignature, decodedParams.useEthPath ); return true; } /** * @dev Swaps the user collateral for the debt asset and then repay the debt on the protocol on behalf of the user * without using flash loans. This method can be used when the temporary transfer of the collateral asset to this * contract does not affect the user position. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset * @param collateralAsset Address of asset to be swapped * @param debtAsset Address of debt asset * @param collateralAmount Amount of the collateral to be swapped * @param debtRepayAmount Amount of the debt to be repaid * @param debtRateMode Rate mode of the debt to be repaid * @param permitSignature struct containing the permit signature * @param useEthPath struct containing the permit signature */ function swapAndRepay( address collateralAsset, address debtAsset, uint256 collateralAmount, uint256 debtRepayAmount, uint256 debtRateMode, PermitSignature calldata permitSignature, bool useEthPath ) external { DataTypes.ReserveData memory collateralReserveData = _getReserveData(collateralAsset); DataTypes.ReserveData memory debtReserveData = _getReserveData(debtAsset); address debtToken = DataTypes.InterestRateMode(debtRateMode) == DataTypes.InterestRateMode.STABLE ? debtReserveData.stableDebtTokenAddress : debtReserveData.variableDebtTokenAddress; uint256 currentDebt = IERC20(debtToken).balanceOf(msg.sender); uint256 amountToRepay = debtRepayAmount <= currentDebt ? debtRepayAmount : currentDebt; if (collateralAsset != debtAsset) { uint256 maxCollateralToSwap = collateralAmount; if (amountToRepay < debtRepayAmount) { maxCollateralToSwap = maxCollateralToSwap.mul(amountToRepay).div(debtRepayAmount); } // Get exact collateral needed for the swap to avoid leftovers uint256[] memory amounts = _getAmountsIn(collateralAsset, debtAsset, amountToRepay, useEthPath); require(amounts[0] <= maxCollateralToSwap, 'slippage too high'); // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, msg.sender, amounts[0], permitSignature ); // Swap collateral for debt asset _swapTokensForExactTokens(collateralAsset, debtAsset, amounts[0], amountToRepay, useEthPath); } else { // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, msg.sender, amountToRepay, permitSignature ); } // Repay debt. Approves 0 first to comply with tokens that implement the anti frontrunning approval fix IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amountToRepay); LENDING_POOL.repay(debtAsset, amountToRepay, debtRateMode, msg.sender); } /** * @dev Perform the repay of the debt, pulls the initiator collateral and swaps to repay the flash loan * * @param collateralAsset Address of token to be swapped * @param debtAsset Address of debt token to be received from the swap * @param amount Amount of the debt to be repaid * @param collateralAmount Amount of the reserve to be swapped * @param rateMode Rate mode of the debt to be repaid * @param initiator Address of the user * @param premium Fee of the flash loan * @param permitSignature struct containing the permit signature */ function _swapAndRepay( address collateralAsset, address debtAsset, uint256 amount, uint256 collateralAmount, uint256 rateMode, address initiator, uint256 premium, PermitSignature memory permitSignature, bool useEthPath ) internal { DataTypes.ReserveData memory collateralReserveData = _getReserveData(collateralAsset); // Repay debt. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amount); uint256 repaidAmount = IERC20(debtAsset).balanceOf(address(this)); LENDING_POOL.repay(debtAsset, amount, rateMode, initiator); repaidAmount = repaidAmount.sub(IERC20(debtAsset).balanceOf(address(this))); if (collateralAsset != debtAsset) { uint256 maxCollateralToSwap = collateralAmount; if (repaidAmount < amount) { maxCollateralToSwap = maxCollateralToSwap.mul(repaidAmount).div(amount); } uint256 neededForFlashLoanDebt = repaidAmount.add(premium); uint256[] memory amounts = _getAmountsIn(collateralAsset, debtAsset, neededForFlashLoanDebt, useEthPath); require(amounts[0] <= maxCollateralToSwap, 'slippage too high'); // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, initiator, amounts[0], permitSignature ); // Swap collateral asset to the debt asset _swapTokensForExactTokens( collateralAsset, debtAsset, amounts[0], neededForFlashLoanDebt, useEthPath ); } else { // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, initiator, repaidAmount.add(premium), permitSignature ); } // Repay flashloan. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amount.add(premium)); } /** * @dev Decodes debt information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset Address of the reserve to be swapped * uint256 collateralAmount Amount of reserve to be swapped * uint256 rateMode Rate modes of the debt to be repaid * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v V param for the permit signature * bytes32 r R param for the permit signature * bytes32 s S param for the permit signature * bool useEthPath use WETH path route * @return RepayParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (RepayParams memory) { ( address collateralAsset, uint256 collateralAmount, uint256 rateMode, uint256 permitAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bool useEthPath ) = abi.decode( params, (address, uint256, uint256, uint256, uint256, uint8, bytes32, bytes32, bool) ); return RepayParams( collateralAsset, collateralAmount, rateMode, PermitSignature(permitAmount, deadline, v, r, s), useEthPath ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts//SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts//IERC20.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {ILendingPoolCollateralManager} from '../../interfaces/ILendingPoolCollateralManager.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {GenericLogic} from '../libraries/logic/GenericLogic.sol'; import {Helpers} from '../libraries/helpers/Helpers.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {LendingPoolStorage} from './LendingPoolStorage.sol'; /** * @title LendingPoolCollateralManager contract * @author Aave * @dev Implements actions involving management of collateral in the protocol, the main one being the liquidations * IMPORTANT This contract will run always via DELEGATECALL, through the LendingPool, so the chain of inheritance * is the same as the LendingPool, to have compatible storage layouts **/ contract LendingPoolCollateralManager is ILendingPoolCollateralManager, VersionedInitializable, LendingPoolStorage { using SafeERC20 for IERC20; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000; struct LiquidationCallLocalVars { uint256 userCollateralBalance; uint256 userStableDebt; uint256 userVariableDebt; uint256 maxLiquidatableDebt; uint256 actualDebtToLiquidate; uint256 liquidationRatio; uint256 maxAmountCollateralToLiquidate; uint256 userStableRate; uint256 maxCollateralToLiquidate; uint256 debtAmountNeeded; uint256 healthFactor; uint256 liquidatorPreviousATokenBalance; IAToken collateralAtoken; bool isCollateralEnabled; DataTypes.InterestRateMode borrowRateMode; uint256 errorCode; string errorMsg; } /** * @dev As thIS contract extends the VersionedInitializable contract to match the state * of the LendingPool contract, the getRevision() function is needed, but the value is not * important, as the initialize() function will never be called here */ function getRevision() internal pure override returns (uint256) { return 0; } /** * @dev Function to liquidate a position if its Health Factor drops below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external override returns (uint256, string memory) { DataTypes.ReserveData storage collateralReserve = _reserves[collateralAsset]; DataTypes.ReserveData storage debtReserve = _reserves[debtAsset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[user]; LiquidationCallLocalVars memory vars; (, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData( user, _reserves, userConfig, _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); (vars.userStableDebt, vars.userVariableDebt) = Helpers.getUserCurrentDebt(user, debtReserve); (vars.errorCode, vars.errorMsg) = ValidationLogic.validateLiquidationCall( collateralReserve, debtReserve, userConfig, vars.healthFactor, vars.userStableDebt, vars.userVariableDebt ); if (Errors.CollateralManagerErrors(vars.errorCode) != Errors.CollateralManagerErrors.NO_ERROR) { return (vars.errorCode, vars.errorMsg); } vars.collateralAtoken = IAToken(collateralReserve.aTokenAddress); vars.userCollateralBalance = vars.collateralAtoken.balanceOf(user); vars.maxLiquidatableDebt = vars.userStableDebt.add(vars.userVariableDebt).percentMul( LIQUIDATION_CLOSE_FACTOR_PERCENT ); vars.actualDebtToLiquidate = debtToCover > vars.maxLiquidatableDebt ? vars.maxLiquidatableDebt : debtToCover; ( vars.maxCollateralToLiquidate, vars.debtAmountNeeded ) = _calculateAvailableCollateralToLiquidate( collateralReserve, debtReserve, collateralAsset, debtAsset, vars.actualDebtToLiquidate, vars.userCollateralBalance ); // If debtAmountNeeded < actualDebtToLiquidate, there isn't enough // collateral to cover the actual amount that is being liquidated, hence we liquidate // a smaller amount if (vars.debtAmountNeeded < vars.actualDebtToLiquidate) { vars.actualDebtToLiquidate = vars.debtAmountNeeded; } // If the liquidator reclaims the underlying asset, we make sure there is enough available liquidity in the // collateral reserve if (!receiveAToken) { uint256 currentAvailableCollateral = IERC20(collateralAsset).balanceOf(address(vars.collateralAtoken)); if (currentAvailableCollateral < vars.maxCollateralToLiquidate) { return ( uint256(Errors.CollateralManagerErrors.NOT_ENOUGH_LIQUIDITY), Errors.LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE ); } } debtReserve.updateState(); if (vars.userVariableDebt >= vars.actualDebtToLiquidate) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, vars.actualDebtToLiquidate, debtReserve.variableBorrowIndex ); } else { // If the user doesn't have variable debt, no need to try to burn variable debt tokens if (vars.userVariableDebt > 0) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, vars.userVariableDebt, debtReserve.variableBorrowIndex ); } IStableDebtToken(debtReserve.stableDebtTokenAddress).burn( user, vars.actualDebtToLiquidate.sub(vars.userVariableDebt) ); } debtReserve.updateInterestRates( debtAsset, debtReserve.aTokenAddress, vars.actualDebtToLiquidate, 0 ); if (receiveAToken) { vars.liquidatorPreviousATokenBalance = IERC20(vars.collateralAtoken).balanceOf(msg.sender); vars.collateralAtoken.transferOnLiquidation(user, msg.sender, vars.maxCollateralToLiquidate); if (vars.liquidatorPreviousATokenBalance == 0) { DataTypes.UserConfigurationMap storage liquidatorConfig = _usersConfig[msg.sender]; liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true); emit ReserveUsedAsCollateralEnabled(collateralAsset, msg.sender); } } else { collateralReserve.updateState(); collateralReserve.updateInterestRates( collateralAsset, address(vars.collateralAtoken), 0, vars.maxCollateralToLiquidate ); // Burn the equivalent amount of aToken, sending the underlying to the liquidator vars.collateralAtoken.burn( user, msg.sender, vars.maxCollateralToLiquidate, collateralReserve.liquidityIndex ); } // If the collateral being liquidated is equal to the user balance, // we set the currency as not being used as collateral anymore if (vars.maxCollateralToLiquidate == vars.userCollateralBalance) { userConfig.setUsingAsCollateral(collateralReserve.id, false); emit ReserveUsedAsCollateralDisabled(collateralAsset, user); } // Transfers the debt asset being repaid to the aToken, where the liquidity is kept IERC20(debtAsset).safeTransferFrom( msg.sender, debtReserve.aTokenAddress, vars.actualDebtToLiquidate ); emit LiquidationCall( collateralAsset, debtAsset, user, vars.actualDebtToLiquidate, vars.maxCollateralToLiquidate, msg.sender, receiveAToken ); return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); } struct AvailableCollateralToLiquidateLocalVars { uint256 userCompoundedBorrowBalance; uint256 liquidationBonus; uint256 collateralPrice; uint256 debtAssetPrice; uint256 maxAmountCollateralToLiquidate; uint256 debtAssetDecimals; uint256 collateralDecimals; } /** * @dev Calculates how much of a specific collateral can be liquidated, given * a certain amount of debt asset. * - This function needs to be called after all the checks to validate the liquidation have been performed, * otherwise it might fail. * @param collateralReserve The data of the collateral reserve * @param debtReserve The data of the debt reserve * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param userCollateralBalance The collateral balance for the specific `collateralAsset` of the user being liquidated * @return collateralAmount: The maximum amount that is possible to liquidate given all the liquidation constraints * (user balance, close factor) * debtAmountNeeded: The amount to repay with the liquidation **/ function _calculateAvailableCollateralToLiquidate( DataTypes.ReserveData storage collateralReserve, DataTypes.ReserveData storage debtReserve, address collateralAsset, address debtAsset, uint256 debtToCover, uint256 userCollateralBalance ) internal view returns (uint256, uint256) { uint256 collateralAmount = 0; uint256 debtAmountNeeded = 0; IPriceOracleGetter oracle = IPriceOracleGetter(_addressesProvider.getPriceOracle()); AvailableCollateralToLiquidateLocalVars memory vars; vars.collateralPrice = oracle.getAssetPrice(collateralAsset); vars.debtAssetPrice = oracle.getAssetPrice(debtAsset); (, , vars.liquidationBonus, vars.collateralDecimals, ) = collateralReserve .configuration .getParams(); vars.debtAssetDecimals = debtReserve.configuration.getDecimals(); // This is the maximum possible amount of the selected collateral that can be liquidated, given the // max amount of liquidatable debt vars.maxAmountCollateralToLiquidate = vars .debtAssetPrice .mul(debtToCover) .mul(10**vars.collateralDecimals) .percentMul(vars.liquidationBonus) .div(vars.collateralPrice.mul(10**vars.debtAssetDecimals)); if (vars.maxAmountCollateralToLiquidate > userCollateralBalance) { collateralAmount = userCollateralBalance; debtAmountNeeded = vars .collateralPrice .mul(collateralAmount) .mul(10**vars.debtAssetDecimals) .div(vars.debtAssetPrice.mul(10**vars.collateralDecimals)) .percentDiv(vars.liquidationBonus); } else { collateralAmount = vars.maxAmountCollateralToLiquidate; debtAmountNeeded = debtToCover; } return (collateralAmount, debtAmountNeeded); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableAToken} from './IInitializableAToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; interface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param value The amount being * @param index The new liquidity index of the reserve **/ event Mint(address indexed from, uint256 value, uint256 index); /** * @dev Mints `amount` aTokens to `user` * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted after aTokens are burned * @param from The owner of the aTokens, getting them burned * @param target The address that will receive the underlying * @param value The amount being burned * @param index The new liquidity index of the reserve **/ event Burn(address indexed from, address indexed target, uint256 value, uint256 index); /** * @dev Emitted during the transfer action * @param from The user whose tokens are being transferred * @param to The recipient * @param value The amount being transferred * @param index The new liquidity index of the reserve **/ event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index); /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external; /** * @dev Mints aTokens to the reserve treasury * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external; /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external; /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param user The recipient of the underlying * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address user, uint256 amount) external returns (uint256); /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IStableDebtToken * @notice Defines the interface for the stable debt token * @dev It does not inherit from IERC20 to save in code size * @author Aave **/ interface IStableDebtToken is IInitializableDebtToken { /** * @dev Emitted when new stable debt is minted * @param user The address of the user who triggered the minting * @param onBehalfOf The recipient of stable debt tokens * @param amount The amount minted * @param currentBalance The current balance of the user * @param balanceIncrease The increase in balance since the last action of the user * @param newRate The rate of the debt after the minting * @param avgStableRate The new average stable rate after the minting * @param newTotalSupply The new total supply of the stable debt token after the action **/ event Mint( address indexed user, address indexed onBehalfOf, uint256 amount, uint256 currentBalance, uint256 balanceIncrease, uint256 newRate, uint256 avgStableRate, uint256 newTotalSupply ); /** * @dev Emitted when new stable debt is burned * @param user The address of the user * @param amount The amount being burned * @param currentBalance The current balance of the user * @param balanceIncrease The the increase in balance since the last action of the user * @param avgStableRate The new average stable rate after the burning * @param newTotalSupply The new total supply of the stable debt token after the action **/ event Burn( address indexed user, uint256 amount, uint256 currentBalance, uint256 balanceIncrease, uint256 avgStableRate, uint256 newTotalSupply ); /** * @dev Mints debt token to the `onBehalfOf` address. * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt tokens to mint * @param rate The rate of the debt being minted **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 rate ) external returns (bool); /** * @dev Burns debt of `user` * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address of the user getting his debt burned * @param amount The amount of debt tokens getting burned **/ function burn(address user, uint256 amount) external; /** * @dev Returns the average rate of all the stable rate loans. * @return The average stable rate **/ function getAverageStableRate() external view returns (uint256); /** * @dev Returns the stable rate of the user debt * @return The stable rate of the user **/ function getUserStableRate(address user) external view returns (uint256); /** * @dev Returns the timestamp of the last update of the user * @return The timestamp **/ function getUserLastUpdated(address user) external view returns (uint40); /** * @dev Returns the principal, the total supply and the average stable rate **/ function getSupplyData() external view returns ( uint256, uint256, uint256, uint40 ); /** * @dev Returns the timestamp of the last update of the total supply * @return The timestamp **/ function getTotalSupplyLastUpdated() external view returns (uint40); /** * @dev Returns the total supply and the average stable rate **/ function getTotalSupplyAndAvgRate() external view returns (uint256, uint256); /** * @dev Returns the principal debt balance of the user * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external view returns (uint256); /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IVariableDebtToken * @author Aave * @notice Defines the basic interface for a variable debt token. **/ interface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param onBehalfOf The address of the user on which behalf minting has been performed * @param value The amount to be minted * @param index The last index of the reserve **/ event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index); /** * @dev Mints debt token to the `onBehalfOf` address * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted when variable debt is burnt * @param user The user which debt has been burned * @param amount The amount of debt being burned * @param index The index of the user **/ event Burn(address indexed user, uint256 amount, uint256 index); /** * @dev Burns user variable debt * @param user The user which debt is burnt * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title ILendingPoolCollateralManager * @author Aave * @notice Defines the actions involving management of collateral in the protocol. **/ interface ILendingPoolCollateralManager { /** * @dev Emitted when a borrower is liquidated * @param collateral The address of the collateral being liquidated * @param principal The address of the reserve * @param user The address of the user being liquidated * @param debtToCover The total amount liquidated * @param liquidatedCollateralAmount The amount of collateral being liquidated * @param liquidator The address of the liquidator * @param receiveAToken true if the liquidator wants to receive aTokens, false otherwise **/ event LiquidationCall( address indexed collateral, address indexed principal, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when a reserve is disabled as collateral for an user * @param reserve The address of the reserve * @param user The address of the user **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted when a reserve is enabled as collateral for an user * @param reserve The address of the reserve * @param user The address of the user **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Users can invoke this function to liquidate an undercollateralized position. * @param collateral The address of the collateral to liquidated * @param principal The address of the principal reserve * @param user The address of the borrower * @param debtToCover The amount of principal that the liquidator wants to repay * @param receiveAToken true if the liquidators wants to receive the aTokens, false if * he wants to receive the underlying asset directly **/ function liquidationCall( address collateral, address principal, address user, uint256 debtToCover, bool receiveAToken ) external returns (uint256, string memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title VersionedInitializable * * @dev Helper contract to implement 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. * * @author Aave, inspired by the OpenZeppelin Initializable contract */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 private lastInitializedRevision = 0; /** * @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() { uint256 revision = getRevision(); require( initializing || isConstructor() || revision > lastInitializedRevision, 'Contract instance has already been initialized' ); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; lastInitializedRevision = revision; } _; if (isTopLevelCall) { initializing = false; } } /** * @dev returns the revision number of the contract * Needs to be defined in the inherited class as a constant. **/ function getRevision() internal pure virtual returns (uint256); /** * @dev Returns true if and only if the function is running in the constructor **/ function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; //solium-disable-next-line assembly { cs := extcodesize(address()) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title GenericLogic library * @author Aave * @title Implements protocol-level logic to calculate and validate the state of a user */ library GenericLogic { using ReserveLogic for DataTypes.ReserveData; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1 ether; struct balanceDecreaseAllowedLocalVars { uint256 decimals; uint256 liquidationThreshold; uint256 totalCollateralInETH; uint256 totalDebtInETH; uint256 avgLiquidationThreshold; uint256 amountToDecreaseInETH; uint256 collateralBalanceAfterDecrease; uint256 liquidationThresholdAfterDecrease; uint256 healthFactorAfterDecrease; bool reserveUsageAsCollateralEnabled; } /** * @dev Checks if a specific balance decrease is allowed * (i.e. doesn't bring the user borrow position health factor under HEALTH_FACTOR_LIQUIDATION_THRESHOLD) * @param asset The address of the underlying asset of the reserve * @param user The address of the user * @param amount The amount to decrease * @param reservesData The data of all the reserves * @param userConfig The user configuration * @param reserves The list of all the active reserves * @param oracle The address of the oracle contract * @return true if the decrease of the balance is allowed **/ function balanceDecreaseAllowed( address asset, address user, uint256 amount, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap calldata userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view returns (bool) { if (!userConfig.isBorrowingAny() || !userConfig.isUsingAsCollateral(reservesData[asset].id)) { return true; } balanceDecreaseAllowedLocalVars memory vars; (, vars.liquidationThreshold, , vars.decimals, ) = reservesData[asset] .configuration .getParams(); if (vars.liquidationThreshold == 0) { return true; } ( vars.totalCollateralInETH, vars.totalDebtInETH, , vars.avgLiquidationThreshold, ) = calculateUserAccountData(user, reservesData, userConfig, reserves, reservesCount, oracle); if (vars.totalDebtInETH == 0) { return true; } vars.amountToDecreaseInETH = IPriceOracleGetter(oracle).getAssetPrice(asset).mul(amount).div( 10**vars.decimals ); vars.collateralBalanceAfterDecrease = vars.totalCollateralInETH.sub(vars.amountToDecreaseInETH); //if there is a borrow, there can't be 0 collateral if (vars.collateralBalanceAfterDecrease == 0) { return false; } vars.liquidationThresholdAfterDecrease = vars .totalCollateralInETH .mul(vars.avgLiquidationThreshold) .sub(vars.amountToDecreaseInETH.mul(vars.liquidationThreshold)) .div(vars.collateralBalanceAfterDecrease); uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalances( vars.collateralBalanceAfterDecrease, vars.totalDebtInETH, vars.liquidationThresholdAfterDecrease ); return healthFactorAfterDecrease >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD; } struct CalculateUserAccountDataVars { uint256 reserveUnitPrice; uint256 tokenUnit; uint256 compoundedLiquidityBalance; uint256 compoundedBorrowBalance; uint256 decimals; uint256 ltv; uint256 liquidationThreshold; uint256 i; uint256 healthFactor; uint256 totalCollateralInETH; uint256 totalDebtInETH; uint256 avgLtv; uint256 avgLiquidationThreshold; uint256 reservesLength; bool healthFactorBelowThreshold; address currentReserveAddress; bool usageAsCollateralEnabled; bool userUsesReserveAsCollateral; } /** * @dev Calculates the user data across the reserves. * this includes the total liquidity/collateral/borrow balances in ETH, * the average Loan To Value, the average Liquidation Ratio, and the Health factor. * @param user The address of the user * @param reservesData Data of all the reserves * @param userConfig The configuration of the user * @param reserves The list of the available reserves * @param oracle The price oracle address * @return The total collateral and total debt of the user in ETH, the avg ltv, liquidation threshold and the HF **/ function calculateUserAccountData( address user, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap memory userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) internal view returns ( uint256, uint256, uint256, uint256, uint256 ) { CalculateUserAccountDataVars memory vars; if (userConfig.isEmpty()) { return (0, 0, 0, 0, uint256(-1)); } for (vars.i = 0; vars.i < reservesCount; vars.i++) { if (!userConfig.isUsingAsCollateralOrBorrowing(vars.i)) { continue; } vars.currentReserveAddress = reserves[vars.i]; DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress]; (vars.ltv, vars.liquidationThreshold, , vars.decimals, ) = currentReserve .configuration .getParams(); vars.tokenUnit = 10**vars.decimals; vars.reserveUnitPrice = IPriceOracleGetter(oracle).getAssetPrice(vars.currentReserveAddress); if (vars.liquidationThreshold != 0 && userConfig.isUsingAsCollateral(vars.i)) { vars.compoundedLiquidityBalance = IERC20(currentReserve.aTokenAddress).balanceOf(user); uint256 liquidityBalanceETH = vars.reserveUnitPrice.mul(vars.compoundedLiquidityBalance).div(vars.tokenUnit); vars.totalCollateralInETH = vars.totalCollateralInETH.add(liquidityBalanceETH); vars.avgLtv = vars.avgLtv.add(liquidityBalanceETH.mul(vars.ltv)); vars.avgLiquidationThreshold = vars.avgLiquidationThreshold.add( liquidityBalanceETH.mul(vars.liquidationThreshold) ); } if (userConfig.isBorrowing(vars.i)) { vars.compoundedBorrowBalance = IERC20(currentReserve.stableDebtTokenAddress).balanceOf( user ); vars.compoundedBorrowBalance = vars.compoundedBorrowBalance.add( IERC20(currentReserve.variableDebtTokenAddress).balanceOf(user) ); vars.totalDebtInETH = vars.totalDebtInETH.add( vars.reserveUnitPrice.mul(vars.compoundedBorrowBalance).div(vars.tokenUnit) ); } } vars.avgLtv = vars.totalCollateralInETH > 0 ? vars.avgLtv.div(vars.totalCollateralInETH) : 0; vars.avgLiquidationThreshold = vars.totalCollateralInETH > 0 ? vars.avgLiquidationThreshold.div(vars.totalCollateralInETH) : 0; vars.healthFactor = calculateHealthFactorFromBalances( vars.totalCollateralInETH, vars.totalDebtInETH, vars.avgLiquidationThreshold ); return ( vars.totalCollateralInETH, vars.totalDebtInETH, vars.avgLtv, vars.avgLiquidationThreshold, vars.healthFactor ); } /** * @dev Calculates the health factor from the corresponding balances * @param totalCollateralInETH The total collateral in ETH * @param totalDebtInETH The total debt in ETH * @param liquidationThreshold The avg liquidation threshold * @return The health factor calculated from the balances provided **/ function calculateHealthFactorFromBalances( uint256 totalCollateralInETH, uint256 totalDebtInETH, uint256 liquidationThreshold ) internal pure returns (uint256) { if (totalDebtInETH == 0) return uint256(-1); return (totalCollateralInETH.percentMul(liquidationThreshold)).wadDiv(totalDebtInETH); } /** * @dev Calculates the equivalent amount in ETH that an user can borrow, depending on the available collateral and the * average Loan To Value * @param totalCollateralInETH The total collateral in ETH * @param totalDebtInETH The total borrow balance * @param ltv The average loan to value * @return the amount available to borrow in ETH for the user **/ function calculateAvailableBorrowsETH( uint256 totalCollateralInETH, uint256 totalDebtInETH, uint256 ltv ) internal pure returns (uint256) { uint256 availableBorrowsETH = totalCollateralInETH.percentMul(ltv); if (availableBorrowsETH < totalDebtInETH) { return 0; } availableBorrowsETH = availableBorrowsETH.sub(totalDebtInETH); return availableBorrowsETH; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title Helpers library * @author Aave */ library Helpers { /** * @dev Fetches the user current stable and variable debt balances * @param user The user address * @param reserve The reserve data object * @return The stable and variable debt balance **/ function getUserCurrentDebt(address user, DataTypes.ReserveData storage reserve) internal view returns (uint256, uint256) { return ( IERC20(reserve.stableDebtTokenAddress).balanceOf(user), IERC20(reserve.variableDebtTokenAddress).balanceOf(user) ); } function getUserCurrentDebtMemory(address user, DataTypes.ReserveData memory reserve) internal view returns (uint256, uint256) { return ( IERC20(reserve.stableDebtTokenAddress).balanceOf(user), IERC20(reserve.variableDebtTokenAddress).balanceOf(user) ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return halfRAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return halfWAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfWAD) / WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfRAY) / RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {Helpers} from '../helpers/Helpers.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 4000; uint256 public constant REBALANCE_UP_USAGE_RATIO_THRESHOLD = 0.95 * 1e27; //usage ratio of 95% /** * @dev Validates a deposit action * @param reserve The reserve object on which the user is depositing * @param amount The amount to be deposited */ function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view { (bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags(); require(amount != 0, Errors.VL_INVALID_AMOUNT); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!isFrozen, Errors.VL_RESERVE_FROZEN); } /** * @dev Validates a withdraw action * @param reserveAddress The address of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user * @param reservesData The reserves state * @param userConfig The user configuration * @param reserves The addresses of the reserves * @param reservesCount The number of reserves * @param oracle The price oracle */ function validateWithdraw( address reserveAddress, uint256 amount, uint256 userBalance, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { require(amount != 0, Errors.VL_INVALID_AMOUNT); require(amount <= userBalance, Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE); (bool isActive, , , ) = reservesData[reserveAddress].configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require( GenericLogic.balanceDecreaseAllowed( reserveAddress, msg.sender, amount, reservesData, userConfig, reserves, reservesCount, oracle ), Errors.VL_TRANSFER_NOT_ALLOWED ); } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 currentLiquidationThreshold; uint256 amountOfCollateralNeededETH; uint256 userCollateralBalanceETH; uint256 userBorrowBalanceETH; uint256 availableLiquidity; uint256 healthFactor; bool isActive; bool isFrozen; bool borrowingEnabled; bool stableRateBorrowingEnabled; } /** * @dev Validates a borrow action * @param asset The address of the asset to borrow * @param reserve The reserve state from which the user is borrowing * @param userAddress The address of the user * @param amount The amount to be borrowed * @param amountInETH The amount to be borrowed, in ETH * @param interestRateMode The interest rate mode at which the user is borrowing * @param maxStableLoanPercent The max amount of the liquidity that can be borrowed at stable rate, in percentage * @param reservesData The state of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateBorrow( address asset, DataTypes.ReserveData storage reserve, address userAddress, uint256 amount, uint256 amountInETH, uint256 interestRateMode, uint256 maxStableLoanPercent, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { ValidateBorrowLocalVars memory vars; (vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled) = reserve .configuration .getFlags(); require(vars.isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!vars.isFrozen, Errors.VL_RESERVE_FROZEN); require(amount != 0, Errors.VL_INVALID_AMOUNT); require(vars.borrowingEnabled, Errors.VL_BORROWING_NOT_ENABLED); //validate interest rate mode require( uint256(DataTypes.InterestRateMode.VARIABLE) == interestRateMode || uint256(DataTypes.InterestRateMode.STABLE) == interestRateMode, Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED ); ( vars.userCollateralBalanceETH, vars.userBorrowBalanceETH, vars.currentLtv, vars.currentLiquidationThreshold, vars.healthFactor ) = GenericLogic.calculateUserAccountData( userAddress, reservesData, userConfig, reserves, reservesCount, oracle ); require(vars.userCollateralBalanceETH > 0, Errors.VL_COLLATERAL_BALANCE_IS_0); require( vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.amountOfCollateralNeededETH = vars.userBorrowBalanceETH.add(amountInETH).percentDiv( vars.currentLtv ); //LTV is calculated in percentage require( vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH, Errors.VL_COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a portion of the total available liquidity **/ if (interestRateMode == uint256(DataTypes.InterestRateMode.STABLE)) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require(vars.stableRateBorrowingEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.id) || reserve.configuration.getLtv() == 0 || amount > IERC20(reserve.aTokenAddress).balanceOf(userAddress), Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY ); vars.availableLiquidity = IERC20(asset).balanceOf(reserve.aTokenAddress); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(maxStableLoanPercent); require(amount <= maxLoanSizeStable, Errors.VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } } /** * @dev Validates a repay action * @param reserve The reserve state from which the user is repaying * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveData storage reserve, uint256 amountSent, DataTypes.InterestRateMode rateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) external view { bool isActive = reserve.configuration.getActive(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(amountSent > 0, Errors.VL_INVALID_AMOUNT); require( (stableDebt > 0 && DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE) || (variableDebt > 0 && DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.VARIABLE), Errors.VL_NO_DEBT_OF_SELECTED_TYPE ); require( amountSent != uint256(-1) || msg.sender == onBehalfOf, Errors.VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF ); } /** * @dev Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the borrow */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) external view { (bool isActive, bool isFrozen, , bool stableRateEnabled) = reserve.configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!isFrozen, Errors.VL_RESERVE_FROZEN); if (currentRateMode == DataTypes.InterestRateMode.STABLE) { require(stableDebt > 0, Errors.VL_NO_STABLE_RATE_LOAN_IN_RESERVE); } else if (currentRateMode == DataTypes.InterestRateMode.VARIABLE) { require(variableDebt > 0, Errors.VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE); /** * user wants to swap to stable, before swapping we need to ensure that * 1. stable borrow rate is enabled on the reserve * 2. user is not trying to abuse the reserve by depositing * more collateral than he is borrowing, artificially lowering * the interest rate, borrowing at variable, and switching to stable **/ require(stableRateEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.id) || reserve.configuration.getLtv() == 0 || stableDebt.add(variableDebt) > IERC20(reserve.aTokenAddress).balanceOf(msg.sender), Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY ); } else { revert(Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED); } } /** * @dev Validates a stable borrow rate rebalance action * @param reserve The reserve state on which the user is getting rebalanced * @param reserveAddress The address of the reserve * @param stableDebtToken The stable debt token instance * @param variableDebtToken The variable debt token instance * @param aTokenAddress The address of the aToken contract */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, address reserveAddress, IERC20 stableDebtToken, IERC20 variableDebtToken, address aTokenAddress ) external view { (bool isActive, , , ) = reserve.configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); //if the usage ratio is below 95%, no rebalances are needed uint256 totalDebt = stableDebtToken.totalSupply().add(variableDebtToken.totalSupply()).wadToRay(); uint256 availableLiquidity = IERC20(reserveAddress).balanceOf(aTokenAddress).wadToRay(); uint256 usageRatio = totalDebt == 0 ? 0 : totalDebt.rayDiv(availableLiquidity.add(totalDebt)); //if the liquidity rate is below REBALANCE_UP_THRESHOLD of the max variable APR at 95% usage, //then we allow rebalancing of the stable rate positions. uint256 currentLiquidityRate = reserve.currentLiquidityRate; uint256 maxVariableBorrowRate = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).getMaxVariableBorrowRate(); require( usageRatio >= REBALANCE_UP_USAGE_RATIO_THRESHOLD && currentLiquidityRate <= maxVariableBorrowRate.percentMul(REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD), Errors.LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET ); } /** * @dev Validates the action of setting an asset as collateral * @param reserve The state of the reserve that the user is enabling or disabling as collateral * @param reserveAddress The address of the reserve * @param reservesData The data of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateSetUseReserveAsCollateral( DataTypes.ReserveData storage reserve, address reserveAddress, bool useAsCollateral, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { uint256 underlyingBalance = IERC20(reserve.aTokenAddress).balanceOf(msg.sender); require(underlyingBalance > 0, Errors.VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0); require( useAsCollateral || GenericLogic.balanceDecreaseAllowed( reserveAddress, msg.sender, underlyingBalance, reservesData, userConfig, reserves, reservesCount, oracle ), Errors.VL_DEPOSIT_ALREADY_IN_USE ); } /** * @dev Validates a flashloan action * @param assets The assets being flashborrowed * @param amounts The amounts for each asset being borrowed **/ function validateFlashloan(address[] memory assets, uint256[] memory amounts) internal pure { require(assets.length == amounts.length, Errors.VL_INCONSISTENT_FLASHLOAN_PARAMS); } /** * @dev Validates the liquidation action * @param collateralReserve The reserve data of the collateral * @param principalReserve The reserve data of the principal * @param userConfig The user configuration * @param userHealthFactor The user's health factor * @param userStableDebt Total stable debt balance of the user * @param userVariableDebt Total variable debt balance of the user **/ function validateLiquidationCall( DataTypes.ReserveData storage collateralReserve, DataTypes.ReserveData storage principalReserve, DataTypes.UserConfigurationMap storage userConfig, uint256 userHealthFactor, uint256 userStableDebt, uint256 userVariableDebt ) internal view returns (uint256, string memory) { if ( !collateralReserve.configuration.getActive() || !principalReserve.configuration.getActive() ) { return ( uint256(Errors.CollateralManagerErrors.NO_ACTIVE_RESERVE), Errors.VL_NO_ACTIVE_RESERVE ); } if (userHealthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD) { return ( uint256(Errors.CollateralManagerErrors.HEALTH_FACTOR_ABOVE_THRESHOLD), Errors.LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD ); } bool isCollateralEnabled = collateralReserve.configuration.getLiquidationThreshold() > 0 && userConfig.isUsingAsCollateral(collateralReserve.id); //if collateral isn't enabled as collateral by user, it cannot be liquidated if (!isCollateralEnabled) { return ( uint256(Errors.CollateralManagerErrors.COLLATERAL_CANNOT_BE_LIQUIDATED), Errors.LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED ); } if (userStableDebt == 0 && userVariableDebt == 0) { return ( uint256(Errors.CollateralManagerErrors.CURRRENCY_NOT_BORROWED), Errors.LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER ); } return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); } /** * @dev Validates an aToken transfer * @param from The user from which the aTokens are being transferred * @param reservesData The state of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateTransfer( address from, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) internal view { (, , , , uint256 healthFactor) = GenericLogic.calculateUserAccountData( from, reservesData, userConfig, reserves, reservesCount, oracle ); require( healthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.VL_TRANSFER_NOT_ALLOWED ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; contract LendingPoolStorage { using ReserveLogic for DataTypes.ReserveData; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; ILendingPoolAddressesProvider internal _addressesProvider; mapping(address => DataTypes.ReserveData) internal _reserves; mapping(address => DataTypes.UserConfigurationMap) internal _usersConfig; // the list of the available reserves, structured as a mapping for gas savings reasons mapping(uint256 => address) internal _reservesList; uint256 internal _reservesCount; bool internal _paused; uint256 internal _maxStableRateBorrowSizePercent; uint256 internal _flashLoanPremiumTotal; uint256 internal _maxNumberOfReserves; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from './ILendingPool.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IInitializableAToken * @notice Interface for the initialize function on AToken * @author Aave **/ interface IInitializableAToken { /** * @dev Emitted when an aToken is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param treasury The address of the treasury * @param incentivesController The address of the incentives controller for this aToken * @param aTokenDecimals the decimals of the underlying * @param aTokenName the name of the aToken * @param aTokenSymbol the symbol of the aToken * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address treasury, address incentivesController, uint8 aTokenDecimals, string aTokenName, string aTokenSymbol, bytes params ); /** * @dev Initializes the aToken * @param pool The address of the lending pool where this aToken will be used * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IAaveIncentivesController { function handleAction( address user, uint256 userBalance, uint256 totalSupply ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from './ILendingPool.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IInitializableDebtToken * @notice Interface for the initialize function common between debt tokens * @author Aave **/ interface IInitializableDebtToken { /** * @dev Emitted when a debt token is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param incentivesController The address of the incentives controller for this aToken * @param debtTokenDecimals the decimals of the debt token * @param debtTokenName the name of the debt token * @param debtTokenSymbol the symbol of the debt token * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address incentivesController, uint8 debtTokenDecimals, string debtTokenName, string debtTokenSymbol, bytes params ); /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {MathUtils} from '../math/MathUtils.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements the logic to update the reserves state */ library ReserveLogic { using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; /** * @dev Emitted when the state of a reserve is updated * @param asset The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed asset, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); using ReserveLogic for DataTypes.ReserveData; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; /** * @dev Returns the ongoing normalized income for the reserve * A value of 1e27 means there is no income. As time passes, the income is accrued * A value of 2*1e27 means for each unit of asset one unit of income has been accrued * @param reserve The reserve object * @return the normalized income. expressed in ray **/ function getNormalizedIncome(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; //solium-disable-next-line if (timestamp == uint40(block.timestamp)) { //if the index was updated in the same block, no need to perform any calculation return reserve.liquidityIndex; } uint256 cumulated = MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul( reserve.liquidityIndex ); return cumulated; } /** * @dev Returns the ongoing normalized variable debt for the reserve * A value of 1e27 means there is no debt. As time passes, the income is accrued * A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated * @param reserve The reserve object * @return The normalized variable debt. expressed in ray **/ function getNormalizedDebt(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; //solium-disable-next-line if (timestamp == uint40(block.timestamp)) { //if the index was updated in the same block, no need to perform any calculation return reserve.variableBorrowIndex; } uint256 cumulated = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul( reserve.variableBorrowIndex ); return cumulated; } /** * @dev Updates the liquidity cumulative index and the variable borrow index. * @param reserve the reserve object **/ function updateState(DataTypes.ReserveData storage reserve) internal { uint256 scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply(); uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex; uint256 previousLiquidityIndex = reserve.liquidityIndex; uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp; (uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) = _updateIndexes( reserve, scaledVariableDebt, previousLiquidityIndex, previousVariableBorrowIndex, lastUpdatedTimestamp ); _mintToTreasury( reserve, scaledVariableDebt, previousVariableBorrowIndex, newLiquidityIndex, newVariableBorrowIndex, lastUpdatedTimestamp ); } /** * @dev Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example to accumulate * the flashloan fee to the reserve, and spread it between all the depositors * @param reserve The reserve object * @param totalLiquidity The total liquidity available in the reserve * @param amount The amount to accomulate **/ function cumulateToLiquidityIndex( DataTypes.ReserveData storage reserve, uint256 totalLiquidity, uint256 amount ) internal { uint256 amountToLiquidityRatio = amount.wadToRay().rayDiv(totalLiquidity.wadToRay()); uint256 result = amountToLiquidityRatio.add(WadRayMath.ray()); result = result.rayMul(reserve.liquidityIndex); require(result <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(result); } /** * @dev Initializes a reserve * @param reserve The reserve object * @param aTokenAddress The address of the overlying atoken contract * @param interestRateStrategyAddress The address of the interest rate strategy contract **/ function init( DataTypes.ReserveData storage reserve, address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress ) external { require(reserve.aTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED); reserve.liquidityIndex = uint128(WadRayMath.ray()); reserve.variableBorrowIndex = uint128(WadRayMath.ray()); reserve.aTokenAddress = aTokenAddress; reserve.stableDebtTokenAddress = stableDebtTokenAddress; reserve.variableDebtTokenAddress = variableDebtTokenAddress; reserve.interestRateStrategyAddress = interestRateStrategyAddress; } struct UpdateInterestRatesLocalVars { address stableDebtTokenAddress; uint256 availableLiquidity; uint256 totalStableDebt; uint256 newLiquidityRate; uint256 newStableRate; uint256 newVariableRate; uint256 avgStableRate; uint256 totalVariableDebt; } /** * @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate * @param reserve The address of the reserve to be updated * @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action * @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow) **/ function updateInterestRates( DataTypes.ReserveData storage reserve, address reserveAddress, address aTokenAddress, uint256 liquidityAdded, uint256 liquidityTaken ) internal { UpdateInterestRatesLocalVars memory vars; vars.stableDebtTokenAddress = reserve.stableDebtTokenAddress; (vars.totalStableDebt, vars.avgStableRate) = IStableDebtToken(vars.stableDebtTokenAddress) .getTotalSupplyAndAvgRate(); //calculates the total variable debt locally using the scaled total supply instead //of totalSupply(), as it's noticeably cheaper. Also, the index has been //updated by the previous updateState() call vars.totalVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress) .scaledTotalSupply() .rayMul(reserve.variableBorrowIndex); ( vars.newLiquidityRate, vars.newStableRate, vars.newVariableRate ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates( reserveAddress, aTokenAddress, liquidityAdded, liquidityTaken, vars.totalStableDebt, vars.totalVariableDebt, vars.avgStableRate, reserve.configuration.getReserveFactor() ); require(vars.newLiquidityRate <= type(uint128).max, Errors.RL_LIQUIDITY_RATE_OVERFLOW); require(vars.newStableRate <= type(uint128).max, Errors.RL_STABLE_BORROW_RATE_OVERFLOW); require(vars.newVariableRate <= type(uint128).max, Errors.RL_VARIABLE_BORROW_RATE_OVERFLOW); reserve.currentLiquidityRate = uint128(vars.newLiquidityRate); reserve.currentStableBorrowRate = uint128(vars.newStableRate); reserve.currentVariableBorrowRate = uint128(vars.newVariableRate); emit ReserveDataUpdated( reserveAddress, vars.newLiquidityRate, vars.newStableRate, vars.newVariableRate, reserve.liquidityIndex, reserve.variableBorrowIndex ); } struct MintToTreasuryLocalVars { uint256 currentStableDebt; uint256 principalStableDebt; uint256 previousStableDebt; uint256 currentVariableDebt; uint256 previousVariableDebt; uint256 avgStableRate; uint256 cumulatedStableInterest; uint256 totalDebtAccrued; uint256 amountToMint; uint256 reserveFactor; uint40 stableSupplyUpdatedTimestamp; } /** * @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the * specific asset. * @param reserve The reserve reserve to be updated * @param scaledVariableDebt The current scaled total variable debt * @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest * @param newLiquidityIndex The new liquidity index * @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest **/ function _mintToTreasury( DataTypes.ReserveData storage reserve, uint256 scaledVariableDebt, uint256 previousVariableBorrowIndex, uint256 newLiquidityIndex, uint256 newVariableBorrowIndex, uint40 timestamp ) internal { MintToTreasuryLocalVars memory vars; vars.reserveFactor = reserve.configuration.getReserveFactor(); if (vars.reserveFactor == 0) { return; } //fetching the principal, total stable debt and the avg stable rate ( vars.principalStableDebt, vars.currentStableDebt, vars.avgStableRate, vars.stableSupplyUpdatedTimestamp ) = IStableDebtToken(reserve.stableDebtTokenAddress).getSupplyData(); //calculate the last principal variable debt vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex); //calculate the new total supply after accumulation of the index vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex); //calculate the stable debt until the last timestamp update vars.cumulatedStableInterest = MathUtils.calculateCompoundedInterest( vars.avgStableRate, vars.stableSupplyUpdatedTimestamp, timestamp ); vars.previousStableDebt = vars.principalStableDebt.rayMul(vars.cumulatedStableInterest); //debt accrued is the sum of the current debt minus the sum of the debt at the last update vars.totalDebtAccrued = vars .currentVariableDebt .add(vars.currentStableDebt) .sub(vars.previousVariableDebt) .sub(vars.previousStableDebt); vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor); if (vars.amountToMint != 0) { IAToken(reserve.aTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex); } } /** * @dev Updates the reserve indexes and the timestamp of the update * @param reserve The reserve reserve to be updated * @param scaledVariableDebt The scaled variable debt * @param liquidityIndex The last stored liquidity index * @param variableBorrowIndex The last stored variable borrow index **/ function _updateIndexes( DataTypes.ReserveData storage reserve, uint256 scaledVariableDebt, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 timestamp ) internal returns (uint256, uint256) { uint256 currentLiquidityRate = reserve.currentLiquidityRate; uint256 newLiquidityIndex = liquidityIndex; uint256 newVariableBorrowIndex = variableBorrowIndex; //only cumulating if there is any income being produced if (currentLiquidityRate > 0) { uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp); newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex); require(newLiquidityIndex <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(newLiquidityIndex); //as the liquidity rate might come only from stable rate loans, we need to ensure //that there is actual variable debt before accumulating if (scaledVariableDebt != 0) { uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp); newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex); require( newVariableBorrowIndex <= type(uint128).max, Errors.RL_VARIABLE_BORROW_INDEX_OVERFLOW ); reserve.variableBorrowIndex = uint128(newVariableBorrowIndex); } } //solium-disable-next-line reserve.lastUpdateTimestamp = uint40(block.timestamp); return (newLiquidityIndex, newVariableBorrowIndex); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveConfiguration library * @author Aave * @notice Implements the bitmap logic to handle the reserve configuration */ library ReserveConfiguration { uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore uint256 constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore uint256 constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore uint256 constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16; uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32; uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48; uint256 constant IS_ACTIVE_START_BIT_POSITION = 56; uint256 constant IS_FROZEN_START_BIT_POSITION = 57; uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58; uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59; uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64; uint256 constant MAX_VALID_LTV = 65535; uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535; uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535; uint256 constant MAX_VALID_DECIMALS = 255; uint256 constant MAX_VALID_RESERVE_FACTOR = 65535; /** * @dev Sets the Loan to Value of the reserve * @param self The reserve configuration * @param ltv the new ltv **/ function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure { require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV); self.data = (self.data & LTV_MASK) | ltv; } /** * @dev Gets the Loan to Value of the reserve * @param self The reserve configuration * @return The loan to value **/ function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return self.data & ~LTV_MASK; } /** * @dev Sets the liquidation threshold of the reserve * @param self The reserve configuration * @param threshold The new liquidation threshold **/ function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold) internal pure { require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD); self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION); } /** * @dev Gets the liquidation threshold of the reserve * @param self The reserve configuration * @return The liquidation threshold **/ function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION; } /** * @dev Sets the liquidation bonus of the reserve * @param self The reserve configuration * @param bonus The new liquidation bonus **/ function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus) internal pure { require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS); self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION); } /** * @dev Gets the liquidation bonus of the reserve * @param self The reserve configuration * @return The liquidation bonus **/ function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION; } /** * @dev Sets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @param decimals The decimals **/ function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals) internal pure { require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS); self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION); } /** * @dev Gets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @return The decimals of the asset **/ function getDecimals(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION; } /** * @dev Sets the active state of the reserve * @param self The reserve configuration * @param active The active state **/ function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure { self.data = (self.data & ACTIVE_MASK) | (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION); } /** * @dev Gets the active state of the reserve * @param self The reserve configuration * @return The active state **/ function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~ACTIVE_MASK) != 0; } /** * @dev Sets the frozen state of the reserve * @param self The reserve configuration * @param frozen The frozen state **/ function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure { self.data = (self.data & FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION); } /** * @dev Gets the frozen state of the reserve * @param self The reserve configuration * @return The frozen state **/ function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~FROZEN_MASK) != 0; } /** * @dev Enables or disables borrowing on the reserve * @param self The reserve configuration * @param enabled True if the borrowing needs to be enabled, false otherwise **/ function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure { self.data = (self.data & BORROWING_MASK) | (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION); } /** * @dev Gets the borrowing state of the reserve * @param self The reserve configuration * @return The borrowing state **/ function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~BORROWING_MASK) != 0; } /** * @dev Enables or disables stable rate borrowing on the reserve * @param self The reserve configuration * @param enabled True if the stable rate borrowing needs to be enabled, false otherwise **/ function setStableRateBorrowingEnabled( DataTypes.ReserveConfigurationMap memory self, bool enabled ) internal pure { self.data = (self.data & STABLE_BORROWING_MASK) | (uint256(enabled ? 1 : 0) << STABLE_BORROWING_ENABLED_START_BIT_POSITION); } /** * @dev Gets the stable rate borrowing state of the reserve * @param self The reserve configuration * @return The stable rate borrowing state **/ function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~STABLE_BORROWING_MASK) != 0; } /** * @dev Sets the reserve factor of the reserve * @param self The reserve configuration * @param reserveFactor The reserve factor **/ function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor) internal pure { require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR); self.data = (self.data & RESERVE_FACTOR_MASK) | (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION); } /** * @dev Gets the reserve factor of the reserve * @param self The reserve configuration * @return The reserve factor **/ function getReserveFactor(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION; } /** * @dev Gets the configuration flags of the reserve * @param self The reserve configuration * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlags(DataTypes.ReserveConfigurationMap storage self) internal view returns ( bool, bool, bool, bool ) { uint256 dataLocal = self.data; return ( (dataLocal & ~ACTIVE_MASK) != 0, (dataLocal & ~FROZEN_MASK) != 0, (dataLocal & ~BORROWING_MASK) != 0, (dataLocal & ~STABLE_BORROWING_MASK) != 0 ); } /** * @dev Gets the configuration paramters of the reserve * @param self The reserve configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals **/ function getParams(DataTypes.ReserveConfigurationMap storage self) internal view returns ( uint256, uint256, uint256, uint256, uint256 ) { uint256 dataLocal = self.data; return ( dataLocal & ~LTV_MASK, (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @dev Gets the configuration paramters of the reserve from a memory object * @param self The reserve configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals **/ function getParamsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( uint256, uint256, uint256, uint256, uint256 ) { return ( self.data & ~LTV_MASK, (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @dev Gets the configuration flags of the reserve from a memory object * @param self The reserve configuration * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( bool, bool, bool, bool ) { return ( (self.data & ~ACTIVE_MASK) != 0, (self.data & ~FROZEN_MASK) != 0, (self.data & ~BORROWING_MASK) != 0, (self.data & ~STABLE_BORROWING_MASK) != 0 ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title UserConfiguration library * @author Aave * @notice Implements the bitmap logic to handle the user configuration */ library UserConfiguration { uint256 internal constant BORROWING_MASK = 0x5555555555555555555555555555555555555555555555555555555555555555; /** * @dev Sets if the user is borrowing the reserve identified by reserveIndex * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @param borrowing True if the user is borrowing the reserve, false otherwise **/ function setBorrowing( DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool borrowing ) internal { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); self.data = (self.data & ~(1 << (reserveIndex * 2))) | (uint256(borrowing ? 1 : 0) << (reserveIndex * 2)); } /** * @dev Sets if the user is using as collateral the reserve identified by reserveIndex * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @param usingAsCollateral True if the user is usin the reserve as collateral, false otherwise **/ function setUsingAsCollateral( DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool usingAsCollateral ) internal { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); self.data = (self.data & ~(1 << (reserveIndex * 2 + 1))) | (uint256(usingAsCollateral ? 1 : 0) << (reserveIndex * 2 + 1)); } /** * @dev Used to validate if a user has been using the reserve for borrowing or as collateral * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve for borrowing or as collateral, false otherwise **/ function isUsingAsCollateralOrBorrowing( DataTypes.UserConfigurationMap memory self, uint256 reserveIndex ) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2)) & 3 != 0; } /** * @dev Used to validate if a user has been using the reserve for borrowing * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve for borrowing, false otherwise **/ function isBorrowing(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2)) & 1 != 0; } /** * @dev Used to validate if a user has been using the reserve as collateral * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve as collateral, false otherwise **/ function isUsingAsCollateral(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2 + 1)) & 1 != 0; } /** * @dev Used to validate if a user has been borrowing from any reserve * @param self The configuration object * @return True if the user has been borrowing any reserve, false otherwise **/ function isBorrowingAny(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data & BORROWING_MASK != 0; } /** * @dev Used to validate if a user has not been using any reserve * @param self The configuration object * @return True if the user has been borrowing any reserve, false otherwise **/ function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data == 0; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IReserveInterestRateStrategyInterface interface * @dev Interface for the calculation of the interest rates * @author Aave */ interface IReserveInterestRateStrategy { function baseVariableBorrowRate() external view returns (uint256); function getMaxVariableBorrowRate() external view returns (uint256); function calculateInterestRates( address reserve, uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256, uint256, uint256 ); function calculateInterestRates( address reserve, address aToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {WadRayMath} from './WadRayMath.sol'; library MathUtils { using SafeMath for uint256; using WadRayMath for uint256; /// @dev Ignoring leap years uint256 internal constant SECONDS_PER_YEAR = 365 days; /** * @dev Function to calculate the interest accumulated using a linear interest rate formula * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate linearly accumulated during the timeDelta, in ray **/ function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { //solium-disable-next-line uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp)); return (rate.mul(timeDifference) / SECONDS_PER_YEAR).add(WadRayMath.ray()); } /** * @dev Function to calculate the interest using a compounded interest rate formula * To avoid expensive exponentiation, the calculation is performed using a binomial approximation: * * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3... * * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods * * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate compounded during the timeDelta, in ray **/ function calculateCompoundedInterest( uint256 rate, uint40 lastUpdateTimestamp, uint256 currentTimestamp ) internal pure returns (uint256) { //solium-disable-next-line uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp)); if (exp == 0) { return WadRayMath.ray(); } uint256 expMinusOne = exp - 1; uint256 expMinusTwo = exp > 2 ? exp - 2 : 0; uint256 ratePerSecond = rate / SECONDS_PER_YEAR; uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2; uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6; return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm); } /** * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp * @param rate The interest rate (in ray) * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated **/ function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {FlashLoanReceiverBase} from '../../flashloan/base/FlashLoanReceiverBase.sol'; import {MintableERC20} from '../tokens/MintableERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; contract MockFlashLoanReceiver is FlashLoanReceiverBase { using SafeERC20 for IERC20; ILendingPoolAddressesProvider internal _provider; event ExecutedWithFail(address[] _assets, uint256[] _amounts, uint256[] _premiums); event ExecutedWithSuccess(address[] _assets, uint256[] _amounts, uint256[] _premiums); bool _failExecution; uint256 _amountToApprove; bool _simulateEOA; constructor(ILendingPoolAddressesProvider provider) public FlashLoanReceiverBase(provider) {} function setFailExecutionTransfer(bool fail) public { _failExecution = fail; } function setAmountToApprove(uint256 amountToApprove) public { _amountToApprove = amountToApprove; } function setSimulateEOA(bool flag) public { _simulateEOA = flag; } function amountToApprove() public view returns (uint256) { return _amountToApprove; } function simulateEOA() public view returns (bool) { return _simulateEOA; } function executeOperation( address[] memory assets, uint256[] memory amounts, uint256[] memory premiums, address initiator, bytes memory params ) public override returns (bool) { params; initiator; if (_failExecution) { emit ExecutedWithFail(assets, amounts, premiums); return !_simulateEOA; } for (uint256 i = 0; i < assets.length; i++) { //mint to this contract the specific amount MintableERC20 token = MintableERC20(assets[i]); //check the contract has the specified balance require( amounts[i] <= IERC20(assets[i]).balanceOf(address(this)), 'Invalid balance for the contract' ); uint256 amountToReturn = (_amountToApprove != 0) ? _amountToApprove : amounts[i].add(premiums[i]); //execution does not fail - mint tokens and return them to the _destination token.mint(premiums[i]); IERC20(assets[i]).approve(address(LENDING_POOL), amountToReturn); } emit ExecutedWithSuccess(assets, amounts, premiums); return true; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ERC20} from '../../dependencies/openzeppelin/contracts/ERC20.sol'; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract MintableERC20 is ERC20 { constructor( string memory name, string memory symbol, uint8 decimals ) public ERC20(name, symbol) { _setupDecimals(decimals); } /** * @dev Function to mint tokens * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(uint256 value) public returns (bool) { _mint(_msgSender(), value); return true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import './Context.sol'; import './IERC20.sol'; import './SafeMath.sol'; import './Address.sol'; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {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 {} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {Address} from '../dependencies/openzeppelin/contracts/Address.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; /** * @title WalletBalanceProvider contract * @author Aave, influenced by https://github.com/wbobeirne/eth-balance-checker/blob/master/contracts/BalanceChecker.sol * @notice Implements a logic of getting multiple tokens balance for one user address * @dev NOTE: THIS CONTRACT IS NOT USED WITHIN THE AAVE PROTOCOL. It's an accessory contract used to reduce the number of calls * towards the blockchain from the Aave backend. **/ contract WalletBalanceProvider { using Address for address payable; using Address for address; using SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; address constant MOCK_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /** @dev Fallback function, don't accept any ETH **/ receive() external payable { //only contracts can send ETH to the core require(msg.sender.isContract(), '22'); } /** @dev Check the token balance of a wallet in a token contract Returns the balance of the token for user. Avoids possible errors: - return 0 on non-contract address **/ function balanceOf(address user, address token) public view returns (uint256) { if (token == MOCK_ETH_ADDRESS) { return user.balance; // ETH balance // check if token is actually a contract } else if (token.isContract()) { return IERC20(token).balanceOf(user); } revert('INVALID_TOKEN'); } /** * @notice Fetches, for a list of _users and _tokens (ETH included with mock address), the balances * @param users The list of users * @param tokens The list of tokens * @return And array with the concatenation of, for each user, his/her balances **/ function batchBalanceOf(address[] calldata users, address[] calldata tokens) external view returns (uint256[] memory) { uint256[] memory balances = new uint256[](users.length * tokens.length); for (uint256 i = 0; i < users.length; i++) { for (uint256 j = 0; j < tokens.length; j++) { balances[i * tokens.length + j] = balanceOf(users[i], tokens[j]); } } return balances; } /** @dev provides balances of user wallet for all reserves available on the pool */ function getUserWalletBalances(address provider, address user) external view returns (address[] memory, uint256[] memory) { ILendingPool pool = ILendingPool(ILendingPoolAddressesProvider(provider).getLendingPool()); address[] memory reserves = pool.getReservesList(); address[] memory reservesWithEth = new address[](reserves.length + 1); for (uint256 i = 0; i < reserves.length; i++) { reservesWithEth[i] = reserves[i]; } reservesWithEth[reserves.length] = MOCK_ETH_ADDRESS; uint256[] memory balances = new uint256[](reservesWithEth.length); for (uint256 j = 0; j < reserves.length; j++) { DataTypes.ReserveConfigurationMap memory configuration = pool.getConfiguration(reservesWithEth[j]); (bool isActive, , , ) = configuration.getFlagsMemory(); if (!isActive) { balances[j] = 0; continue; } balances[j] = balanceOf(user, reservesWithEth[j]); } balances[reserves.length] = balanceOf(user, MOCK_ETH_ADDRESS); return (reservesWithEth, balances); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IWETH} from './interfaces/IWETH.sol'; import {IWETHGateway} from './interfaces/IWETHGateway.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {Helpers} from '../protocol/libraries/helpers/Helpers.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; contract WETHGateway is IWETHGateway, Ownable { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; IWETH internal immutable WETH; /** * @dev Sets the WETH address and the LendingPoolAddressesProvider address. Infinite approves lending pool. * @param weth Address of the Wrapped Ether contract **/ constructor(address weth) public { WETH = IWETH(weth); } function authorizeLendingPool(address lendingPool) external onlyOwner { WETH.approve(lendingPool, uint256(-1)); } /** * @dev deposits WETH into the reserve, using native ETH. A corresponding amount of the overlying asset (aTokens) * is minted. * @param lendingPool address of the targeted underlying lending pool * @param onBehalfOf address of the user who will receive the aTokens representing the deposit * @param referralCode integrators are assigned a referral code and can potentially receive rewards. **/ function depositETH( address lendingPool, address onBehalfOf, uint16 referralCode ) external payable override { WETH.deposit{value: msg.value}(); ILendingPool(lendingPool).deposit(address(WETH), msg.value, onBehalfOf, referralCode); } /** * @dev withdraws the WETH _reserves of msg.sender. * @param lendingPool address of the targeted underlying lending pool * @param amount amount of aWETH to withdraw and receive native ETH * @param to address of the user who will receive native ETH */ function withdrawETH( address lendingPool, uint256 amount, address to ) external override { IAToken aWETH = IAToken(ILendingPool(lendingPool).getReserveData(address(WETH)).aTokenAddress); uint256 userBalance = aWETH.balanceOf(msg.sender); uint256 amountToWithdraw = amount; // if amount is equal to uint(-1), the user wants to redeem everything if (amount == type(uint256).max) { amountToWithdraw = userBalance; } aWETH.transferFrom(msg.sender, address(this), amountToWithdraw); ILendingPool(lendingPool).withdraw(address(WETH), amountToWithdraw, address(this)); WETH.withdraw(amountToWithdraw); _safeTransferETH(to, amountToWithdraw); } /** * @dev repays a borrow on the WETH reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified). * @param lendingPool address of the targeted underlying lending pool * @param amount the amount to repay, or uint256(-1) if the user wants to repay everything * @param rateMode the rate mode to repay * @param onBehalfOf the address for which msg.sender is repaying */ function repayETH( address lendingPool, uint256 amount, uint256 rateMode, address onBehalfOf ) external payable override { (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebtMemory( onBehalfOf, ILendingPool(lendingPool).getReserveData(address(WETH)) ); uint256 paybackAmount = DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } require(msg.value >= paybackAmount, 'msg.value is less than repayment amount'); WETH.deposit{value: paybackAmount}(); ILendingPool(lendingPool).repay(address(WETH), msg.value, rateMode, onBehalfOf); // refund remaining dust eth if (msg.value > paybackAmount) _safeTransferETH(msg.sender, msg.value - paybackAmount); } /** * @dev borrow WETH, unwraps to ETH and send both the ETH and DebtTokens to msg.sender, via `approveDelegation` and onBehalf argument in `LendingPool.borrow`. * @param lendingPool address of the targeted underlying lending pool * @param amount the amount of ETH to borrow * @param interesRateMode the interest rate mode * @param referralCode integrators are assigned a referral code and can potentially receive rewards */ function borrowETH( address lendingPool, uint256 amount, uint256 interesRateMode, uint16 referralCode ) external override { ILendingPool(lendingPool).borrow( address(WETH), amount, interesRateMode, referralCode, msg.sender ); WETH.withdraw(amount); _safeTransferETH(msg.sender, amount); } /** * @dev transfer ETH to an address, revert if it fails. * @param to recipient of the transfer * @param value the amount to send */ function _safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'ETH_TRANSFER_FAILED'); } /** * @dev transfer ERC20 from the utility contract, for ERC20 recovery in case of stuck tokens due * direct transfers to the contract address. * @param token token to transfer * @param to recipient of the transfer * @param amount amount to send */ function emergencyTokenTransfer( address token, address to, uint256 amount ) external onlyOwner { IERC20(token).transfer(to, amount); } /** * @dev transfer native Ether from the utility contract, for native Ether recovery in case of stuck Ether * due selfdestructs or transfer ether to pre-computated contract address before deployment. * @param to recipient of the transfer * @param amount amount to send */ function emergencyEtherTransfer(address to, uint256 amount) external onlyOwner { _safeTransferETH(to, amount); } /** * @dev Get WETH address used by WETHGateway */ function getWETHAddress() external view returns (address) { return address(WETH); } /** * @dev Only WETH contract is allowed to transfer ETH here. Prevent other addresses to send Ether to this contract. */ receive() external payable { require(msg.sender == address(WETH), 'Receive not allowed'); } /** * @dev Revert fallback calls */ fallback() external payable { revert('Fallback not allowed'); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IWETH { function deposit() external payable; function withdraw(uint256) external; function approve(address guy, uint256 wad) external returns (bool); function transferFrom( address src, address dst, uint256 wad ) external returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IWETHGateway { function depositETH( address lendingPool, address onBehalfOf, uint16 referralCode ) external payable; function withdrawETH( address lendingPool, uint256 amount, address onBehalfOf ) external; function repayETH( address lendingPool, uint256 amount, uint256 rateMode, address onBehalfOf ) external payable; function borrowETH( address lendingPool, uint256 amount, uint256 interesRateMode, uint16 referralCode ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IReserveInterestRateStrategy} from '../../interfaces/IReserveInterestRateStrategy.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import 'hardhat/console.sol'; /** * @title DefaultReserveInterestRateStrategy contract * @notice Implements the calculation of the interest rates depending on the reserve state * @dev The model of interest rate is based on 2 slopes, one before the `OPTIMAL_UTILIZATION_RATE` * point of utilization and another from that one to 100% * - An instance of this same contract, can't be used across different Aave markets, due to the caching * of the LendingPoolAddressesProvider * @author Aave **/ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { using WadRayMath for uint256; using SafeMath for uint256; using PercentageMath for uint256; /** * @dev this constant represents the utilization rate at which the pool aims to obtain most competitive borrow rates. * Expressed in ray **/ uint256 public immutable OPTIMAL_UTILIZATION_RATE; /** * @dev This constant represents the excess utilization rate above the optimal. It's always equal to * 1-optimal utilization rate. Added as a constant here for gas optimizations. * Expressed in ray **/ uint256 public immutable EXCESS_UTILIZATION_RATE; ILendingPoolAddressesProvider public immutable addressesProvider; // Base variable borrow rate when Utilization rate = 0. Expressed in ray uint256 internal immutable _baseVariableBorrowRate; // Slope of the variable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _variableRateSlope1; // Slope of the variable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _variableRateSlope2; // Slope of the stable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope1; // Slope of the stable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope2; constructor( ILendingPoolAddressesProvider provider, uint256 optimalUtilizationRate, uint256 baseVariableBorrowRate, uint256 variableRateSlope1, uint256 variableRateSlope2, uint256 stableRateSlope1, uint256 stableRateSlope2 ) public { OPTIMAL_UTILIZATION_RATE = optimalUtilizationRate; EXCESS_UTILIZATION_RATE = WadRayMath.ray().sub(optimalUtilizationRate); addressesProvider = provider; _baseVariableBorrowRate = baseVariableBorrowRate; _variableRateSlope1 = variableRateSlope1; _variableRateSlope2 = variableRateSlope2; _stableRateSlope1 = stableRateSlope1; _stableRateSlope2 = stableRateSlope2; } function variableRateSlope1() external view returns (uint256) { return _variableRateSlope1; } function variableRateSlope2() external view returns (uint256) { return _variableRateSlope2; } function stableRateSlope1() external view returns (uint256) { return _stableRateSlope1; } function stableRateSlope2() external view returns (uint256) { return _stableRateSlope2; } function baseVariableBorrowRate() external view override returns (uint256) { return _baseVariableBorrowRate; } function getMaxVariableBorrowRate() external view override returns (uint256) { return _baseVariableBorrowRate.add(_variableRateSlope1).add(_variableRateSlope2); } /** * @dev Calculates the interest rates depending on the reserve's state and configurations * @param reserve The address of the reserve * @param liquidityAdded The liquidity added during the operation * @param liquidityTaken The liquidity taken during the operation * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param averageStableBorrowRate The weighted average of all the stable rate loans * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market * @return The liquidity rate, the stable borrow rate and the variable borrow rate **/ function calculateInterestRates( address reserve, address aToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view override returns ( uint256, uint256, uint256 ) { uint256 availableLiquidity = IERC20(reserve).balanceOf(aToken); //avoid stack too deep availableLiquidity = availableLiquidity.add(liquidityAdded).sub(liquidityTaken); return calculateInterestRates( reserve, availableLiquidity, totalStableDebt, totalVariableDebt, averageStableBorrowRate, reserveFactor ); } struct CalcInterestRatesLocalVars { uint256 totalDebt; uint256 currentVariableBorrowRate; uint256 currentStableBorrowRate; uint256 currentLiquidityRate; uint256 utilizationRate; } /** * @dev Calculates the interest rates depending on the reserve's state and configurations. * NOTE This function is kept for compatibility with the previous DefaultInterestRateStrategy interface. * New protocol implementation uses the new calculateInterestRates() interface * @param reserve The address of the reserve * @param availableLiquidity The liquidity available in the corresponding aToken * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param averageStableBorrowRate The weighted average of all the stable rate loans * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market * @return The liquidity rate, the stable borrow rate and the variable borrow rate **/ function calculateInterestRates( address reserve, uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) public view override returns ( uint256, uint256, uint256 ) { CalcInterestRatesLocalVars memory vars; vars.totalDebt = totalStableDebt.add(totalVariableDebt); vars.currentVariableBorrowRate = 0; vars.currentStableBorrowRate = 0; vars.currentLiquidityRate = 0; vars.utilizationRate = vars.totalDebt == 0 ? 0 : vars.totalDebt.rayDiv(availableLiquidity.add(vars.totalDebt)); vars.currentStableBorrowRate = ILendingRateOracle(addressesProvider.getLendingRateOracle()) .getMarketBorrowRate(reserve); if (vars.utilizationRate > OPTIMAL_UTILIZATION_RATE) { uint256 excessUtilizationRateRatio = vars.utilizationRate.sub(OPTIMAL_UTILIZATION_RATE).rayDiv(EXCESS_UTILIZATION_RATE); vars.currentStableBorrowRate = vars.currentStableBorrowRate.add(_stableRateSlope1).add( _stableRateSlope2.rayMul(excessUtilizationRateRatio) ); vars.currentVariableBorrowRate = _baseVariableBorrowRate.add(_variableRateSlope1).add( _variableRateSlope2.rayMul(excessUtilizationRateRatio) ); } else { vars.currentStableBorrowRate = vars.currentStableBorrowRate.add( _stableRateSlope1.rayMul(vars.utilizationRate.rayDiv(OPTIMAL_UTILIZATION_RATE)) ); vars.currentVariableBorrowRate = _baseVariableBorrowRate.add( vars.utilizationRate.rayMul(_variableRateSlope1).rayDiv(OPTIMAL_UTILIZATION_RATE) ); } vars.currentLiquidityRate = _getOverallBorrowRate( totalStableDebt, totalVariableDebt, vars .currentVariableBorrowRate, averageStableBorrowRate ) .rayMul(vars.utilizationRate) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(reserveFactor)); return ( vars.currentLiquidityRate, vars.currentStableBorrowRate, vars.currentVariableBorrowRate ); } /** * @dev Calculates the overall borrow rate as the weighted average between the total variable debt and total stable debt * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param currentVariableBorrowRate The current variable borrow rate of the reserve * @param currentAverageStableBorrowRate The current weighted average of all the stable rate loans * @return The weighted averaged borrow rate **/ function _getOverallBorrowRate( uint256 totalStableDebt, uint256 totalVariableDebt, uint256 currentVariableBorrowRate, uint256 currentAverageStableBorrowRate ) internal pure returns (uint256) { uint256 totalDebt = totalStableDebt.add(totalVariableDebt); if (totalDebt == 0) return 0; uint256 weightedVariableRate = totalVariableDebt.wadToRay().rayMul(currentVariableBorrowRate); uint256 weightedStableRate = totalStableDebt.wadToRay().rayMul(currentAverageStableBorrowRate); uint256 overallBorrowRate = weightedVariableRate.add(weightedStableRate).rayDiv(totalDebt.wadToRay()); return overallBorrowRate; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title ILendingRateOracle interface * @notice Interface for the Aave borrow rate oracle. Provides the average market borrow rate to be used as a base for the stable borrow rate calculations **/ interface ILendingRateOracle { /** @dev returns the market borrow rate in ray **/ function getMarketBorrowRate(address asset) external view returns (uint256); /** @dev sets the market borrow rate. Rate value must be in ray **/ function setMarketBorrowRate(address asset, uint256 rate) external; } // 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: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUiPoolDataProvider} from './interfaces/IUiPoolDataProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol'; import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol'; import {WadRayMath} from '../protocol/libraries/math/WadRayMath.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import { DefaultReserveInterestRateStrategy } from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol'; contract UiPoolDataProvider is IUiPoolDataProvider { using WadRayMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; address public constant MOCK_USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96; function getInterestRateStrategySlopes(DefaultReserveInterestRateStrategy interestRateStrategy) internal view returns ( uint256, uint256, uint256, uint256 ) { return ( interestRateStrategy.variableRateSlope1(), interestRateStrategy.variableRateSlope2(), interestRateStrategy.stableRateSlope1(), interestRateStrategy.stableRateSlope2() ); } function getReservesData(ILendingPoolAddressesProvider provider, address user) external view override returns ( AggregatedReserveData[] memory, UserReserveData[] memory, uint256 ) { ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); IPriceOracleGetter oracle = IPriceOracleGetter(provider.getPriceOracle()); address[] memory reserves = lendingPool.getReservesList(); DataTypes.UserConfigurationMap memory userConfig = lendingPool.getUserConfiguration(user); AggregatedReserveData[] memory reservesData = new AggregatedReserveData[](reserves.length); UserReserveData[] memory userReservesData = new UserReserveData[](user != address(0) ? reserves.length : 0); for (uint256 i = 0; i < reserves.length; i++) { AggregatedReserveData memory reserveData = reservesData[i]; reserveData.underlyingAsset = reserves[i]; // reserve current state DataTypes.ReserveData memory baseData = lendingPool.getReserveData(reserveData.underlyingAsset); reserveData.liquidityIndex = baseData.liquidityIndex; reserveData.variableBorrowIndex = baseData.variableBorrowIndex; reserveData.liquidityRate = baseData.currentLiquidityRate; reserveData.variableBorrowRate = baseData.currentVariableBorrowRate; reserveData.stableBorrowRate = baseData.currentStableBorrowRate; reserveData.lastUpdateTimestamp = baseData.lastUpdateTimestamp; reserveData.aTokenAddress = baseData.aTokenAddress; reserveData.stableDebtTokenAddress = baseData.stableDebtTokenAddress; reserveData.variableDebtTokenAddress = baseData.variableDebtTokenAddress; reserveData.interestRateStrategyAddress = baseData.interestRateStrategyAddress; reserveData.priceInEth = oracle.getAssetPrice(reserveData.underlyingAsset); reserveData.availableLiquidity = IERC20Detailed(reserveData.underlyingAsset).balanceOf( reserveData.aTokenAddress ); ( reserveData.totalPrincipalStableDebt, , reserveData.averageStableRate, reserveData.stableDebtLastUpdateTimestamp ) = IStableDebtToken(reserveData.stableDebtTokenAddress).getSupplyData(); reserveData.totalScaledVariableDebt = IVariableDebtToken(reserveData.variableDebtTokenAddress) .scaledTotalSupply(); // reserve configuration // we're getting this info from the aToken, because some of assets can be not compliant with ETC20Detailed reserveData.symbol = IERC20Detailed(reserveData.aTokenAddress).symbol(); reserveData.name = ''; ( reserveData.baseLTVasCollateral, reserveData.reserveLiquidationThreshold, reserveData.reserveLiquidationBonus, reserveData.decimals, reserveData.reserveFactor ) = baseData.configuration.getParamsMemory(); ( reserveData.isActive, reserveData.isFrozen, reserveData.borrowingEnabled, reserveData.stableBorrowRateEnabled ) = baseData.configuration.getFlagsMemory(); reserveData.usageAsCollateralEnabled = reserveData.baseLTVasCollateral != 0; ( reserveData.variableRateSlope1, reserveData.variableRateSlope2, reserveData.stableRateSlope1, reserveData.stableRateSlope2 ) = getInterestRateStrategySlopes( DefaultReserveInterestRateStrategy(reserveData.interestRateStrategyAddress) ); if (user != address(0)) { // user reserve data userReservesData[i].underlyingAsset = reserveData.underlyingAsset; userReservesData[i].scaledATokenBalance = IAToken(reserveData.aTokenAddress) .scaledBalanceOf(user); userReservesData[i].usageAsCollateralEnabledOnUser = userConfig.isUsingAsCollateral(i); if (userConfig.isBorrowing(i)) { userReservesData[i].scaledVariableDebt = IVariableDebtToken( reserveData .variableDebtTokenAddress ) .scaledBalanceOf(user); userReservesData[i].principalStableDebt = IStableDebtToken( reserveData .stableDebtTokenAddress ) .principalBalanceOf(user); if (userReservesData[i].principalStableDebt != 0) { userReservesData[i].stableBorrowRate = IStableDebtToken( reserveData .stableDebtTokenAddress ) .getUserStableRate(user); userReservesData[i].stableBorrowLastUpdateTimestamp = IStableDebtToken( reserveData .stableDebtTokenAddress ) .getUserLastUpdated(user); } } } } return (reservesData, userReservesData, oracle.getAssetPrice(MOCK_USD_ADDRESS)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; interface IUiPoolDataProvider { struct AggregatedReserveData { address underlyingAsset; string name; string symbol; uint256 decimals; uint256 baseLTVasCollateral; uint256 reserveLiquidationThreshold; uint256 reserveLiquidationBonus; uint256 reserveFactor; bool usageAsCollateralEnabled; bool borrowingEnabled; bool stableBorrowRateEnabled; bool isActive; bool isFrozen; // base data uint128 liquidityIndex; uint128 variableBorrowIndex; uint128 liquidityRate; uint128 variableBorrowRate; uint128 stableBorrowRate; uint40 lastUpdateTimestamp; address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; address interestRateStrategyAddress; // uint256 availableLiquidity; uint256 totalPrincipalStableDebt; uint256 averageStableRate; uint256 stableDebtLastUpdateTimestamp; uint256 totalScaledVariableDebt; uint256 priceInEth; uint256 variableRateSlope1; uint256 variableRateSlope2; uint256 stableRateSlope1; uint256 stableRateSlope2; } // // struct ReserveData { // uint256 averageStableBorrowRate; // uint256 totalLiquidity; // } struct UserReserveData { address underlyingAsset; uint256 scaledATokenBalance; bool usageAsCollateralEnabledOnUser; uint256 stableBorrowRate; uint256 scaledVariableDebt; uint256 principalStableDebt; uint256 stableBorrowLastUpdateTimestamp; } // // struct ATokenSupplyData { // string name; // string symbol; // uint8 decimals; // uint256 totalSupply; // address aTokenAddress; // } function getReservesData(ILendingPoolAddressesProvider provider, address user) external view returns ( AggregatedReserveData[] memory, UserReserveData[] memory, uint256 ); // function getUserReservesData(ILendingPoolAddressesProvider provider, address user) // external // view // returns (UserReserveData[] memory); // // function getAllATokenSupply(ILendingPoolAddressesProvider provider) // external // view // returns (ATokenSupplyData[] memory); // // function getATokenSupply(address[] calldata aTokens) // external // view // returns (ATokenSupplyData[] memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; contract AaveProtocolDataProvider { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; address constant MKR = 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2; address constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; struct TokenData { string symbol; address tokenAddress; } ILendingPoolAddressesProvider public immutable ADDRESSES_PROVIDER; constructor(ILendingPoolAddressesProvider addressesProvider) public { ADDRESSES_PROVIDER = addressesProvider; } function getAllReservesTokens() external view returns (TokenData[] memory) { ILendingPool pool = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()); address[] memory reserves = pool.getReservesList(); TokenData[] memory reservesTokens = new TokenData[](reserves.length); for (uint256 i = 0; i < reserves.length; i++) { if (reserves[i] == MKR) { reservesTokens[i] = TokenData({symbol: 'MKR', tokenAddress: reserves[i]}); continue; } if (reserves[i] == ETH) { reservesTokens[i] = TokenData({symbol: 'ETH', tokenAddress: reserves[i]}); continue; } reservesTokens[i] = TokenData({ symbol: IERC20Detailed(reserves[i]).symbol(), tokenAddress: reserves[i] }); } return reservesTokens; } function getAllATokens() external view returns (TokenData[] memory) { ILendingPool pool = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()); address[] memory reserves = pool.getReservesList(); TokenData[] memory aTokens = new TokenData[](reserves.length); for (uint256 i = 0; i < reserves.length; i++) { DataTypes.ReserveData memory reserveData = pool.getReserveData(reserves[i]); aTokens[i] = TokenData({ symbol: IERC20Detailed(reserveData.aTokenAddress).symbol(), tokenAddress: reserveData.aTokenAddress }); } return aTokens; } function getReserveConfigurationData(address asset) external view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ) { DataTypes.ReserveConfigurationMap memory configuration = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getConfiguration(asset); (ltv, liquidationThreshold, liquidationBonus, decimals, reserveFactor) = configuration .getParamsMemory(); (isActive, isFrozen, borrowingEnabled, stableBorrowRateEnabled) = configuration .getFlagsMemory(); usageAsCollateralEnabled = liquidationThreshold > 0; } function getReserveData(address asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); return ( IERC20Detailed(asset).balanceOf(reserve.aTokenAddress), IERC20Detailed(reserve.stableDebtTokenAddress).totalSupply(), IERC20Detailed(reserve.variableDebtTokenAddress).totalSupply(), reserve.currentLiquidityRate, reserve.currentVariableBorrowRate, reserve.currentStableBorrowRate, IStableDebtToken(reserve.stableDebtTokenAddress).getAverageStableRate(), reserve.liquidityIndex, reserve.variableBorrowIndex, reserve.lastUpdateTimestamp ); } function getUserReserveData(address asset, address user) external view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); DataTypes.UserConfigurationMap memory userConfig = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getUserConfiguration(user); currentATokenBalance = IERC20Detailed(reserve.aTokenAddress).balanceOf(user); currentVariableDebt = IERC20Detailed(reserve.variableDebtTokenAddress).balanceOf(user); currentStableDebt = IERC20Detailed(reserve.stableDebtTokenAddress).balanceOf(user); principalStableDebt = IStableDebtToken(reserve.stableDebtTokenAddress).principalBalanceOf(user); scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledBalanceOf(user); liquidityRate = reserve.currentLiquidityRate; stableBorrowRate = IStableDebtToken(reserve.stableDebtTokenAddress).getUserStableRate(user); stableRateLastUpdated = IStableDebtToken(reserve.stableDebtTokenAddress).getUserLastUpdated( user ); usageAsCollateralEnabled = userConfig.isUsingAsCollateral(reserve.id); } function getReserveTokensAddresses(address asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); return ( reserve.aTokenAddress, reserve.stableDebtTokenAddress, reserve.variableDebtTokenAddress ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {DebtTokenBase} from './base/DebtTokenBase.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title VariableDebtToken * @notice Implements a variable debt token to track the borrowing positions of users * at variable rate mode * @author Aave **/ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; ILendingPool internal _pool; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) public override initializer { _setName(debtTokenName); _setSymbol(debtTokenSymbol); _setDecimals(debtTokenDecimals); _pool = pool; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), address(incentivesController), debtTokenDecimals, debtTokenName, debtTokenSymbol, params ); } /** * @dev Gets the revision of the stable debt token implementation * @return The debt token implementation revision **/ function getRevision() internal pure virtual override returns (uint256) { return DEBT_TOKEN_REVISION; } /** * @dev Calculates the accumulated debt balance of the user * @return The debt balance of the user **/ function balanceOf(address user) public view virtual override returns (uint256) { uint256 scaledBalance = super.balanceOf(user); if (scaledBalance == 0) { return 0; } return scaledBalance.rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } /** * @dev Mints debt token to the `onBehalfOf` address * - Only callable by the LendingPool * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { if (user != onBehalfOf) { _decreaseBorrowAllowance(onBehalfOf, user, amount); } uint256 previousBalance = super.balanceOf(onBehalfOf); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(onBehalfOf, amountScaled); emit Transfer(address(0), onBehalfOf, amount); emit Mint(user, onBehalfOf, amount, index); return previousBalance == 0; } /** * @dev Burns user variable debt * - Only callable by the LendingPool * @param user The user whose debt is getting burned * @param amount The amount getting burned * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); emit Transfer(user, address(0), amount); emit Burn(user, amount, index); } /** * @dev Returns the principal debt balance of the user from * @return The debt balance of the user since the last burn/mint action **/ function scaledBalanceOf(address user) public view virtual override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the total supply of the variable debt token. Represents the total debt accrued by the users * @return The total supply **/ function totalSupply() public view virtual override returns (uint256) { return super.totalSupply().rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return the scaled total supply **/ function scaledTotalSupply() public view virtual override returns (uint256) { return super.totalSupply(); } /** * @dev Returns the principal balance of the user and principal total supply. * @param user The address of the user * @return The principal balance of the user * @return The principal total supply **/ function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { return (super.balanceOf(user), super.totalSupply()); } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } function _getUnderlyingAssetAddress() internal view override returns (address) { return _underlyingAsset; } function _getLendingPool() internal view override returns (ILendingPool) { return _pool; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from '../../../interfaces/ILendingPool.sol'; import {ICreditDelegationToken} from '../../../interfaces/ICreditDelegationToken.sol'; import { VersionedInitializable } from '../../libraries/aave-upgradeability/VersionedInitializable.sol'; import {IncentivizedERC20} from '../IncentivizedERC20.sol'; import {Errors} from '../../libraries/helpers/Errors.sol'; /** * @title DebtTokenBase * @notice Base contract for different types of debt tokens, like StableDebtToken or VariableDebtToken * @author Aave */ abstract contract DebtTokenBase is IncentivizedERC20('DEBTTOKEN_IMPL', 'DEBTTOKEN_IMPL', 0), VersionedInitializable, ICreditDelegationToken { mapping(address => mapping(address => uint256)) internal _borrowAllowances; /** * @dev Only lending pool can call functions marked by this modifier **/ modifier onlyLendingPool { require(_msgSender() == address(_getLendingPool()), Errors.CT_CALLER_MUST_BE_LENDING_POOL); _; } /** * @dev delegates borrowing power to a user on the specific debt token * @param delegatee the address receiving the delegated borrowing power * @param amount the maximum amount being delegated. Delegation will still * respect the liquidation constraints (even if delegated, a delegatee cannot * force a delegator HF to go below 1) **/ function approveDelegation(address delegatee, uint256 amount) external override { _borrowAllowances[_msgSender()][delegatee] = amount; emit BorrowAllowanceDelegated(_msgSender(), delegatee, _getUnderlyingAssetAddress(), amount); } /** * @dev returns the borrow allowance of the user * @param fromUser The user to giving allowance * @param toUser The user to give allowance to * @return the current allowance of toUser **/ function borrowAllowance(address fromUser, address toUser) external view override returns (uint256) { return _borrowAllowances[fromUser][toUser]; } /** * @dev Being non transferrable, the debt token does not implement any of the * standard ERC20 functions for transfer and allowance. **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { recipient; amount; revert('TRANSFER_NOT_SUPPORTED'); } function allowance(address owner, address spender) public view virtual override returns (uint256) { owner; spender; revert('ALLOWANCE_NOT_SUPPORTED'); } function approve(address spender, uint256 amount) public virtual override returns (bool) { spender; amount; revert('APPROVAL_NOT_SUPPORTED'); } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { sender; recipient; amount; revert('TRANSFER_NOT_SUPPORTED'); } function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) { spender; addedValue; revert('ALLOWANCE_NOT_SUPPORTED'); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) { spender; subtractedValue; revert('ALLOWANCE_NOT_SUPPORTED'); } function _decreaseBorrowAllowance( address delegator, address delegatee, uint256 amount ) internal { uint256 newAllowance = _borrowAllowances[delegator][delegatee].sub(amount, Errors.BORROW_ALLOWANCE_NOT_ENOUGH); _borrowAllowances[delegator][delegatee] = newAllowance; emit BorrowAllowanceDelegated(delegator, delegatee, _getUnderlyingAssetAddress(), newAllowance); } function _getUnderlyingAssetAddress() internal view virtual returns (address); function _getLendingPool() internal view virtual returns (ILendingPool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface ICreditDelegationToken { event BorrowAllowanceDelegated( address indexed fromUser, address indexed toUser, address asset, uint256 amount ); /** * @dev delegates borrowing power to a user on the specific debt token * @param delegatee the address receiving the delegated borrowing power * @param amount the maximum amount being delegated. Delegation will still * respect the liquidation constraints (even if delegated, a delegatee cannot * force a delegator HF to go below 1) **/ function approveDelegation(address delegatee, uint256 amount) external; /** * @dev returns the borrow allowance of the user * @param fromUser The user to giving allowance * @param toUser The user to give allowance to * @return the current allowance of toUser **/ function borrowAllowance(address fromUser, address toUser) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Context} from '../../dependencies/openzeppelin/contracts/Context.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title ERC20 * @notice Basic ERC20 implementation * @author Aave, inspired by the Openzeppelin ERC20 implementation **/ abstract contract IncentivizedERC20 is Context, IERC20, IERC20Detailed { using SafeMath for uint256; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 internal _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor( string memory name, string memory symbol, uint8 decimals ) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return The name of the token **/ function name() public view override returns (string memory) { return _name; } /** * @return The symbol of the token **/ function symbol() public view override returns (string memory) { return _symbol; } /** * @return The decimals of the token **/ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total supply of the token **/ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @return The balance of the token **/ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @return Abstract function implemented by the child aToken/debtToken. * Done this way in order to not break compatibility with previous versions of aTokens/debtTokens **/ function _getIncentivesController() internal view virtual returns(IAaveIncentivesController); /** * @dev Executes a transfer of tokens from _msgSender() to recipient * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); emit Transfer(_msgSender(), recipient, amount); return true; } /** * @dev Returns the allowance of spender on the tokens owned by owner * @param owner The owner of the tokens * @param spender The user allowed to spend the owner's tokens * @return The amount of owner's tokens spender is allowed to spend **/ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev Allows `spender` to spend the tokens owned by _msgSender() * @param spender The user allowed to spend _msgSender() tokens * @return `true` **/ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev Executes a transfer of token from sender to recipient, if _msgSender() is allowed to do so * @param sender The owner of the tokens * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ 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') ); emit Transfer(sender, recipient, amount); return true; } /** * @dev Increases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param addedValue The amount being added to the allowance * @return `true` **/ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Decreases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param subtractedValue The amount being subtracted to the allowance * @return `true` **/ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, 'ERC20: decreased allowance below zero' ) ); return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), 'ERC20: transfer from the zero address'); require(recipient != address(0), 'ERC20: transfer to the zero address'); _beforeTokenTransfer(sender, recipient, amount); uint256 oldSenderBalance = _balances[sender]; _balances[sender] = oldSenderBalance.sub(amount, 'ERC20: transfer amount exceeds balance'); uint256 oldRecipientBalance = _balances[recipient]; _balances[recipient] = _balances[recipient].add(amount); if (address(_getIncentivesController()) != address(0)) { uint256 currentTotalSupply = _totalSupply; _getIncentivesController().handleAction(sender, currentTotalSupply, oldSenderBalance); if (sender != recipient) { _getIncentivesController().handleAction(recipient, currentTotalSupply, oldRecipientBalance); } } } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: mint to the zero address'); _beforeTokenTransfer(address(0), account, amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.add(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.add(amount); if (address(_getIncentivesController()) != address(0)) { _getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance); } } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: burn from the zero address'); _beforeTokenTransfer(account, address(0), amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.sub(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, 'ERC20: burn amount exceeds balance'); if (address(_getIncentivesController()) != address(0)) { _getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance); } } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), 'ERC20: approve from the zero address'); require(spender != address(0), 'ERC20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setName(string memory newName) internal { _name = newName; } function _setSymbol(string memory newSymbol) internal { _symbol = newSymbol; } function _setDecimals(uint8 newDecimals) internal { _decimals = newDecimals; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {VariableDebtToken} from '../../protocol/tokenization/VariableDebtToken.sol'; contract MockVariableDebtToken is VariableDebtToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {AToken} from '../../protocol/tokenization/AToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; contract MockAToken is AToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {IncentivizedERC20} from './IncentivizedERC20.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title Aave ERC20 AToken * @dev Implementation of the interest bearing token for the Aave protocol * @author Aave */ contract AToken is VersionedInitializable, IncentivizedERC20('ATOKEN_IMPL', 'ATOKEN_IMPL', 0), IAToken { using WadRayMath for uint256; using SafeERC20 for IERC20; bytes public constant EIP712_REVISION = bytes('1'); bytes32 internal constant EIP712_DOMAIN = keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'); bytes32 public constant PERMIT_TYPEHASH = keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'); uint256 public constant ATOKEN_REVISION = 0x1; /// @dev owner => next valid nonce to submit with permit() mapping(address => uint256) public _nonces; bytes32 public DOMAIN_SEPARATOR; ILendingPool internal _pool; address internal _treasury; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; modifier onlyLendingPool { require(_msgSender() == address(_pool), Errors.CT_CALLER_MUST_BE_LENDING_POOL); _; } function getRevision() internal pure virtual override returns (uint256) { return ATOKEN_REVISION; } /** * @dev Initializes the aToken * @param pool The address of the lending pool where this aToken will be used * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external override initializer { uint256 chainId; //solium-disable-next-line assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN, keccak256(bytes(aTokenName)), keccak256(EIP712_REVISION), chainId, address(this) ) ); _setName(aTokenName); _setSymbol(aTokenSymbol); _setDecimals(aTokenDecimals); _pool = pool; _treasury = treasury; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), treasury, address(incentivesController), aTokenDecimals, aTokenName, aTokenSymbol, params ); } /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); IERC20(_underlyingAsset).safeTransfer(receiverOfUnderlying, amount); emit Transfer(user, address(0), amount); emit Burn(user, receiverOfUnderlying, amount, index); } /** * @dev Mints `amount` aTokens to `user` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { uint256 previousBalance = super.balanceOf(user); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(user, amountScaled); emit Transfer(address(0), user, amount); emit Mint(user, amount, index); return previousBalance == 0; } /** * @dev Mints aTokens to the reserve treasury * - Only callable by the LendingPool * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external override onlyLendingPool { if (amount == 0) { return; } address treasury = _treasury; // Compared to the normal mint, we don't check for rounding errors. // The amount to mint can easily be very small since it is a fraction of the interest ccrued. // In that case, the treasury will experience a (very small) loss, but it // wont cause potentially valid transactions to fail. _mint(treasury, amount.rayDiv(index)); emit Transfer(address(0), treasury, amount); emit Mint(treasury, amount, index); } /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * - Only callable by the LendingPool * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external override onlyLendingPool { // Being a normal transfer, the Transfer() and BalanceTransfer() are emitted // so no need to emit a specific event here _transfer(from, to, value, false); emit Transfer(from, to, value); } /** * @dev Calculates the balance of the user: principal balance + interest generated by the principal * @param user The user whose balance is calculated * @return The balance of the user **/ function balanceOf(address user) public view override(IncentivizedERC20, IERC20) returns (uint256) { return super.balanceOf(user).rayMul(_pool.getReserveNormalizedIncome(_underlyingAsset)); } /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { return (super.balanceOf(user), super.totalSupply()); } /** * @dev calculates the total supply of the specific aToken * since the balance of every single user increases over time, the total supply * does that too. * @return the current total supply **/ function totalSupply() public view override(IncentivizedERC20, IERC20) returns (uint256) { uint256 currentSupplyScaled = super.totalSupply(); if (currentSupplyScaled == 0) { return 0; } return currentSupplyScaled.rayMul(_pool.getReserveNormalizedIncome(_underlyingAsset)); } /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return the scaled total supply **/ function scaledTotalSupply() public view virtual override returns (uint256) { return super.totalSupply(); } /** * @dev Returns the address of the Aave treasury, receiving the fees on this aToken **/ function RESERVE_TREASURY_ADDRESS() public view returns (address) { return _treasury; } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } /** * @dev For internal usage in the logic of the parent contract IncentivizedERC20 **/ function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param target The recipient of the aTokens * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address target, uint256 amount) external override onlyLendingPool returns (uint256) { IERC20(_underlyingAsset).safeTransfer(target, amount); return amount; } /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external override onlyLendingPool {} /** * @dev implements the permit function as for * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md * @param owner The owner of the funds * @param spender The spender * @param value The amount * @param deadline The deadline timestamp, type(uint256).max for max deadline * @param v Signature param * @param s Signature param * @param r Signature param */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(owner != address(0), 'INVALID_OWNER'); //solium-disable-next-line require(block.timestamp <= deadline, 'INVALID_EXPIRATION'); uint256 currentValidNonce = _nonces[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require(owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE'); _nonces[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } /** * @dev Transfers the aTokens between two users. Validates the transfer * (ie checks for valid HF after the transfer) if required * @param from The source address * @param to The destination address * @param amount The amount getting transferred * @param validate `true` if the transfer needs to be validated **/ function _transfer( address from, address to, uint256 amount, bool validate ) internal { address underlyingAsset = _underlyingAsset; ILendingPool pool = _pool; uint256 index = pool.getReserveNormalizedIncome(underlyingAsset); uint256 fromBalanceBefore = super.balanceOf(from).rayMul(index); uint256 toBalanceBefore = super.balanceOf(to).rayMul(index); super._transfer(from, to, amount.rayDiv(index)); if (validate) { pool.finalizeTransfer(underlyingAsset, from, to, amount, fromBalanceBefore, toBalanceBefore); } emit BalanceTransfer(from, to, amount, index); } /** * @dev Overrides the parent _transfer to force validated transfer() and transferFrom() * @param from The source address * @param to The destination address * @param amount The amount getting transferred **/ function _transfer( address from, address to, uint256 amount ) internal override { _transfer(from, to, amount, true); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IDelegationToken} from '../../interfaces/IDelegationToken.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {AToken} from './AToken.sol'; /** * @title Aave AToken enabled to delegate voting power of the underlying asset to a different address * @dev The underlying asset needs to be compatible with the COMP delegation interface * @author Aave */ contract DelegationAwareAToken is AToken { modifier onlyPoolAdmin { require( _msgSender() == ILendingPool(_pool).getAddressesProvider().getPoolAdmin(), Errors.CALLER_NOT_POOL_ADMIN ); _; } /** * @dev Delegates voting power of the underlying asset to a `delegatee` address * @param delegatee The address that will receive the delegation **/ function delegateUnderlyingTo(address delegatee) external onlyPoolAdmin { IDelegationToken(_underlyingAsset).delegate(delegatee); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IDelegationToken * @dev Implements an interface for tokens with delegation COMP/UNI compatible * @author Aave **/ interface IDelegationToken { function delegate(address delegatee) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; import { ILendingPoolAddressesProviderRegistry } from '../../interfaces/ILendingPoolAddressesProviderRegistry.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title LendingPoolAddressesProviderRegistry contract * @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets * - Used for indexing purposes of Aave protocol's markets * - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with, * for example with `0` for the Aave main market and `1` for the next created * @author Aave **/ contract LendingPoolAddressesProviderRegistry is Ownable, ILendingPoolAddressesProviderRegistry { mapping(address => uint256) private _addressesProviders; address[] private _addressesProvidersList; /** * @dev Returns the list of registered addresses provider * @return The list of addresses provider, potentially containing address(0) elements **/ function getAddressesProvidersList() external view override returns (address[] memory) { address[] memory addressesProvidersList = _addressesProvidersList; uint256 maxLength = addressesProvidersList.length; address[] memory activeProviders = new address[](maxLength); for (uint256 i = 0; i < maxLength; i++) { if (_addressesProviders[addressesProvidersList[i]] > 0) { activeProviders[i] = addressesProvidersList[i]; } } return activeProviders; } /** * @dev Registers an addresses provider * @param provider The address of the new LendingPoolAddressesProvider * @param id The id for the new LendingPoolAddressesProvider, referring to the market it belongs to **/ function registerAddressesProvider(address provider, uint256 id) external override onlyOwner { require(id != 0, Errors.LPAPR_INVALID_ADDRESSES_PROVIDER_ID); _addressesProviders[provider] = id; _addToAddressesProvidersList(provider); emit AddressesProviderRegistered(provider); } /** * @dev Removes a LendingPoolAddressesProvider from the list of registered addresses provider * @param provider The LendingPoolAddressesProvider address **/ function unregisterAddressesProvider(address provider) external override onlyOwner { require(_addressesProviders[provider] > 0, Errors.LPAPR_PROVIDER_NOT_REGISTERED); _addressesProviders[provider] = 0; emit AddressesProviderUnregistered(provider); } /** * @dev Returns the id on a registered LendingPoolAddressesProvider * @return The id or 0 if the LendingPoolAddressesProvider is not registered */ function getAddressesProviderIdByAddress(address addressesProvider) external view override returns (uint256) { return _addressesProviders[addressesProvider]; } function _addToAddressesProvidersList(address provider) internal { uint256 providersCount = _addressesProvidersList.length; for (uint256 i = 0; i < providersCount; i++) { if (_addressesProvidersList[i] == provider) { return; } } _addressesProvidersList.push(provider); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title LendingPoolAddressesProviderRegistry contract * @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets * - Used for indexing purposes of Aave protocol's markets * - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with, * for example with `0` for the Aave main market and `1` for the next created * @author Aave **/ interface ILendingPoolAddressesProviderRegistry { event AddressesProviderRegistered(address indexed newAddress); event AddressesProviderUnregistered(address indexed newAddress); function getAddressesProvidersList() external view returns (address[] memory); function getAddressesProviderIdByAddress(address addressesProvider) external view returns (uint256); function registerAddressesProvider(address provider, uint256 id) external; function unregisterAddressesProvider(address provider) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IChainlinkAggregator} from '../interfaces/IChainlinkAggregator.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; /// @title AaveOracle /// @author Aave /// @notice Proxy smart contract to get the price of an asset from a price source, with Chainlink Aggregator /// smart contracts as primary option /// - If the returned price by a Chainlink aggregator is <= 0, the call is forwarded to a fallbackOracle /// - Owned by the Aave governance system, allowed to add sources for assets, replace them /// and change the fallbackOracle contract AaveOracle is IPriceOracleGetter, Ownable { using SafeERC20 for IERC20; event WethSet(address indexed weth); event AssetSourceUpdated(address indexed asset, address indexed source); event FallbackOracleUpdated(address indexed fallbackOracle); mapping(address => IChainlinkAggregator) private assetsSources; IPriceOracleGetter private _fallbackOracle; address public immutable WETH; /// @notice Constructor /// @param assets The addresses of the assets /// @param sources The address of the source of each asset /// @param fallbackOracle The address of the fallback oracle to use if the data of an /// aggregator is not consistent constructor( address[] memory assets, address[] memory sources, address fallbackOracle, address weth ) public { _setFallbackOracle(fallbackOracle); _setAssetsSources(assets, sources); WETH = weth; emit WethSet(weth); } /// @notice External function called by the Aave governance to set or replace sources of assets /// @param assets The addresses of the assets /// @param sources The address of the source of each asset function setAssetSources(address[] calldata assets, address[] calldata sources) external onlyOwner { _setAssetsSources(assets, sources); } /// @notice Sets the fallbackOracle /// - Callable only by the Aave governance /// @param fallbackOracle The address of the fallbackOracle function setFallbackOracle(address fallbackOracle) external onlyOwner { _setFallbackOracle(fallbackOracle); } /// @notice Internal function to set the sources for each asset /// @param assets The addresses of the assets /// @param sources The address of the source of each asset function _setAssetsSources(address[] memory assets, address[] memory sources) internal { require(assets.length == sources.length, 'INCONSISTENT_PARAMS_LENGTH'); for (uint256 i = 0; i < assets.length; i++) { assetsSources[assets[i]] = IChainlinkAggregator(sources[i]); emit AssetSourceUpdated(assets[i], sources[i]); } } /// @notice Internal function to set the fallbackOracle /// @param fallbackOracle The address of the fallbackOracle function _setFallbackOracle(address fallbackOracle) internal { _fallbackOracle = IPriceOracleGetter(fallbackOracle); emit FallbackOracleUpdated(fallbackOracle); } /// @notice Gets an asset price by address /// @param asset The asset address function getAssetPrice(address asset) public view override returns (uint256) { IChainlinkAggregator source = assetsSources[asset]; if (asset == WETH) { return 1 ether; } else if (address(source) == address(0)) { return _fallbackOracle.getAssetPrice(asset); } else { int256 price = IChainlinkAggregator(source).latestAnswer(); if (price > 0) { return uint256(price); } else { return _fallbackOracle.getAssetPrice(asset); } } } /// @notice Gets a list of prices from a list of assets addresses /// @param assets The list of assets addresses function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory) { uint256[] memory prices = new uint256[](assets.length); for (uint256 i = 0; i < assets.length; i++) { prices[i] = getAssetPrice(assets[i]); } return prices; } /// @notice Gets the address of the source for an asset address /// @param asset The address of the asset /// @return address The address of the source function getSourceOfAsset(address asset) external view returns (address) { return address(assetsSources[asset]); } /// @notice Gets the address of the fallback oracle /// @return address The addres of the fallback oracle function getFallbackOracle() external view returns (address) { return address(_fallbackOracle); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IChainlinkAggregator { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); event NewRound(uint256 indexed roundId, address indexed startedBy); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import { InitializableImmutableAdminUpgradeabilityProxy } from '../libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {IInitializableDebtToken} from '../../interfaces/IInitializableDebtToken.sol'; import {IInitializableAToken} from '../../interfaces/IInitializableAToken.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; import {ILendingPoolConfigurator} from '../../interfaces/ILendingPoolConfigurator.sol'; /** * @title LendingPoolConfigurator contract * @author Aave * @dev Implements the configuration methods for the Aave protocol **/ contract LendingPoolConfigurator is VersionedInitializable, ILendingPoolConfigurator { using SafeMath for uint256; using PercentageMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; ILendingPoolAddressesProvider internal addressesProvider; ILendingPool internal pool; modifier onlyPoolAdmin { require(addressesProvider.getPoolAdmin() == msg.sender, Errors.CALLER_NOT_POOL_ADMIN); _; } modifier onlyEmergencyAdmin { require( addressesProvider.getEmergencyAdmin() == msg.sender, Errors.LPC_CALLER_NOT_EMERGENCY_ADMIN ); _; } uint256 internal constant CONFIGURATOR_REVISION = 0x1; function getRevision() internal pure override returns (uint256) { return CONFIGURATOR_REVISION; } function initialize(ILendingPoolAddressesProvider provider) public initializer { addressesProvider = provider; pool = ILendingPool(addressesProvider.getLendingPool()); } /** * @dev Initializes reserves in batch **/ function batchInitReserve(InitReserveInput[] calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; for (uint256 i = 0; i < input.length; i++) { _initReserve(cachedPool, input[i]); } } function _initReserve(ILendingPool pool, InitReserveInput calldata input) internal { address aTokenProxyAddress = _initTokenWithProxy( input.aTokenImpl, abi.encodeWithSelector( IInitializableAToken.initialize.selector, pool, input.treasury, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.aTokenName, input.aTokenSymbol, input.params ) ); address stableDebtTokenProxyAddress = _initTokenWithProxy( input.stableDebtTokenImpl, abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, pool, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.stableDebtTokenName, input.stableDebtTokenSymbol, input.params ) ); address variableDebtTokenProxyAddress = _initTokenWithProxy( input.variableDebtTokenImpl, abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, pool, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.variableDebtTokenName, input.variableDebtTokenSymbol, input.params ) ); pool.initReserve( input.underlyingAsset, aTokenProxyAddress, stableDebtTokenProxyAddress, variableDebtTokenProxyAddress, input.interestRateStrategyAddress ); DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(input.underlyingAsset); currentConfig.setDecimals(input.underlyingAssetDecimals); currentConfig.setActive(true); currentConfig.setFrozen(false); pool.setConfiguration(input.underlyingAsset, currentConfig.data); emit ReserveInitialized( input.underlyingAsset, aTokenProxyAddress, stableDebtTokenProxyAddress, variableDebtTokenProxyAddress, input.interestRateStrategyAddress ); } /** * @dev Updates the aToken implementation for the reserve **/ function updateAToken(UpdateATokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableAToken.initialize.selector, cachedPool, input.treasury, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.aTokenAddress, input.implementation, encodedCall ); emit ATokenUpgraded(input.asset, reserveData.aTokenAddress, input.implementation); } /** * @dev Updates the stable debt token implementation for the reserve **/ function updateStableDebtToken(UpdateDebtTokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, cachedPool, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.stableDebtTokenAddress, input.implementation, encodedCall ); emit StableDebtTokenUpgraded( input.asset, reserveData.stableDebtTokenAddress, input.implementation ); } /** * @dev Updates the variable debt token implementation for the asset **/ function updateVariableDebtToken(UpdateDebtTokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, cachedPool, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.variableDebtTokenAddress, input.implementation, encodedCall ); emit VariableDebtTokenUpgraded( input.asset, reserveData.variableDebtTokenAddress, input.implementation ); } /** * @dev Enables borrowing on a reserve * @param asset The address of the underlying asset of the reserve * @param stableBorrowRateEnabled True if stable borrow rate needs to be enabled by default on this reserve **/ function enableBorrowingOnReserve(address asset, bool stableBorrowRateEnabled) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setBorrowingEnabled(true); currentConfig.setStableRateBorrowingEnabled(stableBorrowRateEnabled); pool.setConfiguration(asset, currentConfig.data); emit BorrowingEnabledOnReserve(asset, stableBorrowRateEnabled); } /** * @dev Disables borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function disableBorrowingOnReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setBorrowingEnabled(false); pool.setConfiguration(asset, currentConfig.data); emit BorrowingDisabledOnReserve(asset); } /** * @dev Configures the reserve collateralization parameters * all the values are expressed in percentages with two decimals of precision. A valid value is 10000, which means 100.00% * @param asset The address of the underlying asset of the reserve * @param ltv The loan to value of the asset when used as collateral * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus The bonus liquidators receive to liquidate this asset. The values is always above 100%. A value of 105% * means the liquidator will receive a 5% bonus **/ function configureReserveAsCollateral( address asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); //validation of the parameters: the LTV can //only be lower or equal than the liquidation threshold //(otherwise a loan against the asset would cause instantaneous liquidation) require(ltv <= liquidationThreshold, Errors.LPC_INVALID_CONFIGURATION); if (liquidationThreshold != 0) { //liquidation bonus must be bigger than 100.00%, otherwise the liquidator would receive less //collateral than needed to cover the debt require( liquidationBonus > PercentageMath.PERCENTAGE_FACTOR, Errors.LPC_INVALID_CONFIGURATION ); //if threshold * bonus is less than PERCENTAGE_FACTOR, it's guaranteed that at the moment //a loan is taken there is enough collateral available to cover the liquidation bonus require( liquidationThreshold.percentMul(liquidationBonus) <= PercentageMath.PERCENTAGE_FACTOR, Errors.LPC_INVALID_CONFIGURATION ); } else { require(liquidationBonus == 0, Errors.LPC_INVALID_CONFIGURATION); //if the liquidation threshold is being set to 0, // the reserve is being disabled as collateral. To do so, //we need to ensure no liquidity is deposited _checkNoLiquidity(asset); } currentConfig.setLtv(ltv); currentConfig.setLiquidationThreshold(liquidationThreshold); currentConfig.setLiquidationBonus(liquidationBonus); pool.setConfiguration(asset, currentConfig.data); emit CollateralConfigurationChanged(asset, ltv, liquidationThreshold, liquidationBonus); } /** * @dev Enable stable rate borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function enableReserveStableRate(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setStableRateBorrowingEnabled(true); pool.setConfiguration(asset, currentConfig.data); emit StableRateEnabledOnReserve(asset); } /** * @dev Disable stable rate borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function disableReserveStableRate(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setStableRateBorrowingEnabled(false); pool.setConfiguration(asset, currentConfig.data); emit StableRateDisabledOnReserve(asset); } /** * @dev Activates a reserve * @param asset The address of the underlying asset of the reserve **/ function activateReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setActive(true); pool.setConfiguration(asset, currentConfig.data); emit ReserveActivated(asset); } /** * @dev Deactivates a reserve * @param asset The address of the underlying asset of the reserve **/ function deactivateReserve(address asset) external onlyPoolAdmin { _checkNoLiquidity(asset); DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setActive(false); pool.setConfiguration(asset, currentConfig.data); emit ReserveDeactivated(asset); } /** * @dev Freezes a reserve. A frozen reserve doesn't allow any new deposit, borrow or rate swap * but allows repayments, liquidations, rate rebalances and withdrawals * @param asset The address of the underlying asset of the reserve **/ function freezeReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setFrozen(true); pool.setConfiguration(asset, currentConfig.data); emit ReserveFrozen(asset); } /** * @dev Unfreezes a reserve * @param asset The address of the underlying asset of the reserve **/ function unfreezeReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setFrozen(false); pool.setConfiguration(asset, currentConfig.data); emit ReserveUnfrozen(asset); } /** * @dev Updates the reserve factor of a reserve * @param asset The address of the underlying asset of the reserve * @param reserveFactor The new reserve factor of the reserve **/ function setReserveFactor(address asset, uint256 reserveFactor) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setReserveFactor(reserveFactor); pool.setConfiguration(asset, currentConfig.data); emit ReserveFactorChanged(asset, reserveFactor); } /** * @dev Sets the interest rate strategy of a reserve * @param asset The address of the underlying asset of the reserve * @param rateStrategyAddress The new address of the interest strategy contract **/ function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) external onlyPoolAdmin { pool.setReserveInterestRateStrategyAddress(asset, rateStrategyAddress); emit ReserveInterestRateStrategyChanged(asset, rateStrategyAddress); } /** * @dev pauses or unpauses all the actions of the protocol, including aToken transfers * @param val true if protocol needs to be paused, false otherwise **/ function setPoolPause(bool val) external onlyEmergencyAdmin { pool.setPause(val); } function _initTokenWithProxy(address implementation, bytes memory initParams) internal returns (address) { InitializableImmutableAdminUpgradeabilityProxy proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this)); proxy.initialize(implementation, initParams); return address(proxy); } function _upgradeTokenImplementation( address proxyAddress, address implementation, bytes memory initParams ) internal { InitializableImmutableAdminUpgradeabilityProxy proxy = InitializableImmutableAdminUpgradeabilityProxy(payable(proxyAddress)); proxy.upgradeToAndCall(implementation, initParams); } function _checkNoLiquidity(address asset) internal view { DataTypes.ReserveData memory reserveData = pool.getReserveData(asset); uint256 availableLiquidity = IERC20Detailed(asset).balanceOf(reserveData.aTokenAddress); require( availableLiquidity == 0 && reserveData.currentLiquidityRate == 0, Errors.LPC_RESERVE_LIQUIDITY_NOT_0 ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseImmutableAdminUpgradeabilityProxy.sol'; import '../../../dependencies/openzeppelin/upgradeability/InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends BaseAdminUpgradeabilityProxy with an initializer function */ contract InitializableImmutableAdminUpgradeabilityProxy is BaseImmutableAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { constructor(address admin) public BaseImmutableAdminUpgradeabilityProxy(admin) {} /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseImmutableAdminUpgradeabilityProxy, Proxy) { BaseImmutableAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ILendingPoolConfigurator { struct InitReserveInput { address aTokenImpl; address stableDebtTokenImpl; address variableDebtTokenImpl; uint8 underlyingAssetDecimals; address interestRateStrategyAddress; address underlyingAsset; address treasury; address incentivesController; string underlyingAssetName; string aTokenName; string aTokenSymbol; string variableDebtTokenName; string variableDebtTokenSymbol; string stableDebtTokenName; string stableDebtTokenSymbol; bytes params; } struct UpdateATokenInput { address asset; address treasury; address incentivesController; string name; string symbol; address implementation; bytes params; } struct UpdateDebtTokenInput { address asset; address incentivesController; string name; string symbol; address implementation; bytes params; } /** * @dev Emitted when a reserve is initialized. * @param asset The address of the underlying asset of the reserve * @param aToken The address of the associated aToken contract * @param stableDebtToken The address of the associated stable rate debt token * @param variableDebtToken The address of the associated variable rate debt token * @param interestRateStrategyAddress The address of the interest rate strategy for the reserve **/ event ReserveInitialized( address indexed asset, address indexed aToken, address stableDebtToken, address variableDebtToken, address interestRateStrategyAddress ); /** * @dev Emitted when borrowing is enabled on a reserve * @param asset The address of the underlying asset of the reserve * @param stableRateEnabled True if stable rate borrowing is enabled, false otherwise **/ event BorrowingEnabledOnReserve(address indexed asset, bool stableRateEnabled); /** * @dev Emitted when borrowing is disabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event BorrowingDisabledOnReserve(address indexed asset); /** * @dev Emitted when the collateralization risk parameters for the specified asset are updated. * @param asset The address of the underlying asset of the reserve * @param ltv The loan to value of the asset when used as collateral * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus The bonus liquidators receive to liquidate this asset **/ event CollateralConfigurationChanged( address indexed asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ); /** * @dev Emitted when stable rate borrowing is enabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event StableRateEnabledOnReserve(address indexed asset); /** * @dev Emitted when stable rate borrowing is disabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event StableRateDisabledOnReserve(address indexed asset); /** * @dev Emitted when a reserve is activated * @param asset The address of the underlying asset of the reserve **/ event ReserveActivated(address indexed asset); /** * @dev Emitted when a reserve is deactivated * @param asset The address of the underlying asset of the reserve **/ event ReserveDeactivated(address indexed asset); /** * @dev Emitted when a reserve is frozen * @param asset The address of the underlying asset of the reserve **/ event ReserveFrozen(address indexed asset); /** * @dev Emitted when a reserve is unfrozen * @param asset The address of the underlying asset of the reserve **/ event ReserveUnfrozen(address indexed asset); /** * @dev Emitted when a reserve factor is updated * @param asset The address of the underlying asset of the reserve * @param factor The new reserve factor **/ event ReserveFactorChanged(address indexed asset, uint256 factor); /** * @dev Emitted when the reserve decimals are updated * @param asset The address of the underlying asset of the reserve * @param decimals The new decimals **/ event ReserveDecimalsChanged(address indexed asset, uint256 decimals); /** * @dev Emitted when a reserve interest strategy contract is updated * @param asset The address of the underlying asset of the reserve * @param strategy The new address of the interest strategy contract **/ event ReserveInterestRateStrategyChanged(address indexed asset, address strategy); /** * @dev Emitted when an aToken implementation is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The aToken proxy address * @param implementation The new aToken implementation **/ event ATokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); /** * @dev Emitted when the implementation of a stable debt token is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The stable debt token proxy address * @param implementation The new aToken implementation **/ event StableDebtTokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); /** * @dev Emitted when the implementation of a variable debt token is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The variable debt token proxy address * @param implementation The new aToken implementation **/ event VariableDebtTokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import '../../../dependencies/openzeppelin/upgradeability/BaseUpgradeabilityProxy.sol'; /** * @title BaseImmutableAdminUpgradeabilityProxy * @author Aave, inspired by the OpenZeppelin upgradeability proxy pattern * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. The admin role is stored in an immutable, which * helps saving transactions costs * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseImmutableAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { address immutable ADMIN; constructor(address admin) public { ADMIN = admin; } modifier ifAdmin() { if (msg.sender == ADMIN) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return ADMIN; } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); (bool success, ) = newImplementation.delegatecall(data); require(success); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal virtual override { require(msg.sender != ADMIN, 'Cannot call fallback function from the proxy admin'); super._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseUpgradeabilityProxy.sol'; /** * @title InitializableUpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './Proxy.sol'; import '../contracts/Address.sol'; /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal view override returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; //solium-disable-next-line assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require( Address.isContract(newImplementation), 'Cannot set a proxy implementation to a non-contract address' ); bytes32 slot = IMPLEMENTATION_SLOT; //solium-disable-next-line assembly { sstore(slot, newImplementation) } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.0; /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { //solium-disable-next-line assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {DebtTokenBase} from './base/DebtTokenBase.sol'; import {MathUtils} from '../libraries/math/MathUtils.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title StableDebtToken * @notice Implements a stable debt token to track the borrowing positions of users * at stable rate mode * @author Aave **/ contract StableDebtToken is IStableDebtToken, DebtTokenBase { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; uint256 internal _avgStableRate; mapping(address => uint40) internal _timestamps; mapping(address => uint256) internal _usersStableRate; uint40 internal _totalSupplyTimestamp; ILendingPool internal _pool; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) public override initializer { _setName(debtTokenName); _setSymbol(debtTokenSymbol); _setDecimals(debtTokenDecimals); _pool = pool; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), address(incentivesController), debtTokenDecimals, debtTokenName, debtTokenSymbol, params ); } /** * @dev Gets the revision of the stable debt token implementation * @return The debt token implementation revision **/ function getRevision() internal pure virtual override returns (uint256) { return DEBT_TOKEN_REVISION; } /** * @dev Returns the average stable rate across all the stable rate debt * @return the average stable rate **/ function getAverageStableRate() external view virtual override returns (uint256) { return _avgStableRate; } /** * @dev Returns the timestamp of the last user action * @return The last update timestamp **/ function getUserLastUpdated(address user) external view virtual override returns (uint40) { return _timestamps[user]; } /** * @dev Returns the stable rate of the user * @param user The address of the user * @return The stable rate of user **/ function getUserStableRate(address user) external view virtual override returns (uint256) { return _usersStableRate[user]; } /** * @dev Calculates the current user debt balance * @return The accumulated debt of the user **/ function balanceOf(address account) public view virtual override returns (uint256) { uint256 accountBalance = super.balanceOf(account); uint256 stableRate = _usersStableRate[account]; if (accountBalance == 0) { return 0; } uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest(stableRate, _timestamps[account]); return accountBalance.rayMul(cumulatedInterest); } struct MintLocalVars { uint256 previousSupply; uint256 nextSupply; uint256 amountInRay; uint256 newStableRate; uint256 currentAvgStableRate; } /** * @dev Mints debt token to the `onBehalfOf` address. * - Only callable by the LendingPool * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt tokens to mint * @param rate The rate of the debt being minted **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 rate ) external override onlyLendingPool returns (bool) { MintLocalVars memory vars; if (user != onBehalfOf) { _decreaseBorrowAllowance(onBehalfOf, user, amount); } (, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(onBehalfOf); vars.previousSupply = totalSupply(); vars.currentAvgStableRate = _avgStableRate; vars.nextSupply = _totalSupply = vars.previousSupply.add(amount); vars.amountInRay = amount.wadToRay(); vars.newStableRate = _usersStableRate[onBehalfOf] .rayMul(currentBalance.wadToRay()) .add(vars.amountInRay.rayMul(rate)) .rayDiv(currentBalance.add(amount).wadToRay()); require(vars.newStableRate <= type(uint128).max, Errors.SDT_STABLE_DEBT_OVERFLOW); _usersStableRate[onBehalfOf] = vars.newStableRate; //solium-disable-next-line _totalSupplyTimestamp = _timestamps[onBehalfOf] = uint40(block.timestamp); // Calculates the updated average stable rate vars.currentAvgStableRate = _avgStableRate = vars .currentAvgStableRate .rayMul(vars.previousSupply.wadToRay()) .add(rate.rayMul(vars.amountInRay)) .rayDiv(vars.nextSupply.wadToRay()); _mint(onBehalfOf, amount.add(balanceIncrease), vars.previousSupply); emit Transfer(address(0), onBehalfOf, amount); emit Mint( user, onBehalfOf, amount, currentBalance, balanceIncrease, vars.newStableRate, vars.currentAvgStableRate, vars.nextSupply ); return currentBalance == 0; } /** * @dev Burns debt of `user` * @param user The address of the user getting his debt burned * @param amount The amount of debt tokens getting burned **/ function burn(address user, uint256 amount) external override onlyLendingPool { (, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(user); uint256 previousSupply = totalSupply(); uint256 newAvgStableRate = 0; uint256 nextSupply = 0; uint256 userStableRate = _usersStableRate[user]; // Since the total supply and each single user debt accrue separately, // there might be accumulation errors so that the last borrower repaying // mght actually try to repay more than the available debt supply. // In this case we simply set the total supply and the avg stable rate to 0 if (previousSupply <= amount) { _avgStableRate = 0; _totalSupply = 0; } else { nextSupply = _totalSupply = previousSupply.sub(amount); uint256 firstTerm = _avgStableRate.rayMul(previousSupply.wadToRay()); uint256 secondTerm = userStableRate.rayMul(amount.wadToRay()); // For the same reason described above, when the last user is repaying it might // happen that user rate * user balance > avg rate * total supply. In that case, // we simply set the avg rate to 0 if (secondTerm >= firstTerm) { newAvgStableRate = _avgStableRate = _totalSupply = 0; } else { newAvgStableRate = _avgStableRate = firstTerm.sub(secondTerm).rayDiv(nextSupply.wadToRay()); } } if (amount == currentBalance) { _usersStableRate[user] = 0; _timestamps[user] = 0; } else { //solium-disable-next-line _timestamps[user] = uint40(block.timestamp); } //solium-disable-next-line _totalSupplyTimestamp = uint40(block.timestamp); if (balanceIncrease > amount) { uint256 amountToMint = balanceIncrease.sub(amount); _mint(user, amountToMint, previousSupply); emit Mint( user, user, amountToMint, currentBalance, balanceIncrease, userStableRate, newAvgStableRate, nextSupply ); } else { uint256 amountToBurn = amount.sub(balanceIncrease); _burn(user, amountToBurn, previousSupply); emit Burn(user, amountToBurn, currentBalance, balanceIncrease, newAvgStableRate, nextSupply); } emit Transfer(user, address(0), amount); } /** * @dev Calculates the increase in balance since the last user interaction * @param user The address of the user for which the interest is being accumulated * @return The previous principal balance, the new principal balance and the balance increase **/ function _calculateBalanceIncrease(address user) internal view returns ( uint256, uint256, uint256 ) { uint256 previousPrincipalBalance = super.balanceOf(user); if (previousPrincipalBalance == 0) { return (0, 0, 0); } // Calculation of the accrued interest since the last accumulation uint256 balanceIncrease = balanceOf(user).sub(previousPrincipalBalance); return ( previousPrincipalBalance, previousPrincipalBalance.add(balanceIncrease), balanceIncrease ); } /** * @dev Returns the principal and total supply, the average borrow rate and the last supply update timestamp **/ function getSupplyData() public view override returns ( uint256, uint256, uint256, uint40 ) { uint256 avgRate = _avgStableRate; return (super.totalSupply(), _calcTotalSupply(avgRate), avgRate, _totalSupplyTimestamp); } /** * @dev Returns the the total supply and the average stable rate **/ function getTotalSupplyAndAvgRate() public view override returns (uint256, uint256) { uint256 avgRate = _avgStableRate; return (_calcTotalSupply(avgRate), avgRate); } /** * @dev Returns the total supply **/ function totalSupply() public view override returns (uint256) { return _calcTotalSupply(_avgStableRate); } /** * @dev Returns the timestamp at which the total supply was updated **/ function getTotalSupplyLastUpdated() public view override returns (uint40) { return _totalSupplyTimestamp; } /** * @dev Returns the principal debt balance of the user from * @param user The user's address * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external view virtual override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev For internal usage in the logic of the parent contracts **/ function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } /** * @dev For internal usage in the logic of the parent contracts **/ function _getUnderlyingAssetAddress() internal view override returns (address) { return _underlyingAsset; } /** * @dev For internal usage in the logic of the parent contracts **/ function _getLendingPool() internal view override returns (ILendingPool) { return _pool; } /** * @dev Calculates the total supply * @param avgRate The average rate at which the total supply increases * @return The debt balance of the user since the last burn/mint action **/ function _calcTotalSupply(uint256 avgRate) internal view virtual returns (uint256) { uint256 principalSupply = super.totalSupply(); if (principalSupply == 0) { return 0; } uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest(avgRate, _totalSupplyTimestamp); return principalSupply.rayMul(cumulatedInterest); } /** * @dev Mints stable debt tokens to an user * @param account The account receiving the debt tokens * @param amount The amount being minted * @param oldTotalSupply the total supply before the minting event **/ function _mint( address account, uint256 amount, uint256 oldTotalSupply ) internal { uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.add(amount); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } /** * @dev Burns stable debt tokens of an user * @param account The user getting his debt burned * @param amount The amount being burned * @param oldTotalSupply The total supply before the burning event **/ function _burn( address account, uint256 amount, uint256 oldTotalSupply ) internal { uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, Errors.SDT_BURN_EXCEEDS_BALANCE); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {StableDebtToken} from '../../protocol/tokenization/StableDebtToken.sol'; contract MockStableDebtToken is StableDebtToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Address} from '../../dependencies/openzeppelin/contracts/Address.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {IFlashLoanReceiver} from '../../flashloan/interfaces/IFlashLoanReceiver.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {Helpers} from '../libraries/helpers/Helpers.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; import {GenericLogic} from '../libraries/logic/GenericLogic.sol'; import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {LendingPoolStorage} from './LendingPoolStorage.sol'; /** * @title LendingPool contract * @dev Main point of interaction with an Aave protocol's market * - Users can: * # Deposit * # Withdraw * # Borrow * # Repay * # Swap their loans between variable and stable rate * # Enable/disable their deposits as collateral rebalance stable rate borrow positions * # Liquidate positions * # Execute Flash Loans * - To be covered by a proxy contract, owned by the LendingPoolAddressesProvider of the specific market * - All admin functions are callable by the LendingPoolConfigurator contract defined also in the * LendingPoolAddressesProvider * @author Aave **/ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage { using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; uint256 public constant LENDINGPOOL_REVISION = 0x2; modifier whenNotPaused() { _whenNotPaused(); _; } modifier onlyLendingPoolConfigurator() { _onlyLendingPoolConfigurator(); _; } function _whenNotPaused() internal view { require(!_paused, Errors.LP_IS_PAUSED); } function _onlyLendingPoolConfigurator() internal view { require( _addressesProvider.getLendingPoolConfigurator() == msg.sender, Errors.LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR ); } function getRevision() internal pure override returns (uint256) { return LENDINGPOOL_REVISION; } /** * @dev Function is invoked by the proxy contract when the LendingPool contract is added to the * LendingPoolAddressesProvider of the market. * - Caching the address of the LendingPoolAddressesProvider in order to reduce gas consumption * on subsequent operations * @param provider The address of the LendingPoolAddressesProvider **/ function initialize(ILendingPoolAddressesProvider provider) public initializer { _addressesProvider = provider; _maxStableRateBorrowSizePercent = 2500; _flashLoanPremiumTotal = 9; _maxNumberOfReserves = 128; } /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateDeposit(reserve, amount); address aToken = reserve.aTokenAddress; reserve.updateState(); reserve.updateInterestRates(asset, aToken, amount, 0); IERC20(asset).safeTransferFrom(msg.sender, aToken, amount); bool isFirstDeposit = IAToken(aToken).mint(onBehalfOf, amount, reserve.liquidityIndex); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit(asset, msg.sender, onBehalfOf, amount, referralCode); } /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; address aToken = reserve.aTokenAddress; uint256 userBalance = IAToken(aToken).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, aToken, 0, amountToWithdraw); if (amountToWithdraw == userBalance) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } IAToken(aToken).burn(msg.sender, to, amountToWithdraw, reserve.liquidityIndex); emit Withdraw(asset, msg.sender, to, amountToWithdraw); return amountToWithdraw; } /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; _executeBorrow( ExecuteBorrowParams( asset, msg.sender, onBehalfOf, amount, interestRateMode, reserve.aTokenAddress, referralCode, true ) ); } /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode); ValidationLogic.validateRepay( reserve, amount, interestRateMode, onBehalfOf, stableDebt, variableDebt ); uint256 paybackAmount = interestRateMode == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } reserve.updateState(); if (interestRateMode == DataTypes.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount); } else { IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); } address aToken = reserve.aTokenAddress; reserve.updateInterestRates(asset, aToken, paybackAmount, 0); if (stableDebt.add(variableDebt).sub(paybackAmount) == 0) { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } IERC20(asset).safeTransferFrom(msg.sender, aToken, paybackAmount); IAToken(aToken).handleRepayment(msg.sender, paybackAmount); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); return paybackAmount; } /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(msg.sender, reserve); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode); ValidationLogic.validateSwapRateMode( reserve, _usersConfig[msg.sender], stableDebt, variableDebt, interestRateMode ); reserve.updateState(); if (interestRateMode == DataTypes.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); IVariableDebtToken(reserve.variableDebtTokenAddress).mint( msg.sender, msg.sender, stableDebt, reserve.variableBorrowIndex ); } else { IVariableDebtToken(reserve.variableDebtTokenAddress).burn( msg.sender, variableDebt, reserve.variableBorrowIndex ); IStableDebtToken(reserve.stableDebtTokenAddress).mint( msg.sender, msg.sender, variableDebt, reserve.currentStableBorrowRate ); } reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); emit Swap(asset, msg.sender, rateMode); } /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; IERC20 stableDebtToken = IERC20(reserve.stableDebtTokenAddress); IERC20 variableDebtToken = IERC20(reserve.variableDebtTokenAddress); address aTokenAddress = reserve.aTokenAddress; uint256 stableDebt = IERC20(stableDebtToken).balanceOf(user); ValidationLogic.validateRebalanceStableBorrowRate( reserve, asset, stableDebtToken, variableDebtToken, aTokenAddress ); reserve.updateState(); IStableDebtToken(address(stableDebtToken)).burn(user, stableDebt); IStableDebtToken(address(stableDebtToken)).mint( user, user, stableDebt, reserve.currentStableBorrowRate ); reserve.updateInterestRates(asset, aTokenAddress, 0, 0); emit RebalanceStableBorrowRate(asset, user); } /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ 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); } else { emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } } /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external override whenNotPaused { address collateralManager = _addressesProvider.getLendingPoolCollateralManager(); //solium-disable-next-line (bool success, bytes memory result) = collateralManager.delegatecall( abi.encodeWithSignature( 'liquidationCall(address,address,address,uint256,bool)', collateralAsset, debtAsset, user, debtToCover, receiveAToken ) ); require(success, Errors.LP_LIQUIDATION_CALL_FAILED); (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string)); require(returnCode == 0, string(abi.encodePacked(returnMessage))); } struct FlashLoanLocalVars { IFlashLoanReceiver receiver; address oracle; uint256 i; address currentAsset; address currentATokenAddress; uint256 currentAmount; uint256 currentPremium; uint256 currentAmountPlusPremium; address debtToken; } /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external override whenNotPaused { FlashLoanLocalVars memory vars; ValidationLogic.validateFlashloan(assets, amounts); address[] memory aTokenAddresses = new address[](assets.length); uint256[] memory premiums = new uint256[](assets.length); vars.receiver = IFlashLoanReceiver(receiverAddress); for (vars.i = 0; vars.i < assets.length; vars.i++) { aTokenAddresses[vars.i] = _reserves[assets[vars.i]].aTokenAddress; premiums[vars.i] = amounts[vars.i].mul(_flashLoanPremiumTotal).div(10000); IAToken(aTokenAddresses[vars.i]).transferUnderlyingTo(receiverAddress, amounts[vars.i]); } require( vars.receiver.executeOperation(assets, amounts, premiums, msg.sender, params), Errors.LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN ); for (vars.i = 0; vars.i < assets.length; vars.i++) { vars.currentAsset = assets[vars.i]; vars.currentAmount = amounts[vars.i]; vars.currentPremium = premiums[vars.i]; vars.currentATokenAddress = aTokenAddresses[vars.i]; vars.currentAmountPlusPremium = vars.currentAmount.add(vars.currentPremium); if (DataTypes.InterestRateMode(modes[vars.i]) == DataTypes.InterestRateMode.NONE) { _reserves[vars.currentAsset].updateState(); _reserves[vars.currentAsset].cumulateToLiquidityIndex( IERC20(vars.currentATokenAddress).totalSupply(), vars.currentPremium ); _reserves[vars.currentAsset].updateInterestRates( vars.currentAsset, vars.currentATokenAddress, vars.currentAmountPlusPremium, 0 ); IERC20(vars.currentAsset).safeTransferFrom( receiverAddress, vars.currentATokenAddress, vars.currentAmountPlusPremium ); } else { // If the user chose to not return the funds, the system checks if there is enough collateral and // eventually opens a debt position _executeBorrow( ExecuteBorrowParams( vars.currentAsset, msg.sender, onBehalfOf, vars.currentAmount, modes[vars.i], vars.currentATokenAddress, referralCode, false ) ); } emit FlashLoan( receiverAddress, msg.sender, vars.currentAsset, vars.currentAmount, vars.currentPremium, referralCode ); } } /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view override returns (DataTypes.ReserveData memory) { return _reserves[asset]; } /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ 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 ); } /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view override returns (DataTypes.ReserveConfigurationMap memory) { return _reserves[asset].configuration; } /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view override returns (DataTypes.UserConfigurationMap memory) { return _usersConfig[user]; } /** * @dev Returns the normalized income per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view virtual override returns (uint256) { return _reserves[asset].getNormalizedIncome(); } /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view override returns (uint256) { return _reserves[asset].getNormalizedDebt(); } /** * @dev Returns if the LendingPool is paused */ function paused() external view override returns (bool) { return _paused; } /** * @dev Returns the list of the initialized reserves **/ 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; } /** * @dev Returns the cached LendingPoolAddressesProvider connected to this contract **/ function getAddressesProvider() external view override returns (ILendingPoolAddressesProvider) { return _addressesProvider; } /** * @dev Returns the percentage of available liquidity that can be borrowed at once at stable rate */ function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() public view returns (uint256) { return _maxStableRateBorrowSizePercent; } /** * @dev Returns the fee on flash loans */ function FLASHLOAN_PREMIUM_TOTAL() public view returns (uint256) { return _flashLoanPremiumTotal; } /** * @dev Returns the maximum number of reserves supported to be listed in this LendingPool */ function MAX_NUMBER_RESERVES() public view returns (uint256) { return _maxNumberOfReserves; } /** * @dev Validates and finalizes an aToken transfer * - Only callable by the overlying aToken of the `asset` * @param asset The address of the underlying asset of the aToken * @param from The user from which the aTokens are transferred * @param to The user receiving the aTokens * @param amount The amount being transferred/withdrawn * @param balanceFromBefore The aToken balance of the `from` user before the transfer * @param balanceToBefore The aToken balance of the `to` user before the transfer */ function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromBefore, uint256 balanceToBefore ) external override whenNotPaused { require(msg.sender == _reserves[asset].aTokenAddress, Errors.LP_CALLER_MUST_BE_AN_ATOKEN); 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); } } } /** * @dev Initializes a reserve, activating it, assigning an aToken and debt tokens and an * interest rate strategy * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param aTokenAddress The address of the aToken that will be assigned to the reserve * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve * @param aTokenAddress The address of the VariableDebtToken that will be assigned to the reserve * @param interestRateStrategyAddress The address of the interest rate strategy contract **/ function initReserve( address asset, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external override onlyLendingPoolConfigurator { require(Address.isContract(asset), Errors.LP_NOT_CONTRACT); _reserves[asset].init( aTokenAddress, stableDebtAddress, variableDebtAddress, interestRateStrategyAddress ); _addReserveToList(asset); } /** * @dev Updates the address of the interest rate strategy contract * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param rateStrategyAddress The address of the interest rate strategy contract **/ function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) external override onlyLendingPoolConfigurator { _reserves[asset].interestRateStrategyAddress = rateStrategyAddress; } /** * @dev Sets the configuration bitmap of the reserve as a whole * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param configuration The new configuration bitmap **/ function setConfiguration(address asset, uint256 configuration) external override onlyLendingPoolConfigurator { _reserves[asset].configuration.data = configuration; } /** * @dev Set the _pause state of a reserve * - Only callable by the LendingPoolConfigurator contract * @param val `true` to pause the reserve, `false` to un-pause it */ function setPause(bool val) external override onlyLendingPoolConfigurator { _paused = val; if (_paused) { emit Paused(); } else { emit Unpaused(); } } struct ExecuteBorrowParams { address asset; address user; address onBehalfOf; uint256 amount; uint256 interestRateMode; address aTokenAddress; uint16 referralCode; 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( vars.asset, reserve, vars.onBehalfOf, vars.amount, amountInETH, vars.interestRateMode, _maxStableRateBorrowSizePercent, _reserves, userConfig, _reservesList, _reservesCount, oracle ); reserve.updateState(); uint256 currentStableRate = 0; bool isFirstBorrowing = false; if (DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE) { currentStableRate = reserve.currentStableBorrowRate; isFirstBorrowing = IStableDebtToken(reserve.stableDebtTokenAddress).mint( vars.user, vars.onBehalfOf, vars.amount, currentStableRate ); } else { 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.aTokenAddress, 0, vars.releaseUnderlying ? vars.amount : 0 ); if (vars.releaseUnderlying) { IAToken(vars.aTokenAddress).transferUnderlyingTo(vars.user, vars.amount); } emit Borrow( vars.asset, vars.user, vars.onBehalfOf, vars.amount, vars.interestRateMode, DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE ? currentStableRate : reserve.currentVariableBorrowRate, vars.referralCode ); } function _addReserveToList(address asset) internal { uint256 reservesCount = _reservesCount; require(reservesCount < _maxNumberOfReserves, Errors.LP_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; } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; interface IExchangeAdapter { event Exchange( address indexed from, address indexed to, address indexed platform, uint256 fromAmount, uint256 toAmount ); function approveExchange(IERC20[] calldata tokens) external; function exchange( address from, address to, uint256 amount, uint256 maxSlippage ) external returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ERC20} from '../../dependencies/openzeppelin/contracts/ERC20.sol'; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract MintableDelegationERC20 is ERC20 { address public delegatee; constructor( string memory name, string memory symbol, uint8 decimals ) public ERC20(name, symbol) { _setupDecimals(decimals); } /** * @dev Function to mint tokensp * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(uint256 value) public returns (bool) { _mint(msg.sender, value); return true; } function delegate(address delegateeAddress) external { delegatee = delegateeAddress; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IUniswapV2Router02} from '../../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {MintableERC20} from '../tokens/MintableERC20.sol'; contract MockUniswapV2Router02 is IUniswapV2Router02 { mapping(address => uint256) internal _amountToReturn; mapping(address => uint256) internal _amountToSwap; mapping(address => mapping(address => mapping(uint256 => uint256))) internal _amountsIn; mapping(address => mapping(address => mapping(uint256 => uint256))) internal _amountsOut; uint256 internal defaultMockValue; function setAmountToReturn(address reserve, uint256 amount) public { _amountToReturn[reserve] = amount; } function setAmountToSwap(address reserve, uint256 amount) public { _amountToSwap[reserve] = amount; } function swapExactTokensForTokens( uint256 amountIn, uint256, /* amountOutMin */ address[] calldata path, address to, uint256 /* deadline */ ) external override returns (uint256[] memory amounts) { IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn); MintableERC20(path[1]).mint(_amountToReturn[path[0]]); IERC20(path[1]).transfer(to, _amountToReturn[path[0]]); amounts = new uint256[](path.length); amounts[0] = amountIn; amounts[1] = _amountToReturn[path[0]]; } function swapTokensForExactTokens( uint256 amountOut, uint256, /* amountInMax */ address[] calldata path, address to, uint256 /* deadline */ ) external override returns (uint256[] memory amounts) { IERC20(path[0]).transferFrom(msg.sender, address(this), _amountToSwap[path[0]]); MintableERC20(path[1]).mint(amountOut); IERC20(path[1]).transfer(to, amountOut); amounts = new uint256[](path.length); amounts[0] = _amountToSwap[path[0]]; amounts[1] = amountOut; } function setAmountOut( uint256 amountIn, address reserveIn, address reserveOut, uint256 amountOut ) public { _amountsOut[reserveIn][reserveOut][amountIn] = amountOut; } function setAmountIn( uint256 amountOut, address reserveIn, address reserveOut, uint256 amountIn ) public { _amountsIn[reserveIn][reserveOut][amountOut] = amountIn; } function setDefaultMockValue(uint256 value) public { defaultMockValue = value; } function getAmountsOut(uint256 amountIn, address[] calldata path) external view override returns (uint256[] memory) { uint256[] memory amounts = new uint256[](path.length); amounts[0] = amountIn; amounts[1] = _amountsOut[path[0]][path[1]][amountIn] > 0 ? _amountsOut[path[0]][path[1]][amountIn] : defaultMockValue; return amounts; } function getAmountsIn(uint256 amountOut, address[] calldata path) external view override returns (uint256[] memory) { uint256[] memory amounts = new uint256[](path.length); amounts[0] = _amountsIn[path[0]][path[1]][amountOut] > 0 ? _amountsIn[path[0]][path[1]][amountOut] : defaultMockValue; amounts[1] = amountOut; return amounts; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; /** * @title UniswapLiquiditySwapAdapter * @notice Uniswap V2 Adapter to swap liquidity. * @author Aave **/ contract UniswapLiquiditySwapAdapter is BaseUniswapAdapter { struct PermitParams { uint256[] amount; uint256[] deadline; uint8[] v; bytes32[] r; bytes32[] s; } struct SwapParams { address[] assetToSwapToList; uint256[] minAmountsToReceive; bool[] swapAllBalance; PermitParams permitParams; bool[] useEthPath; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Swaps the received reserve amount from the flash loan into the asset specified in the params. * The received funds from the swap are then deposited into the protocol on behalf of the user. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and * repay the flash loan. * @param assets Address of asset to be swapped * @param amounts Amount of the asset to be swapped * @param premiums Fee of the flash loan * @param initiator Address of the user * @param params Additional variadic field to include extra params. Expected parameters: * address[] assetToSwapToList List of the addresses of the reserve to be swapped to and deposited * uint256[] minAmountsToReceive List of min amounts to be received from the swap * bool[] swapAllBalance Flag indicating if all the user balance should be swapped * uint256[] permitAmount List of amounts for the permit signature * uint256[] deadline List of deadlines for the permit signature * uint8[] v List of v param for the permit signature * bytes32[] r List of r param for the permit signature * bytes32[] s List of s param for the permit signature */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); SwapParams memory decodedParams = _decodeParams(params); require( assets.length == decodedParams.assetToSwapToList.length && assets.length == decodedParams.minAmountsToReceive.length && assets.length == decodedParams.swapAllBalance.length && assets.length == decodedParams.permitParams.amount.length && assets.length == decodedParams.permitParams.deadline.length && assets.length == decodedParams.permitParams.v.length && assets.length == decodedParams.permitParams.r.length && assets.length == decodedParams.permitParams.s.length && assets.length == decodedParams.useEthPath.length, 'INCONSISTENT_PARAMS' ); for (uint256 i = 0; i < assets.length; i++) { _swapLiquidity( assets[i], decodedParams.assetToSwapToList[i], amounts[i], premiums[i], initiator, decodedParams.minAmountsToReceive[i], decodedParams.swapAllBalance[i], PermitSignature( decodedParams.permitParams.amount[i], decodedParams.permitParams.deadline[i], decodedParams.permitParams.v[i], decodedParams.permitParams.r[i], decodedParams.permitParams.s[i] ), decodedParams.useEthPath[i] ); } return true; } struct SwapAndDepositLocalVars { uint256 i; uint256 aTokenInitiatorBalance; uint256 amountToSwap; uint256 receivedAmount; address aToken; } /** * @dev Swaps an amount of an asset to another and deposits the new asset amount on behalf of the user without using * a flash loan. This method can be used when the temporary transfer of the collateral asset to this contract * does not affect the user position. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and * perform the swap. * @param assetToSwapFromList List of addresses of the underlying asset to be swap from * @param assetToSwapToList List of addresses of the underlying asset to be swap to and deposited * @param amountToSwapList List of amounts to be swapped. If the amount exceeds the balance, the total balance is used for the swap * @param minAmountsToReceive List of min amounts to be received from the swap * @param permitParams List of struct containing the permit signatures * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v param for the permit signature * bytes32 r param for the permit signature * bytes32 s param for the permit signature * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise */ function swapAndDeposit( address[] calldata assetToSwapFromList, address[] calldata assetToSwapToList, uint256[] calldata amountToSwapList, uint256[] calldata minAmountsToReceive, PermitSignature[] calldata permitParams, bool[] calldata useEthPath ) external { require( assetToSwapFromList.length == assetToSwapToList.length && assetToSwapFromList.length == amountToSwapList.length && assetToSwapFromList.length == minAmountsToReceive.length && assetToSwapFromList.length == permitParams.length, 'INCONSISTENT_PARAMS' ); SwapAndDepositLocalVars memory vars; for (vars.i = 0; vars.i < assetToSwapFromList.length; vars.i++) { vars.aToken = _getReserveData(assetToSwapFromList[vars.i]).aTokenAddress; vars.aTokenInitiatorBalance = IERC20(vars.aToken).balanceOf(msg.sender); vars.amountToSwap = amountToSwapList[vars.i] > vars.aTokenInitiatorBalance ? vars.aTokenInitiatorBalance : amountToSwapList[vars.i]; _pullAToken( assetToSwapFromList[vars.i], vars.aToken, msg.sender, vars.amountToSwap, permitParams[vars.i] ); vars.receivedAmount = _swapExactTokensForTokens( assetToSwapFromList[vars.i], assetToSwapToList[vars.i], vars.amountToSwap, minAmountsToReceive[vars.i], useEthPath[vars.i] ); // Deposit new reserve IERC20(assetToSwapToList[vars.i]).safeApprove(address(LENDING_POOL), 0); IERC20(assetToSwapToList[vars.i]).safeApprove(address(LENDING_POOL), vars.receivedAmount); LENDING_POOL.deposit(assetToSwapToList[vars.i], vars.receivedAmount, msg.sender, 0); } } /** * @dev Swaps an `amountToSwap` of an asset to another and deposits the funds on behalf of the initiator. * @param assetFrom Address of the underlying asset to be swap from * @param assetTo Address of the underlying asset to be swap to and deposited * @param amount Amount from flash loan * @param premium Premium of the flash loan * @param minAmountToReceive Min amount to be received from the swap * @param swapAllBalance Flag indicating if all the user balance should be swapped * @param permitSignature List of struct containing the permit signature * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise */ struct SwapLiquidityLocalVars { address aToken; uint256 aTokenInitiatorBalance; uint256 amountToSwap; uint256 receivedAmount; uint256 flashLoanDebt; uint256 amountToPull; } function _swapLiquidity( address assetFrom, address assetTo, uint256 amount, uint256 premium, address initiator, uint256 minAmountToReceive, bool swapAllBalance, PermitSignature memory permitSignature, bool useEthPath ) internal { SwapLiquidityLocalVars memory vars; vars.aToken = _getReserveData(assetFrom).aTokenAddress; vars.aTokenInitiatorBalance = IERC20(vars.aToken).balanceOf(initiator); vars.amountToSwap = swapAllBalance && vars.aTokenInitiatorBalance.sub(premium) <= amount ? vars.aTokenInitiatorBalance.sub(premium) : amount; vars.receivedAmount = _swapExactTokensForTokens( assetFrom, assetTo, vars.amountToSwap, minAmountToReceive, useEthPath ); // Deposit new reserve IERC20(assetTo).safeApprove(address(LENDING_POOL), 0); IERC20(assetTo).safeApprove(address(LENDING_POOL), vars.receivedAmount); LENDING_POOL.deposit(assetTo, vars.receivedAmount, initiator, 0); vars.flashLoanDebt = amount.add(premium); vars.amountToPull = vars.amountToSwap.add(premium); _pullAToken(assetFrom, vars.aToken, initiator, vars.amountToPull, permitSignature); // Repay flash loan IERC20(assetFrom).safeApprove(address(LENDING_POOL), 0); IERC20(assetFrom).safeApprove(address(LENDING_POOL), vars.flashLoanDebt); } /** * @dev Decodes the information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address[] assetToSwapToList List of the addresses of the reserve to be swapped to and deposited * uint256[] minAmountsToReceive List of min amounts to be received from the swap * bool[] swapAllBalance Flag indicating if all the user balance should be swapped * uint256[] permitAmount List of amounts for the permit signature * uint256[] deadline List of deadlines for the permit signature * uint8[] v List of v param for the permit signature * bytes32[] r List of r param for the permit signature * bytes32[] s List of s param for the permit signature * bool[] useEthPath true if the swap needs to occur using ETH in the routing, false otherwise * @return SwapParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (SwapParams memory) { ( address[] memory assetToSwapToList, uint256[] memory minAmountsToReceive, bool[] memory swapAllBalance, uint256[] memory permitAmount, uint256[] memory deadline, uint8[] memory v, bytes32[] memory r, bytes32[] memory s, bool[] memory useEthPath ) = abi.decode( params, (address[], uint256[], bool[], uint256[], uint256[], uint8[], bytes32[], bytes32[], bool[]) ); return SwapParams( assetToSwapToList, minAmountsToReceive, swapAllBalance, PermitParams(permitAmount, deadline, v, r, s), useEthPath ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import {Helpers} from '../protocol/libraries/helpers/Helpers.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; /** * @title UniswapLiquiditySwapAdapter * @notice Uniswap V2 Adapter to swap liquidity. * @author Aave **/ contract FlashLiquidationAdapter is BaseUniswapAdapter { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000; struct LiquidationParams { address collateralAsset; address borrowedAsset; address user; uint256 debtToCover; bool useEthPath; } struct LiquidationCallLocalVars { uint256 initFlashBorrowedBalance; uint256 diffFlashBorrowedBalance; uint256 initCollateralBalance; uint256 diffCollateralBalance; uint256 flashLoanDebt; uint256 soldAmount; uint256 remainingTokens; uint256 borrowedAssetLeftovers; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Liquidate a non-healthy position collateral-wise, with a Health Factor below 1, using Flash Loan and Uniswap to repay flash loan premium. * - The caller (liquidator) with a flash loan covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk minus the flash loan premium. * @param assets Address of asset to be swapped * @param amounts Amount of the asset to be swapped * @param premiums Fee of the flash loan * @param initiator Address of the caller * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium * address borrowedAsset The asset that must be covered * address user The user address with a Health Factor below 1 * uint256 debtToCover The amount of debt to cover * bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); LiquidationParams memory decodedParams = _decodeParams(params); require(assets.length == 1 && assets[0] == decodedParams.borrowedAsset, 'INCONSISTENT_PARAMS'); _liquidateAndSwap( decodedParams.collateralAsset, decodedParams.borrowedAsset, decodedParams.user, decodedParams.debtToCover, decodedParams.useEthPath, amounts[0], premiums[0], initiator ); return true; } /** * @dev * @param collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium * @param borrowedAsset The asset that must be covered * @param user The user address with a Health Factor below 1 * @param debtToCover The amount of debt to coverage, can be max(-1) to liquidate all possible debt * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise * @param flashBorrowedAmount Amount of asset requested at the flash loan to liquidate the user position * @param premium Fee of the requested flash loan * @param initiator Address of the caller */ function _liquidateAndSwap( address collateralAsset, address borrowedAsset, address user, uint256 debtToCover, bool useEthPath, uint256 flashBorrowedAmount, uint256 premium, address initiator ) internal { LiquidationCallLocalVars memory vars; vars.initCollateralBalance = IERC20(collateralAsset).balanceOf(address(this)); if (collateralAsset != borrowedAsset) { vars.initFlashBorrowedBalance = IERC20(borrowedAsset).balanceOf(address(this)); // Track leftover balance to rescue funds in case of external transfers into this contract vars.borrowedAssetLeftovers = vars.initFlashBorrowedBalance.sub(flashBorrowedAmount); } vars.flashLoanDebt = flashBorrowedAmount.add(premium); // Approve LendingPool to use debt token for liquidation IERC20(borrowedAsset).approve(address(LENDING_POOL), debtToCover); // Liquidate the user position and release the underlying collateral LENDING_POOL.liquidationCall(collateralAsset, borrowedAsset, user, debtToCover, false); // Discover the liquidated tokens uint256 collateralBalanceAfter = IERC20(collateralAsset).balanceOf(address(this)); // Track only collateral released, not current asset balance of the contract vars.diffCollateralBalance = collateralBalanceAfter.sub(vars.initCollateralBalance); if (collateralAsset != borrowedAsset) { // Discover flash loan balance after the liquidation uint256 flashBorrowedAssetAfter = IERC20(borrowedAsset).balanceOf(address(this)); // Use only flash loan borrowed assets, not current asset balance of the contract vars.diffFlashBorrowedBalance = flashBorrowedAssetAfter.sub(vars.borrowedAssetLeftovers); // Swap released collateral into the debt asset, to repay the flash loan vars.soldAmount = _swapTokensForExactTokens( collateralAsset, borrowedAsset, vars.diffCollateralBalance, vars.flashLoanDebt.sub(vars.diffFlashBorrowedBalance), useEthPath ); vars.remainingTokens = vars.diffCollateralBalance.sub(vars.soldAmount); } else { vars.remainingTokens = vars.diffCollateralBalance.sub(premium); } // Allow repay of flash loan IERC20(borrowedAsset).approve(address(LENDING_POOL), vars.flashLoanDebt); // Transfer remaining tokens to initiator if (vars.remainingTokens > 0) { IERC20(collateralAsset).transfer(initiator, vars.remainingTokens); } } /** * @dev Decodes the information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset The collateral asset to claim * address borrowedAsset The asset that must be covered and will be exchanged to pay the flash loan premium * address user The user address with a Health Factor below 1 * uint256 debtToCover The amount of debt to cover * bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap * @return LiquidationParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (LiquidationParams memory) { ( address collateralAsset, address borrowedAsset, address user, uint256 debtToCover, bool useEthPath ) = abi.decode(params, (address, address, address, uint256, bool)); return LiquidationParams(collateralAsset, borrowedAsset, user, debtToCover, useEthPath); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseAdminUpgradeabilityProxy.sol'; import './InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param logic address of the initial implementation. * @param admin Address of the proxy administrator. * @param data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize( address logic, address admin, bytes memory data ) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(logic, data); assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './UpgradeabilityProxy.sol'; /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), 'Cannot change the admin of a proxy to the zero address'); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); (bool success, ) = newImplementation.delegatecall(data); require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; //solium-disable-next-line assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; //solium-disable-next-line assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal virtual override { require(msg.sender != _admin(), 'Cannot call fallback function from the proxy admin'); super._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseUpgradeabilityProxy.sol'; /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseAdminUpgradeabilityProxy.sol'; /** * @title AdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for * initializing the implementation, admin, and init data. */ contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor( address _logic, address _admin, bytes memory _data ) public payable UpgradeabilityProxy(_logic, _data) { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; // Prettier ignore to prevent buidler flatter bug // prettier-ignore import {InitializableImmutableAdminUpgradeabilityProxy} from '../libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ contract LendingPoolAddressesProvider is Ownable, ILendingPoolAddressesProvider { string private _marketId; mapping(bytes32 => address) private _addresses; bytes32 private constant LENDING_POOL = 'LENDING_POOL'; bytes32 private constant LENDING_POOL_CONFIGURATOR = 'LENDING_POOL_CONFIGURATOR'; bytes32 private constant POOL_ADMIN = 'POOL_ADMIN'; bytes32 private constant EMERGENCY_ADMIN = 'EMERGENCY_ADMIN'; bytes32 private constant LENDING_POOL_COLLATERAL_MANAGER = 'COLLATERAL_MANAGER'; bytes32 private constant PRICE_ORACLE = 'PRICE_ORACLE'; bytes32 private constant LENDING_RATE_ORACLE = 'LENDING_RATE_ORACLE'; constructor(string memory marketId) public { _setMarketId(marketId); } /** * @dev Returns the id of the Aave market to which this contracts points to * @return The market id **/ function getMarketId() external view override returns (string memory) { return _marketId; } /** * @dev Allows to set the market which this LendingPoolAddressesProvider represents * @param marketId The market id */ function setMarketId(string memory marketId) external override onlyOwner { _setMarketId(marketId); } /** * @dev General function to update the implementation of a proxy registered with * certain `id`. If there is no proxy registered, it will instantiate one and * set as implementation the `implementationAddress` * IMPORTANT Use this function carefully, only for ids that don't have an explicit * setter function, in order to avoid unexpected consequences * @param id The id * @param implementationAddress The address of the new implementation */ function setAddressAsProxy(bytes32 id, address implementationAddress) external override onlyOwner { _updateImpl(id, implementationAddress); emit AddressSet(id, implementationAddress, true); } /** * @dev Sets an address for an id replacing the address saved in the addresses map * IMPORTANT Use this function carefully, as it will do a hard replacement * @param id The id * @param newAddress The address to set */ function setAddress(bytes32 id, address newAddress) external override onlyOwner { _addresses[id] = newAddress; emit AddressSet(id, newAddress, false); } /** * @dev Returns an address by id * @return The address */ function getAddress(bytes32 id) public view override returns (address) { return _addresses[id]; } /** * @dev Returns the address of the LendingPool proxy * @return The LendingPool proxy address **/ function getLendingPool() external view override returns (address) { return getAddress(LENDING_POOL); } /** * @dev Updates the implementation of the LendingPool, or creates the proxy * setting the new `pool` implementation on the first time calling it * @param pool The new LendingPool implementation **/ function setLendingPoolImpl(address pool) external override onlyOwner { _updateImpl(LENDING_POOL, pool); emit LendingPoolUpdated(pool); } /** * @dev Returns the address of the LendingPoolConfigurator proxy * @return The LendingPoolConfigurator proxy address **/ function getLendingPoolConfigurator() external view override returns (address) { return getAddress(LENDING_POOL_CONFIGURATOR); } /** * @dev Updates the implementation of the LendingPoolConfigurator, or creates the proxy * setting the new `configurator` implementation on the first time calling it * @param configurator The new LendingPoolConfigurator implementation **/ function setLendingPoolConfiguratorImpl(address configurator) external override onlyOwner { _updateImpl(LENDING_POOL_CONFIGURATOR, configurator); emit LendingPoolConfiguratorUpdated(configurator); } /** * @dev Returns the address of the LendingPoolCollateralManager. Since the manager is used * through delegateCall within the LendingPool contract, the proxy contract pattern does not work properly hence * the addresses are changed directly * @return The address of the LendingPoolCollateralManager **/ function getLendingPoolCollateralManager() external view override returns (address) { return getAddress(LENDING_POOL_COLLATERAL_MANAGER); } /** * @dev Updates the address of the LendingPoolCollateralManager * @param manager The new LendingPoolCollateralManager address **/ function setLendingPoolCollateralManager(address manager) external override onlyOwner { _addresses[LENDING_POOL_COLLATERAL_MANAGER] = manager; emit LendingPoolCollateralManagerUpdated(manager); } /** * @dev The functions below are getters/setters of addresses that are outside the context * of the protocol hence the upgradable proxy pattern is not used **/ function getPoolAdmin() external view override returns (address) { return getAddress(POOL_ADMIN); } function setPoolAdmin(address admin) external override onlyOwner { _addresses[POOL_ADMIN] = admin; emit ConfigurationAdminUpdated(admin); } function getEmergencyAdmin() external view override returns (address) { return getAddress(EMERGENCY_ADMIN); } function setEmergencyAdmin(address emergencyAdmin) external override onlyOwner { _addresses[EMERGENCY_ADMIN] = emergencyAdmin; emit EmergencyAdminUpdated(emergencyAdmin); } function getPriceOracle() external view override returns (address) { return getAddress(PRICE_ORACLE); } function setPriceOracle(address priceOracle) external override onlyOwner { _addresses[PRICE_ORACLE] = priceOracle; emit PriceOracleUpdated(priceOracle); } function getLendingRateOracle() external view override returns (address) { return getAddress(LENDING_RATE_ORACLE); } function setLendingRateOracle(address lendingRateOracle) external override onlyOwner { _addresses[LENDING_RATE_ORACLE] = lendingRateOracle; emit LendingRateOracleUpdated(lendingRateOracle); } /** * @dev Internal function to update the implementation of a specific proxied component of the protocol * - If there is no proxy registered in the given `id`, it creates the proxy setting `newAdress` * as implementation and calls the initialize() function on the proxy * - If there is already a proxy registered, it just updates the implementation to `newAddress` and * calls the initialize() function via upgradeToAndCall() in the proxy * @param id The id of the proxy to be updated * @param newAddress The address of the new implementation **/ function _updateImpl(bytes32 id, address newAddress) internal { address payable proxyAddress = payable(_addresses[id]); InitializableImmutableAdminUpgradeabilityProxy proxy = InitializableImmutableAdminUpgradeabilityProxy(proxyAddress); bytes memory params = abi.encodeWithSignature('initialize(address)', address(this)); if (proxyAddress == address(0)) { proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this)); proxy.initialize(newAddress, params); _addresses[id] = address(proxy); emit ProxyCreated(id, address(proxy)); } else { proxy.upgradeToAndCall(newAddress, params); } } function _setMarketId(string memory marketId) internal { _marketId = marketId; emit MarketIdSet(marketId); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {LendingPool} from '../protocol/lendingpool/LendingPool.sol'; import { LendingPoolAddressesProvider } from '../protocol/configuration/LendingPoolAddressesProvider.sol'; import {LendingPoolConfigurator} from '../protocol/lendingpool/LendingPoolConfigurator.sol'; import {AToken} from '../protocol/tokenization/AToken.sol'; import { DefaultReserveInterestRateStrategy } from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {StringLib} from './StringLib.sol'; contract ATokensAndRatesHelper is Ownable { address payable private pool; address private addressesProvider; address private poolConfigurator; event deployedContracts(address aToken, address strategy); struct InitDeploymentInput { address asset; uint256[6] rates; } struct ConfigureReserveInput { address asset; uint256 baseLTV; uint256 liquidationThreshold; uint256 liquidationBonus; uint256 reserveFactor; bool stableBorrowingEnabled; } constructor( address payable _pool, address _addressesProvider, address _poolConfigurator ) public { pool = _pool; addressesProvider = _addressesProvider; poolConfigurator = _poolConfigurator; } function initDeployment(InitDeploymentInput[] calldata inputParams) external onlyOwner { for (uint256 i = 0; i < inputParams.length; i++) { emit deployedContracts( address(new AToken()), address( new DefaultReserveInterestRateStrategy( LendingPoolAddressesProvider(addressesProvider), inputParams[i].rates[0], inputParams[i].rates[1], inputParams[i].rates[2], inputParams[i].rates[3], inputParams[i].rates[4], inputParams[i].rates[5] ) ) ); } } function configureReserves(ConfigureReserveInput[] calldata inputParams) external onlyOwner { LendingPoolConfigurator configurator = LendingPoolConfigurator(poolConfigurator); for (uint256 i = 0; i < inputParams.length; i++) { configurator.configureReserveAsCollateral( inputParams[i].asset, inputParams[i].baseLTV, inputParams[i].liquidationThreshold, inputParams[i].liquidationBonus ); configurator.enableBorrowingOnReserve( inputParams[i].asset, inputParams[i].stableBorrowingEnabled ); configurator.setReserveFactor(inputParams[i].asset, inputParams[i].reserveFactor); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library StringLib { function concat(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a, b)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {StableDebtToken} from '../protocol/tokenization/StableDebtToken.sol'; import {VariableDebtToken} from '../protocol/tokenization/VariableDebtToken.sol'; import {LendingRateOracle} from '../mocks/oracle/LendingRateOracle.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {StringLib} from './StringLib.sol'; contract StableAndVariableTokensHelper is Ownable { address payable private pool; address private addressesProvider; event deployedContracts(address stableToken, address variableToken); constructor(address payable _pool, address _addressesProvider) public { pool = _pool; addressesProvider = _addressesProvider; } function initDeployment(address[] calldata tokens, string[] calldata symbols) external onlyOwner { require(tokens.length == symbols.length, 'Arrays not same length'); require(pool != address(0), 'Pool can not be zero address'); for (uint256 i = 0; i < tokens.length; i++) { emit deployedContracts(address(new StableDebtToken()), address(new VariableDebtToken())); } } function setOracleBorrowRates( address[] calldata assets, uint256[] calldata rates, address oracle ) external onlyOwner { require(assets.length == rates.length, 'Arrays not same length'); for (uint256 i = 0; i < assets.length; i++) { // LendingRateOracle owner must be this contract LendingRateOracle(oracle).setMarketBorrowRate(assets[i], rates[i]); } } function setOracleOwnership(address oracle, address admin) external onlyOwner { require(admin != address(0), 'owner can not be zero'); require(LendingRateOracle(oracle).owner() == address(this), 'helper is not owner'); LendingRateOracle(oracle).transferOwnership(admin); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol'; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; contract LendingRateOracle is ILendingRateOracle, Ownable { mapping(address => uint256) borrowRates; mapping(address => uint256) liquidityRates; function getMarketBorrowRate(address _asset) external view override returns (uint256) { return borrowRates[_asset]; } function setMarketBorrowRate(address _asset, uint256 _rate) external override onlyOwner { borrowRates[_asset] = _rate; } function getMarketLiquidityRate(address _asset) external view returns (uint256) { return liquidityRates[_asset]; } function setMarketLiquidityRate(address _asset, uint256 _rate) external onlyOwner { liquidityRates[_asset] = _rate; } }
Gets the configuration paramters of the reserve from a memory object self The reserve configuration return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals/
function getParamsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( uint256, uint256, uint256, uint256, uint256 ) { return ( self.data & ~LTV_MASK, (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); }
68,405
./partial_match/1/0xCDdE7BAB4896B9818aaFFEC71B2ff8576F8550E5/sources/genesis.sol
on-chain whitelist setting ================================================================================ Description of validate address recipient Description of address recipient return value : true if the address in whitelist/
function validate(address recipient) public view returns (bool) { return _whitelist[recipient]; }
15,938,212
./full_match/1/0x77337dEEA78720542f0A1325394Def165918D562/sources/src/libraries/SplitSwapLibrary.sol
Given some asset amount and reserves, returns an amount of the other asset representing equivalent value Require replaced with revert custom error amountA Amount of token A reserveA Reserves for tokenA reserveB Reserves for tokenB return amountB Amount of token B returned
function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { if (_isZero(amountA)) revert ZeroAmount(); if (_isZero(reserveA) || _isZero(reserveB)) revert InsufficientLiquidity(); amountB = (amountA * reserveB) / reserveA; }
16,514,071
// SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "./Ownable.sol"; import "./Strings.sol"; import "./interfaces/ITraits.sol"; import "./interfaces/IWoolf.sol"; contract Traits is Ownable, ITraits { using Strings for uint256; // struct to store each trait's data for metadata and rendering struct Trait { string name; string png; } // mapping from trait type (index) to its name string[9] _traitTypes = [ "Fur", "Head", "Ears", "Eyes", "Nose", "Mouth", "Neck", "Feet", "Alpha" ]; // storage of each traits name and base64 PNG data mapping(uint8 => mapping(uint8 => Trait)) public traitData; // mapping from alphaIndex to its score string[4] _alphas = ["8", "7", "6", "5"]; IWoolf public woolf; constructor() {} /** ADMIN */ function setWoolf(address _woolf) external onlyOwner { woolf = IWoolf(_woolf); } /** * administrative to upload the names and images associated with each trait * @param traitType the trait type to upload the traits for (see traitTypes for a mapping) * @param traits the names and base64 encoded PNGs for each trait */ function uploadTraits( uint8 traitType, uint8[] calldata traitIds, Trait[] calldata traits ) external onlyOwner { require(traitIds.length == traits.length, "Mismatched inputs"); for (uint256 i = 0; i < traits.length; i++) { traitData[traitType][traitIds[i]] = Trait( traits[i].name, traits[i].png ); } } /** RENDER */ /** * generates an <image> element using base64 encoded PNGs * @param trait the trait storing the PNG data * @return the <image> element */ function drawTrait(Trait memory trait) internal pure returns (string memory) { return string( abi.encodePacked( '<image x="4" y="4" width="32" height="32" image-rendering="pixelated" preserveAspectRatio="xMidYMid" xlink:href="data:image/png;base64,', trait.png, '"/>' ) ); } /** * generates an entire SVG by composing multiple <image> elements of PNGs * @param tokenId the ID of the token to generate an SVG for * @return a valid SVG of the Sheep / Wolf */ function drawSVG(uint256 tokenId) public view returns (string memory) { IWoolf.SheepWolf memory s = woolf.getTokenTraits(tokenId); uint8 shift = s.isSheep ? 0 : 9; string memory svgString = string( abi.encodePacked( drawTrait(traitData[0 + shift][s.fur]), s.isSheep ? drawTrait(traitData[1 + shift][s.head]) : drawTrait(traitData[1 + shift][s.alphaIndex]), s.isSheep ? drawTrait(traitData[2 + shift][s.ears]) : "", drawTrait(traitData[3 + shift][s.eyes]), s.isSheep ? drawTrait(traitData[4 + shift][s.nose]) : "", drawTrait(traitData[5 + shift][s.mouth]), s.isSheep ? "" : drawTrait(traitData[6 + shift][s.neck]), s.isSheep ? drawTrait(traitData[7 + shift][s.feet]) : "" ) ); return string( abi.encodePacked( '<svg id="woolf" width="100%" height="100%" version="1.1" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">', svgString, "</svg>" ) ); } /** * generates an attribute for the attributes array in the ERC721 metadata standard * @param traitType the trait type to reference as the metadata key * @param value the token's trait associated with the key * @return a JSON dictionary for the single attribute */ function attributeForTypeAndValue( string memory traitType, string memory value ) internal pure returns (string memory) { return string( abi.encodePacked( '{"trait_type":"', traitType, '","value":"', value, '"}' ) ); } /** * generates an array composed of all the individual traits and values * @param tokenId the ID of the token to compose the metadata for * @return a JSON array of all of the attributes for given token ID */ function compileAttributes(uint256 tokenId) public view returns (string memory) { IWoolf.SheepWolf memory s = woolf.getTokenTraits(tokenId); string memory traits; if (s.isSheep) { traits = string( abi.encodePacked( attributeForTypeAndValue( _traitTypes[0], traitData[0][s.fur].name ), ",", attributeForTypeAndValue( _traitTypes[1], traitData[1][s.head].name ), ",", attributeForTypeAndValue( _traitTypes[2], traitData[2][s.ears].name ), ",", attributeForTypeAndValue( _traitTypes[3], traitData[3][s.eyes].name ), ",", attributeForTypeAndValue( _traitTypes[4], traitData[4][s.nose].name ), ",", attributeForTypeAndValue( _traitTypes[5], traitData[5][s.mouth].name ), ",", attributeForTypeAndValue( _traitTypes[7], traitData[7][s.feet].name ), "," ) ); } else { traits = string( abi.encodePacked( attributeForTypeAndValue( _traitTypes[0], traitData[9][s.fur].name ), ",", attributeForTypeAndValue( _traitTypes[1], traitData[10][s.alphaIndex].name ), ",", attributeForTypeAndValue( _traitTypes[3], traitData[12][s.eyes].name ), ",", attributeForTypeAndValue( _traitTypes[5], traitData[14][s.mouth].name ), ",", attributeForTypeAndValue( _traitTypes[6], traitData[15][s.neck].name ), ",", attributeForTypeAndValue( "Alpha Score", _alphas[s.alphaIndex] ), "," ) ); } return string( abi.encodePacked( "[", traits, '{"trait_type":"Generation","value":', tokenId <= woolf.getPaidTokens() ? '"Gen 0"' : '"Gen 1"', '},{"trait_type":"Type","value":', s.isSheep ? '"Sheep"' : '"Wolf"', "}]" ) ); } /** * generates a base64 encoded metadata response without referencing off-chain content * @param tokenId the ID of the token to generate the metadata for * @return a base64 encoded JSON dictionary of the token's metadata and SVG */ function tokenURI(uint256 tokenId) public view override returns (string memory) { IWoolf.SheepWolf memory s = woolf.getTokenTraits(tokenId); string memory metadata = string( abi.encodePacked( '{"name": "', s.isSheep ? "Sheep #" : "Wolf #", tokenId.toString(), '", "description": "Thousands of Sheep and Wolves compete on a farm in the metaverse. A tempting prize of $WOOL awaits, with deadly high stakes. All the metadata and images are generated and stored 100% on-chain. No IPFS. NO API. Just the Ethereum blockchain.", "image": "data:image/svg+xml;base64,', base64(bytes(drawSVG(tokenId))), '", "attributes":', compileAttributes(tokenId), "}" ) ); return string( abi.encodePacked( "data:application/json;base64,", base64(bytes(metadata)) ) ); } /** BASE 64 - Written by Brech Devos */ string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ""; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for { } lt(dataPtr, endPtr) { } { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(input, 0x3F)))) ) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } }
generates a base64 encoded metadata response without referencing off-chain content tokenId the ID of the token to generate the metadata for return a base64 encoded JSON dictionary of the token's metadata and SVG/
function tokenURI(uint256 tokenId) public view override returns (string memory) { IWoolf.SheepWolf memory s = woolf.getTokenTraits(tokenId); string memory metadata = string( abi.encodePacked( '{"name": "', s.isSheep ? "Sheep #" : "Wolf #", tokenId.toString(), '", "description": "Thousands of Sheep and Wolves compete on a farm in the metaverse. A tempting prize of $WOOL awaits, with deadly high stakes. All the metadata and images are generated and stored 100% on-chain. No IPFS. NO API. Just the Ethereum blockchain.", "image": "data:image/svg+xml;base64,', base64(bytes(drawSVG(tokenId))), '", "attributes":', compileAttributes(tokenId), "}" ) ); return string( abi.encodePacked( "data:application/json;base64,", base64(bytes(metadata)) ) ); } string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
12,545,759
pragma solidity 0.5.17; import "./MToken.sol"; import "./MomaPool.sol"; // unused currently import "./Governance/Moma.sol"; import "./MomaFactoryInterface.sol"; contract MomaFarming is ExponentialNoError { address public admin; Moma public moma; MomaFactoryInterface public factory; bool public constant isMomaFarming = true; /// @notice The initial moma index for a market uint public constant momaInitialIndex = 1e36; uint public momaSpeed; uint public momaTotalWeight; struct MarketState { /// @notice Whether is MOMA market, used to avoid add to momaMarkets again bool isMomaMarket; /// @notice The market's MOMA weight, times of 1 uint weight; /// @notice The market's block number that the supplyIndex was last updated at uint supplyBlock; /// @notice The market's block number that the borrowIndex was last updated at uint borrowBlock; /// @notice The market's last updated supplyIndex uint supplyIndex; /// @notice The market's last updated borrowIndex uint borrowIndex; /// @notice The market's MOMA supply index of each supplier as of the last time they accrued MOMA mapping(address => uint) supplierIndex; /// @notice The market's MOMA borrow index of each borrower as of the last time they accrued MOMA mapping(address => uint) borrowerIndex; } /// @notice Each MOMA pool's each momaMarket's MarketState mapping(address => mapping(address => MarketState)) public marketStates; /// @notice Each MOMA pool's momaMarkets list mapping(address => MToken[]) public momaMarkets; /// @notice Whether is MOMA lending pool mapping(address => bool) public isMomaLendingPool; /// @notice Whether is MOMA pool, used to avoid add to momaPools again mapping(address => bool) public isMomaPool; /// @notice A list of all MOMA pools MomaPool[] public momaPools; /// @notice The MOMA accrued but not yet transferred to each user mapping(address => uint) public momaAccrued; /// @notice Emitted when MOMA is distributed to a supplier event DistributedSupplier(address indexed pool, MToken indexed mToken, address indexed supplier, uint momaDelta, uint marketSupplyIndex); /// @notice Emitted when MOMA is distributed to a borrower event DistributedBorrower(address indexed pool, MToken indexed mToken, address indexed borrower, uint momaDelta, uint marketBorrowIndex); /// @notice Emitted when MOMA is claimed by user event MomaClaimed(address user, uint accrued, uint claimed, uint notClaimed); /// @notice Emitted when admin is changed by admin event NewAdmin(address oldAdmin, address newAdmin); /// @notice Emitted when factory is changed by admin event NewFactory(MomaFactoryInterface oldFactory, MomaFactoryInterface newFactory); /// @notice Emitted when momaSpeed is changed by admin event NewMomaSpeed(uint oldMomaSpeed, uint newMomaSpeed); /// @notice Emitted when a new MOMA weight is changed by admin event NewMarketWeight(address indexed pool, MToken indexed mToken, uint oldWeight, uint newWeight); /// @notice Emitted when a new MOMA total weight is updated event NewTotalWeight(uint oldTotalWeight, uint newTotalWeight); /// @notice Emitted when a new MOMA market is added to momaMarkets event NewMomaMarket(address indexed pool, MToken indexed mToken); /// @notice Emitted when a new MOMA pool is added to momaPools event NewMomaPool(address indexed pool); /// @notice Emitted when MOMA is granted by admin event MomaGranted(address recipient, uint amount); constructor (Moma _moma, MomaFactoryInterface _factory) public { admin = msg.sender; moma = _moma; factory = _factory; } /*** Internal Functions ***/ /** * @notice Calculate the new MOMA supply index and block of this market * @dev Non-moma market will return (0, blockNumber). To avoid revert: momaTotalWeight > 0 * @param pool The pool whose supply index to calculate * @param mToken The market whose supply index to calculate * @return (new index, new block) */ function newMarketSupplyStateInternal(address pool, MToken mToken) internal view returns (uint, uint) { MarketState storage state = marketStates[pool][address(mToken)]; uint _index = state.supplyIndex; uint _block = state.supplyBlock; uint blockNumber = getBlockNumber(); // Non-moma market's weight is always 0, will only update block if (blockNumber > _block) { uint speed = div_(mul_(momaSpeed, state.weight), momaTotalWeight); uint deltaBlocks = sub_(blockNumber, _block); uint _momaAccrued = mul_(deltaBlocks, speed); uint supplyTokens = mToken.totalSupply(); Double memory ratio = supplyTokens > 0 ? fraction(_momaAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: _index}), ratio); _index = index.mantissa; _block = blockNumber; } return (_index, _block); } /** * @notice Accrue MOMA to the market by updating the supply state * @dev To avoid revert: no over/underflow * @param pool The pool whose supply state to update * @param mToken The market whose supply state to update */ function updateMarketSupplyStateInternal(address pool, MToken mToken) internal { MarketState storage state = marketStates[pool][address(mToken)]; // Non-moma market's weight will always be 0, 0 weight moma market will also update nothing if (state.weight > 0) { // momaTotalWeight > 0 (uint _index, uint _block) = newMarketSupplyStateInternal(pool, mToken); state.supplyIndex = _index; state.supplyBlock = _block; } } /** * @notice Calculate the new MOMA borrow index and block of this market * @dev Non-moma market will return (0, blockNumber). To avoid revert: momaTotalWeight > 0, marketBorrowIndex > 0 * @param pool The pool whose borrow index to calculate * @param mToken The market whose borrow index to calculate * @param marketBorrowIndex The market borrow index * @return (new index, new block) */ function newMarketBorrowStateInternal(address pool, MToken mToken, uint marketBorrowIndex) internal view returns (uint, uint) { MarketState storage state = marketStates[pool][address(mToken)]; uint _index = state.borrowIndex; uint _block = state.borrowBlock; uint blockNumber = getBlockNumber(); // Non-moma market's weight is always 0, will only update block if (blockNumber > _block) { uint speed = div_(mul_(momaSpeed, state.weight), momaTotalWeight); uint deltaBlocks = sub_(blockNumber, _block); uint _momaAccrued = mul_(deltaBlocks, speed); uint borrowAmount = div_(mToken.totalBorrows(), Exp({mantissa: marketBorrowIndex})); Double memory ratio = borrowAmount > 0 ? fraction(_momaAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: _index}), ratio); _index = index.mantissa; _block = blockNumber; } return (_index, _block); } /** * @notice Accrue MOMA to the market by updating the borrow state * @dev To avoid revert: no over/underflow * @param pool The pool whose borrow state to update * @param mToken The market whose borrow state to update * @param marketBorrowIndex The market borrow index */ function updateMarketBorrowStateInternal(address pool, MToken mToken, uint marketBorrowIndex) internal { if (isMomaLendingPool[pool] == true) { MarketState storage state = marketStates[pool][address(mToken)]; // Non-moma market's weight will always be 0, 0 weight moma market will also update nothing if (state.weight > 0 && marketBorrowIndex > 0) { // momaTotalWeight > 0 (uint _index, uint _block) = newMarketBorrowStateInternal(pool, mToken, marketBorrowIndex); state.borrowIndex = _index; state.borrowBlock = _block; } } } /** * @notice Calculate MOMA accrued by a supplier * @dev To avoid revert: no over/underflow * @param pool The pool in which the supplier is interacting * @param mToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute token to * @param supplyIndex The MOMA supply index of this market in Double type * @return (new supplierAccrued, new supplierDelta) */ function newSupplierMomaInternal(address pool, MToken mToken, address supplier, Double memory supplyIndex) internal view returns (uint, uint) { Double memory supplierIndex = Double({mantissa: marketStates[pool][address(mToken)].supplierIndex[supplier]}); uint _supplierAccrued = momaAccrued[supplier]; uint _supplierDelta = 0; // supply before set moma market can still get rewards start from set block if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = momaInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = mToken.balanceOf(supplier); _supplierDelta = mul_(supplierTokens, deltaIndex); _supplierAccrued = add_(_supplierAccrued, _supplierDelta); return (_supplierAccrued, _supplierDelta); } /** * @notice Distribute MOMA accrued by a supplier * @dev To avoid revert: no over/underflow * @param pool The pool in which the supplier is interacting * @param mToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute MOMA to */ function distributeSupplierMomaInternal(address pool, MToken mToken, address supplier) internal { MarketState storage state = marketStates[pool][address(mToken)]; if (state.supplyIndex > state.supplierIndex[supplier]) { Double memory supplyIndex = Double({mantissa: state.supplyIndex}); (uint _supplierAccrued, uint _supplierDelta) = newSupplierMomaInternal(pool, mToken, supplier, supplyIndex); state.supplierIndex[supplier] = supplyIndex.mantissa; momaAccrued[supplier] = _supplierAccrued; emit DistributedSupplier(pool, mToken, supplier, _supplierDelta, supplyIndex.mantissa); } } /** * @notice Calculate MOMA accrued by a borrower * @dev Borrowers will not begin to accrue until after the first interaction with the protocol * @dev To avoid revert: marketBorrowIndex > 0 * @param pool The pool in which the borrower is interacting * @param mToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute MOMA to * @param marketBorrowIndex The market borrow index * @param borrowIndex The MOMA borrow index of this market in Double type * @return (new borrowerAccrued, new borrowerDelta) */ function newBorrowerMomaInternal(address pool, MToken mToken, address borrower, uint marketBorrowIndex, Double memory borrowIndex) internal view returns (uint, uint) { Double memory borrowerIndex = Double({mantissa: marketStates[pool][address(mToken)].borrowerIndex[borrower]}); uint _borrowerAccrued = momaAccrued[borrower]; uint _borrowerDelta = 0; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(mToken.borrowBalanceStored(borrower), Exp({mantissa: marketBorrowIndex})); _borrowerDelta = mul_(borrowerAmount, deltaIndex); _borrowerAccrued = add_(_borrowerAccrued, _borrowerDelta); } return (_borrowerAccrued, _borrowerDelta); } /** * @notice Distribute MOMA accrued by a borrower * @dev Borrowers will not begin to accrue until after the first interaction with the protocol * @dev To avoid revert: no over/underflow * @param pool The pool in which the borrower is interacting * @param mToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute MOMA to * @param marketBorrowIndex The market borrow index */ function distributeBorrowerMomaInternal(address pool, MToken mToken, address borrower, uint marketBorrowIndex) internal { if (isMomaLendingPool[pool] == true) { MarketState storage state = marketStates[pool][address(mToken)]; if (state.borrowIndex > state.borrowerIndex[borrower] && marketBorrowIndex > 0) { Double memory borrowIndex = Double({mantissa: state.borrowIndex}); (uint _borrowerAccrued, uint _borrowerDelta) = newBorrowerMomaInternal(pool, mToken, borrower, marketBorrowIndex, borrowIndex); state.borrowerIndex[borrower] = borrowIndex.mantissa; momaAccrued[borrower] = _borrowerAccrued; emit DistributedBorrower(pool, mToken, borrower, _borrowerDelta, borrowIndex.mantissa); } } } /** * @notice Transfer MOMA to the user * @dev Note: If there is not enough MOMA, will do not perform the transfer * @param user The address of the user to transfer MOMA to * @param amount The amount of token to (possibly) transfer * @return The amount of token which was NOT transferred to the user */ function grantMomaInternal(address user, uint amount) internal returns (uint) { uint remaining = moma.balanceOf(address(this)); if (amount > 0 && amount <= remaining) { moma.transfer(user, amount); return 0; } return amount; } /** * @notice Claim all the MOMA have been distributed to user * @param user The address to claim MOMA for */ function claim(address user) internal { uint accrued = momaAccrued[user]; uint notClaimed = grantMomaInternal(user, accrued); momaAccrued[user] = notClaimed; uint claimed = sub_(accrued, notClaimed); emit MomaClaimed(user, accrued, claimed, notClaimed); } /** * @notice Distribute all the MOMA accrued to user in the specified markets of specified pool * @param user The address to distribute MOMA for * @param pool The moma pool to distribute MOMA in * @param mTokens The list of markets to distribute MOMA in * @param suppliers Whether or not to distribute MOMA earned by supplying * @param borrowers Whether or not to distribute MOMA earned by borrowing */ function distribute(address user, address pool, MToken[] memory mTokens, bool suppliers, bool borrowers) internal { for (uint i = 0; i < mTokens.length; i++) { MToken mToken = mTokens[i]; if (suppliers == true) { updateMarketSupplyStateInternal(pool, mToken); distributeSupplierMomaInternal(pool, mToken, user); } if (borrowers == true && isMomaLendingPool[pool] == true) { uint borrowIndex = mToken.borrowIndex(); updateMarketBorrowStateInternal(pool, mToken, borrowIndex); distributeBorrowerMomaInternal(pool, mToken, user, borrowIndex); } } } /** * @notice Distribute all the MOMA accrued to user in all markets of specified pools * @param user The address to distribute MOMA for * @param pools The list of moma pools to distribute MOMA * @param suppliers Whether or not to distribute MOMA earned by supplying * @param borrowers Whether or not to distribute MOMA earned by borrowing */ function distribute(address user, MomaPool[] memory pools, bool suppliers, bool borrowers) internal { for (uint i = 0; i < pools.length; i++) { address pool = address(pools[i]); distribute(user, pool, momaMarkets[pool], suppliers, borrowers); } } /*** Factory Functions ***/ /** * @notice Update pool market's borrowBlock when it upgrades to lending pool in factory * @dev Note: can only call once by factory * @param pool The pool to upgrade */ function upgradeLendingPool(address pool) external { require(msg.sender == address(factory), 'MomaFarming: not factory'); require(isMomaLendingPool[pool] == false, 'MomaFarming: can only upgrade once'); uint blockNumber = getBlockNumber(); MToken[] memory mTokens = momaMarkets[pool]; for (uint i = 0; i < mTokens.length; i++) { MarketState storage state = marketStates[pool][address(mTokens[i])]; state.borrowBlock = blockNumber; // if state.weight > 0 ? } isMomaLendingPool[pool] = true; } /*** Called Functions ***/ /** * @notice Accrue MOMA to the market by updating the supply state * @param mToken The market whose supply state to update */ function updateMarketSupplyState(address mToken) external { require(factory.isMomaPool(msg.sender), 'MomaFarming: not moma pool'); updateMarketSupplyStateInternal(msg.sender, MToken(mToken)); } /** * @notice Accrue MOMA to the market by updating the borrow state * @param mToken The market whose borrow state to update * @param marketBorrowIndex The market borrow index */ function updateMarketBorrowState(address mToken, uint marketBorrowIndex) external { require(factory.isMomaPool(msg.sender), 'MomaFarming: not moma pool'); updateMarketBorrowStateInternal(msg.sender, MToken(mToken), marketBorrowIndex); } /** * @notice Distribute MOMA accrued by a supplier * @param mToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute MOMA to */ function distributeSupplierMoma(address mToken, address supplier) external { require(factory.isMomaPool(msg.sender), 'MomaFarming: not moma pool'); distributeSupplierMomaInternal(msg.sender, MToken(mToken), supplier); } /** * @notice Distribute MOMA accrued by a borrower * @dev Borrowers will not begin to accrue until after the first interaction with the protocol * @param mToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute MOMA to * @param marketBorrowIndex The market borrow index */ function distributeBorrowerMoma(address mToken, address borrower, uint marketBorrowIndex) external { require(factory.isMomaPool(msg.sender), 'MomaFarming: not moma pool'); distributeBorrowerMomaInternal(msg.sender, MToken(mToken), borrower, marketBorrowIndex); } /** * @notice Distribute all the MOMA accrued to user in specified markets of specified pool and claim * @param pool The moma pool to distribute MOMA in * @param mTokens The list of markets to distribute MOMA in * @param suppliers Whether or not to distribute MOMA earned by supplying * @param borrowers Whether or not to distribute MOMA earned by borrowing */ function dclaim(address pool, MToken[] memory mTokens, bool suppliers, bool borrowers) public { distribute(msg.sender, pool, mTokens, suppliers, borrowers); claim(msg.sender); } /** * @notice Distribute all the MOMA accrued to user in all markets of specified pools and claim * @param pools The list of moma pools to distribute and claim MOMA * @param suppliers Whether or not to distribute MOMA earned by supplying * @param borrowers Whether or not to distribute MOMA earned by borrowing */ function dclaim(MomaPool[] memory pools, bool suppliers, bool borrowers) public { distribute(msg.sender, pools, suppliers, borrowers); claim(msg.sender); } /** * @notice Distribute all the MOMA accrued to user in all markets of all pools and claim * @param suppliers Whether or not to distribute MOMA earned by supplying * @param borrowers Whether or not to distribute MOMA earned by borrowing */ function dclaim(bool suppliers, bool borrowers) public { distribute(msg.sender, momaPools, suppliers, borrowers); claim(msg.sender); } /** * @notice Claim all the MOMA have been distributed to user */ function claim() public { claim(msg.sender); } /*** View Functions ***/ /** * @notice Calculate the speed of a moma market * @param pool The moma pool to calculate speed * @param mToken The moma market to calculate speed * @return The mama market speed */ function getMarketSpeed(address pool, address mToken) public view returns (uint) { if (momaTotalWeight == 0) return 0; return div_(mul_(momaSpeed, marketStates[pool][mToken].weight), momaTotalWeight); } /** * @notice Return all of the moma pools * @dev The automatic getter may be used to access an individual pool * @return The list of pool addresses */ function getAllMomaPools() public view returns (MomaPool[] memory) { return momaPools; } /** * @notice Return the total number of moma pools * @return The number of mama pools */ function getMomaPoolNum() public view returns (uint) { return momaPools.length; } /** * @notice Return all of the moma markets of the specified pool * @dev The automatic getter may be used to access an individual market * @param pool The moma pool to get moma markets * @return The list of market addresses */ function getMomaMarkets(address pool) public view returns (MToken[] memory) { return momaMarkets[pool]; } /** * @notice Return the total number of moma markets of all pools * @return The number of total mama markets */ function getMomaMarketNum() public view returns (uint num) { for (uint i = 0; i < momaPools.length; i++) { num += momaMarkets[address(momaPools[i])].length; } } /** * @notice Weather this is a moma market * @param pool The moma pool of this market * @param mToken The moma market to ask * @return true or false */ function isMomaMarket(address pool, address mToken) public view returns (bool) { return marketStates[pool][mToken].isMomaMarket; } function isLendingPool(address pool) public view returns (bool) { return factory.isLendingPool(pool); } /** * @notice Calculate undistributed MOMA accrued by the user in specified market of specified pool * @param user The address to calculate MOMA for * @param pool The moma pool to calculate MOMA * @param mToken The market to calculate MOMA * @param suppliers Whether or not to calculate MOMA earned by supplying * @param borrowers Whether or not to calculate MOMA earned by borrowing * @return The amount of undistributed MOMA of this user */ function undistributed(address user, address pool, MToken mToken, bool suppliers, bool borrowers) public view returns (uint) { uint accrued; uint _index; MarketState storage state = marketStates[pool][address(mToken)]; if (suppliers == true) { if (state.weight > 0) { // momaTotalWeight > 0 (_index, ) = newMarketSupplyStateInternal(pool, mToken); } else { _index = state.supplyIndex; } if (_index > state.supplierIndex[user]) { (, accrued) = newSupplierMomaInternal(pool, mToken, user, Double({mantissa: _index})); } } if (borrowers == true && isMomaLendingPool[pool] == true) { uint marketBorrowIndex = mToken.borrowIndex(); if (marketBorrowIndex > 0) { if (state.weight > 0) { // momaTotalWeight > 0 (_index, ) = newMarketBorrowStateInternal(pool, mToken, marketBorrowIndex); } else { _index = state.borrowIndex; } if (_index > state.borrowerIndex[user]) { (, uint _borrowerDelta) = newBorrowerMomaInternal(pool, mToken, user, marketBorrowIndex, Double({mantissa: _index})); accrued = add_(accrued, _borrowerDelta); } } } return accrued; } /** * @notice Calculate undistributed MOMA accrued by the user in all markets of specified pool * @param user The address to calculate MOMA for * @param pool The moma pool to calculate MOMA * @param suppliers Whether or not to calculate MOMA earned by supplying * @param borrowers Whether or not to calculate MOMA earned by borrowing * @return The amount of undistributed MOMA of this user in each market */ function undistributed(address user, address pool, bool suppliers, bool borrowers) public view returns (uint[] memory) { MToken[] memory mTokens = momaMarkets[pool]; uint[] memory accrued = new uint[](mTokens.length); for (uint i = 0; i < mTokens.length; i++) { accrued[i] = undistributed(user, pool, mTokens[i], suppliers, borrowers); } return accrued; } /*** Admin Functions ***/ /** * @notice Set the new admin address * @param newAdmin The new admin address */ function _setAdmin(address newAdmin) external { require(msg.sender == admin && newAdmin != address(0), 'MomaFarming: admin check'); address oldAdmin = admin; admin = newAdmin; emit NewAdmin(oldAdmin, newAdmin); } /** * @notice Set the new factory contract * @param newFactory The new factory contract address */ function _setFactory(MomaFactoryInterface newFactory) external { require(msg.sender == admin && address(newFactory) != address(0), 'MomaFarming: admin check'); require(newFactory.isMomaFactory(), 'MomaFarming: not moma factory'); MomaFactoryInterface oldFactory = factory; factory = newFactory; emit NewFactory(oldFactory, newFactory); } /** * @notice Update state for all MOMA markets of all pools * @dev Note: Be careful of gas spending! */ function updateAllMomaMarkets() public { for (uint i = 0; i < momaPools.length; i++) { address pool = address(momaPools[i]); MToken[] memory mTokens = momaMarkets[pool]; for (uint j = 0; j < mTokens.length; j++) { MToken mToken = mTokens[j]; updateMarketSupplyStateInternal(pool, mToken); if (isMomaLendingPool[pool] == true) { uint borrowIndex = mToken.borrowIndex(); updateMarketBorrowStateInternal(pool, mToken, borrowIndex); } } } } /** * @notice Set the new momaSpeed for all MOMA markets of all pools * @dev Note: can call at any time, but must update state of all moma markets first * @param newMomaSpeed The new momaSpeed */ function _setMomaSpeed(uint newMomaSpeed) public { require(msg.sender == admin, 'MomaFarming: admin check'); // Update state for all MOMA markets of all pools updateAllMomaMarkets(); uint oldMomaSpeed = momaSpeed; momaSpeed = newMomaSpeed; emit NewMomaSpeed(oldMomaSpeed, newMomaSpeed); } /** * @notice Set MOMA markets' weight, will also mark as MOMA market in the first time * @dev Note: can call at any time, but must update state of all moma markets first * @param pool The address of the pool * @param mTokens The markets to set weigh * @param newWeights The new weights, 0 means no new MOMA farm */ function _setMarketsWeight(address payable pool, MToken[] memory mTokens, uint[] memory newWeights) public { require(msg.sender == admin, 'MomaFarming: admin check'); require(factory.isMomaPool(pool), 'MomaFarming: not moma pool'); require(mTokens.length == newWeights.length, "MomaFarming: param length dismatch"); // Update state for all MOMA markets of all pools updateAllMomaMarkets(); uint oldWeightTotal; uint newWeightTotal; uint blockNumber = getBlockNumber(); // Update state for all MOMA markets to be setted for (uint i = 0; i < mTokens.length; i++) { MToken mToken = mTokens[i]; MarketState storage state = marketStates[pool][address(mToken)]; // add this market to momaMarkets if first set if (!state.isMomaMarket) { (bool isListed, ) = MomaMasterV1Storage(pool).markets(address(mToken)); require(isListed == true, "market is not listed"); state.isMomaMarket = true; momaMarkets[pool].push(mToken); emit NewMomaMarket(pool, mToken); // set initial index of this market state.supplyIndex = momaInitialIndex; state.borrowIndex = momaInitialIndex; } uint oldWeight = state.weight; oldWeightTotal = add_(oldWeightTotal, oldWeight); newWeightTotal = add_(newWeightTotal, newWeights[i]); // update weight and block of this market state.weight = newWeights[i]; state.supplyBlock = blockNumber; state.borrowBlock = blockNumber; emit NewMarketWeight(pool, mToken, oldWeight, newWeights[i]); } uint oldMomaTotalWeight = momaTotalWeight; // update momaTotalWeight momaTotalWeight = add_(sub_(momaTotalWeight, oldWeightTotal), newWeightTotal); emit NewTotalWeight(oldMomaTotalWeight, momaTotalWeight); // add this pool to momaPools if first set if (!isMomaPool[pool]) { isMomaPool[pool] = true; momaPools.push(MomaPool(pool)); emit NewMomaPool(pool); // mark to lending pool if (isLendingPool(pool)) isMomaLendingPool[pool] = true; } } /** * @notice Transfer MOMA to the recipient * @dev Note: If there is not enough MOMA, we do not perform the transfer * @param recipient The address of the recipient to transfer MOMA to * @param amount The amount of MOMA to (possibly) transfer */ function _grantMoma(address recipient, uint amount) public { require(msg.sender == admin, 'MomaFarming: only admin can grant token'); uint notTransfered = grantMomaInternal(recipient, amount); require(notTransfered == 0, 'MomaFarming: insufficient MOMA for grant'); emit MomaGranted(recipient, amount); } function getBlockNumber() public view returns (uint) { return block.number; } }
Transfer MOMA to the user Note: If there is not enough MOMA, will do not perform the transfer user The address of the user to transfer MOMA to amount The amount of token to (possibly) transfer return The amount of token which was NOT transferred to the user/
function grantMomaInternal(address user, uint amount) internal returns (uint) { uint remaining = moma.balanceOf(address(this)); if (amount > 0 && amount <= remaining) { moma.transfer(user, amount); return 0; } return amount; }
12,691,511
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "./base/Controllable.sol"; import "sol-temple/src/tokens/ERC721.sol"; import "sol-temple/src/tokens/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @title Ape Runners RUN /// @author naomsa <https://twitter.com/naomsa666> contract ApeRunnersRUN is Ownable, Pausable, Controllable, ERC20("Ape Runners", "RUN", 18, "1") { /* -------------------------------------------------------------------------- */ /* Airdrop Details */ /* -------------------------------------------------------------------------- */ /// @notice Ape Runners contract. ERC721 public immutable apeRunners; /// @notice Ape Runner id => claimed airdrop. mapping(uint256 => bool) public airdroped; constructor(address newApeRunners) { apeRunners = ERC721(newApeRunners); } /* -------------------------------------------------------------------------- */ /* Airdrop Logic */ /* -------------------------------------------------------------------------- */ /// @notice Claim pending airdrop for each Ape Runner. /// @param ids Ape Runner token ids to claim airdrop. function claim(uint256[] memory ids) external { uint256 pending; for (uint256 i; i < ids.length; i++) { require(apeRunners.ownerOf(ids[i]) == msg.sender, "Not the token owner"); require(!airdroped[ids[i]], "Airdrop already claimed"); airdroped[ids[i]] = true; pending += 150 ether; } super._mint(msg.sender, pending); } /* -------------------------------------------------------------------------- */ /* Owner Logic */ /* -------------------------------------------------------------------------- */ /// @notice Add or edit contract controllers. /// @param addrs Array of addresses to be added/edited. /// @param state New controller state of addresses. function setControllers(address[] calldata addrs, bool state) external onlyOwner { for (uint256 i; i < addrs.length; i++) super._setController(addrs[i], state); } /// @notice Switch the contract paused state between paused and unpaused. function togglePaused() external onlyOwner { if (paused()) _unpause(); else _pause(); } /* -------------------------------------------------------------------------- */ /* ERC-20 Logic */ /* -------------------------------------------------------------------------- */ /// @notice Mint tokens. /// @param to Address to get tokens minted to. /// @param value Number of tokens to be minted. function mint(address to, uint256 value) external onlyController { super._mint(to, value); } /// @notice Burn tokens. /// @param from Address to get tokens burned from. /// @param value Number of tokens to be burned. function burn(address from, uint256 value) external onlyController { super._burn(from, value); } /// @notice See {ERC20-_beforeTokenTransfer}. /// @dev Overriden to block transactions while the contract is paused (avoiding bugs). function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override whenNotPaused { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /// @title Controllable abstract contract Controllable { /// @notice address => is controller. mapping(address => bool) private _isController; /// @notice Require the caller to be a controller. modifier onlyController() { require( _isController[msg.sender], "Controllable: Caller is not a controller" ); _; } /// @notice Check if `addr` is a controller. function isController(address addr) public view returns (bool) { return _isController[addr]; } /// @notice Set the `addr` controller status to `status`. function _setController(address addr, bool status) internal { _isController[addr] = status; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /// @title ERC721 /// @author naomsa <https://twitter.com/naomsa666> /// @notice A complete ERC721 implementation including metadata and enumerable /// functions. Completely gas optimized and extensible. abstract contract ERC721 is IERC165, IERC721, IERC721Metadata, IERC721Enumerable { /* _ _ */ /* ( )_ ( )_ */ /* ___ | ,_) _ _ | ,_) __ */ /* /',__)| | /'__` )| | /'__`\ */ /* \__, \| |_ ( (_| || |_ ( ___/ */ /* (____/`\__)`\__,_)`\__)`\____) */ /// @notice See {ERC721Metadata-name}. string public name; /// @notice See {ERC721Metadata-symbol}. string public symbol; /// @notice See {ERC721Enumerable-totalSupply}. uint256 public totalSupply; /// @notice Array of all owners. mapping(uint256 => address) private _owners; /// @notice Mapping of all balances. mapping(address => uint256) private _balanceOf; /// @notice Mapping from token Id to it's approved address. mapping(uint256 => address) private _tokenApprovals; /// @notice Mapping of approvals between owner and operator. mapping(address => mapping(address => bool)) private _isApprovedForAll; /* _ */ /* (_ ) _ */ /* | | _ __ (_) ___ */ /* | | /'_`\ /'_ `\| | /'___) */ /* | | ( (_) )( (_) || |( (___ */ /* (___)`\___/'`\__ |(_)`\____) */ /* ( )_) | */ /* \___/' */ /// @dev Set token's name and symbol. constructor(string memory name_, string memory symbol_) { name = name_; symbol = symbol_; } /// @notice See {ERC721-balanceOf}. function balanceOf(address account_) public view virtual returns (uint256) { require(account_ != address(0), "ERC721: balance query for the zero address"); return _balanceOf[account_]; } /// @notice See {ERC721-ownerOf}. function ownerOf(uint256 tokenId_) public view virtual returns (address) { require(_exists(tokenId_), "ERC721: query for nonexistent token"); address owner = _owners[tokenId_]; return owner; } /// @notice See {ERC721Metadata-tokenURI}. function tokenURI(uint256) public view virtual returns (string memory); /// @notice See {ERC721-approve}. function approve(address to_, uint256 tokenId_) public virtual { address owner = ownerOf(tokenId_); require(to_ != owner, "ERC721: approval to current owner"); require( msg.sender == owner || _isApprovedForAll[owner][msg.sender], "ERC721: caller is not owner nor approved for all" ); _approve(to_, tokenId_); } /// @notice See {ERC721-getApproved}. function getApproved(uint256 tokenId_) public view virtual returns (address) { require(_exists(tokenId_), "ERC721: query for nonexistent token"); return _tokenApprovals[tokenId_]; } /// @notice See {ERC721-setApprovalForAll}. function setApprovalForAll(address operator_, bool approved_) public virtual { _setApprovalForAll(msg.sender, operator_, approved_); } /// @notice See {ERC721-isApprovedForAll}. function isApprovedForAll(address account_, address operator_) public view virtual returns (bool) { return _isApprovedForAll[account_][operator_]; } /// @notice See {ERC721-transferFrom}. function transferFrom( address from_, address to_, uint256 tokenId_ ) public virtual { require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721: transfer caller is not owner nor approved"); _transfer(from_, to_, tokenId_); } /// @notice See {ERC721-safeTransferFrom}. function safeTransferFrom( address from_, address to_, uint256 tokenId_ ) public virtual { safeTransferFrom(from_, to_, tokenId_, ""); } /// @notice See {ERC721-safeTransferFrom}. function safeTransferFrom( address from_, address to_, uint256 tokenId_, bytes memory data_ ) public virtual { require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from_, to_, tokenId_, data_); } /// @notice See {ERC721Enumerable.tokenOfOwnerByIndex}. function tokenOfOwnerByIndex(address account_, uint256 index_) public view returns (uint256 tokenId) { require(index_ < balanceOf(account_), "ERC721Enumerable: Index out of bounds"); uint256 count; for (uint256 i; i < totalSupply; ++i) { if (account_ == _owners[i]) { if (count == index_) return i; else count++; } } revert("ERC721Enumerable: Index out of bounds"); } /// @notice See {ERC721Enumerable.tokenByIndex}. function tokenByIndex(uint256 index_) public view virtual returns (uint256) { require(index_ < totalSupply, "ERC721Enumerable: Index out of bounds"); return index_; } /// @notice Returns a list of all token Ids owned by `owner`. function walletOfOwner(address account_) public view returns (uint256[] memory) { uint256 balance = balanceOf(account_); uint256[] memory ids = new uint256[](balance); for (uint256 i = 0; i < balance; i++) ids[i] = tokenOfOwnerByIndex(account_, i); return ids; } /* _ _ */ /* _ ( )_ (_ ) */ /* (_) ___ | ,_) __ _ __ ___ _ _ | | */ /* | |/' _ `\| | /'__`\( '__)/' _ `\ /'__` ) | | */ /* | || ( ) || |_ ( ___/| | | ( ) |( (_| | | | */ /* (_)(_) (_)`\__)`\____)(_) (_) (_)`\__,_)(___) */ /// @notice 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. function _safeTransfer( address from_, address to_, uint256 tokenId_, bytes memory data_ ) internal virtual { _transfer(from_, to_, tokenId_); _checkOnERC721Received(from_, to_, tokenId_, data_); } /// @notice Returns whether `tokenId_` exists. function _exists(uint256 tokenId_) internal view virtual returns (bool) { return tokenId_ < totalSupply && _owners[tokenId_] != address(0); } /// @notice Returns whether `spender_` is allowed to manage `tokenId`. function _isApprovedOrOwner(address spender_, uint256 tokenId_) internal view virtual returns (bool) { require(_exists(tokenId_), "ERC721: query for nonexistent token"); address owner = _owners[tokenId_]; return (spender_ == owner || getApproved(tokenId_) == spender_ || isApprovedForAll(owner, spender_)); } /// @notice Safely mints `tokenId_` and transfers it to `to`. function _safeMint(address to_, uint256 tokenId_) internal virtual { _safeMint(to_, tokenId_, ""); } /// @notice Same as {_safeMint}, but with an additional `data_` parameter which is /// forwarded in {ERC721Receiver-onERC721Received} to contract recipients. function _safeMint( address to_, uint256 tokenId_, bytes memory data_ ) internal virtual { _mint(to_, tokenId_); _checkOnERC721Received(address(0), to_, tokenId_, data_); } /// @notice Mints `tokenId_` and transfers it to `to_`. function _mint(address to_, uint256 tokenId_) internal virtual { require(!_exists(tokenId_), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to_, tokenId_); _owners[tokenId_] = to_; totalSupply++; unchecked { _balanceOf[to_]++; } emit Transfer(address(0), to_, tokenId_); _afterTokenTransfer(address(0), to_, tokenId_); } /// @notice Destroys `tokenId`. The approval is cleared when the token is burned. function _burn(uint256 tokenId_) internal virtual { address owner = ownerOf(tokenId_); _beforeTokenTransfer(owner, address(0), tokenId_); // Clear approvals _approve(address(0), tokenId_); totalSupply--; _balanceOf[owner]--; delete _owners[tokenId_]; emit Transfer(owner, address(0), tokenId_); _afterTokenTransfer(owner, address(0), tokenId_); } /// @notice Transfers `tokenId_` from `from_` to `to`. function _transfer( address from_, address to_, uint256 tokenId_ ) internal virtual { require(_owners[tokenId_] == from_, "ERC721: transfer of token that is not own"); _beforeTokenTransfer(from_, to_, tokenId_); // Clear approvals from the previous owner _approve(address(0), tokenId_); _owners[tokenId_] = to_; unchecked { _balanceOf[from_]--; _balanceOf[to_]++; } emit Transfer(from_, to_, tokenId_); _afterTokenTransfer(from_, to_, tokenId_); } /// @notice Approve `to_` to operate on `tokenId_` function _approve(address to_, uint256 tokenId_) internal virtual { _tokenApprovals[tokenId_] = to_; emit Approval(_owners[tokenId_], to_, tokenId_); } /// @notice Approve `operator_` to operate on all of `account_` tokens. function _setApprovalForAll( address account_, address operator_, bool approved_ ) internal virtual { require(account_ != operator_, "ERC721: approve to caller"); _isApprovedForAll[account_][operator_] = approved_; emit ApprovalForAll(account_, operator_, approved_); } /// @notice ERC721Receiver callback checking and calling helper. function _checkOnERC721Received( address from_, address to_, uint256 tokenId_, bytes memory data_ ) private { if (to_.code.length > 0) { try IERC721Receiver(to_).onERC721Received(msg.sender, from_, tokenId_, data_) returns (bytes4 returned) { require(returned == 0x150b7a02, "ERC721: safe transfer to non ERC721Receiver implementation"); } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: safe transfer to non ERC721Receiver implementation"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } } /// @notice Hook that is called before any token transfer. function _beforeTokenTransfer( address from_, address to_, uint256 tokenId_ ) internal virtual {} /// @notice Hook that is called after any token transfer. function _afterTokenTransfer( address from_, address to_, uint256 tokenId_ ) internal virtual {} /* ___ _ _ _ _ __ _ __ */ /* /',__)( ) ( )( '_`\ /'__`\( '__) */ /* \__, \| (_) || (_) )( ___/| | */ /* (____/`\___/'| ,__/'`\____)(_) */ /* | | */ /* (_) */ /// @notice See {ERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId_) public view virtual returns (bool) { return interfaceId_ == type(IERC721).interfaceId || // ERC721 interfaceId_ == type(IERC721Metadata).interfaceId || // ERC721Metadata interfaceId_ == type(IERC721Enumerable).interfaceId || // ERC721Enumerable interfaceId_ == type(IERC165).interfaceId; // ERC165 } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; /** * @title ERC20 * @author naomsa <https://twitter.com/naomsa666> * @notice A complete ERC20 implementation including EIP-2612 permit feature. * Inspired by Solmate's ERC20, aiming at efficiency. */ abstract contract ERC20 is IERC20 { /* _ _ */ /* ( )_ ( )_ */ /* ___ | ,_) _ _ | ,_) __ */ /* /',__)| | /'_` )| | /'__`\ */ /* \__, \| |_ ( (_| || |_ ( ___/ */ /* (____/`\__)`\__,_)`\__)`\____) */ /// @notice See {ERC20-name}. string public name; /// @notice See {ERC20-symbol}. string public symbol; /// @notice See {ERC20-decimals}. uint8 public immutable decimals; /// @notice Used to hash the Domain Separator. string public version; /// @notice See {ERC20-totalSupply}. uint256 public totalSupply; /// @notice See {ERC20-balanceOf}. mapping(address => uint256) public balanceOf; /// @notice See {ERC20-allowance}. mapping(address => mapping(address => uint256)) public allowance; /// @notice See {ERC2612-nonces}. mapping(address => uint256) public nonces; /* _ */ /* (_ ) _ */ /* | | _ __ (_) ___ */ /* | | /'_`\ /'_ `\| | /'___) */ /* | | ( (_) )( (_) || |( (___ */ /* (___)`\___/'`\__ |(_)`\____) */ /* ( )_) | */ /* \___/' */ constructor( string memory name_, string memory symbol_, uint8 decimals_, string memory version_ ) { name = name_; symbol = symbol_; decimals = decimals_; version = version_; } /// @notice See {ERC20-transfer}. function transfer(address to_, uint256 value_) public returns (bool) { _transfer(msg.sender, to_, value_); return true; } /// @notice See {ERC20-transferFrom}. function transferFrom( address from_, address to_, uint256 value_ ) public returns (bool) { uint256 allowed = allowance[from_][msg.sender]; require(allowed >= value_, "ERC20: allowance exceeds transfer value"); if (allowed != type(uint256).max) allowance[from_][msg.sender] -= value_; _transfer(from_, to_, value_); return true; } /// @notice See {ERC20-approve}. function approve(address spender_, uint256 value_) public returns (bool) { _approve(msg.sender, spender_, value_); return true; } /// @notice See {ERC2612-DOMAIN_SEPARATOR}. function DOMAIN_SEPARATOR() public view returns (bytes32) { return _hashEIP712Domain(name, version, block.chainid, address(this)); } /// @notice See {ERC2612-permit}. function permit( address owner_, address spender_, uint256 value_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_ ) public { require(deadline_ >= block.timestamp, "ERC20: expired permit deadline"); // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)") bytes32 digest = _hashEIP712Message( DOMAIN_SEPARATOR(), keccak256( abi.encode( 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9, owner_, spender_, value_, nonces[owner_]++, deadline_ ) ) ); address signer = ecrecover(digest, v_, r_, s_); require(signer != address(0) && signer == owner_, "ERC20: invalid signature"); _approve(owner_, spender_, value_); } /* _ _ */ /* _ ( )_ (_ ) */ /* (_) ___ | ,_) __ _ __ ___ _ _ | | */ /* | |/' _ `\| | /'__`\( '__)/' _ `\ /'_` ) | | */ /* | || ( ) || |_ ( ___/| | | ( ) |( (_| | | | */ /* (_)(_) (_)`\__)`\____)(_) (_) (_)`\__,_)(___) */ /// @notice Internal transfer helper. Throws if `value_` exceeds `from_` balance. function _transfer( address from_, address to_, uint256 value_ ) internal { require(balanceOf[from_] >= value_, "ERC20: insufficient balance"); _beforeTokenTransfer(from_, to_, value_); unchecked { balanceOf[from_] -= value_; balanceOf[to_] += value_; } emit Transfer(from_, to_, value_); _afterTokenTransfer(from_, to_, value_); } /// @notice Internal approve helper. function _approve( address owner_, address spender_, uint256 value_ ) internal { allowance[owner_][spender_] = value_; emit Approval(owner_, spender_, value_); } /// @notice Internal minting logic. function _mint(address to_, uint256 value_) internal { _beforeTokenTransfer(address(0), to_, value_); totalSupply += value_; unchecked { balanceOf[to_] += value_; } emit Transfer(address(0), to_, value_); _afterTokenTransfer(address(0), to_, value_); } /// @notice Internal burning logic. function _burn(address from_, uint256 value_) internal { _beforeTokenTransfer(from_, address(0), value_); require(balanceOf[from_] >= value_, "ERC20: burn value exceeds balance"); unchecked { balanceOf[from_] -= value_; totalSupply -= value_; } emit Transfer(from_, address(0), value_); _afterTokenTransfer(from_, address(0), value_); } /** * @notice EIP721 domain hashing helper. * @dev Modified from https://github.com/0xProject/0x-monorepo/blob/development/contracts/utils/contracts/src/LibEIP712.sol */ function _hashEIP712Domain( string memory name_, string memory version_, uint256 chainId_, address verifyingContract_ ) private pure returns (bytes32) { bytes32 result; assembly { // Calculate hashes of dynamic data let nameHash := keccak256(add(name_, 32), mload(name_)) let versionHash := keccak256(add(version_, 32), mload(version_)) // Load free memory pointer let memPtr := mload(64) // Store params in memory mstore(memPtr, 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f) mstore(add(memPtr, 32), nameHash) mstore(add(memPtr, 64), versionHash) mstore(add(memPtr, 96), chainId_) mstore(add(memPtr, 128), verifyingContract_) // Compute hash result := keccak256(memPtr, 160) } return result; } /** * @notice EIP721 typed message hashing helper. * @dev Modified from https://github.com/0xProject/0x-monorepo/blob/development/contracts/utils/contracts/src/LibEIP712.sol */ function _hashEIP712Message(bytes32 domainSeparator_, bytes32 hash_) private pure returns (bytes32) { bytes32 result; assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), domainSeparator_) // EIP712 domain hash mstore(add(memPtr, 34), hash_) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } function _beforeTokenTransfer( address from, address to, uint256 value ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 value ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
See {ERC721Enumerable.tokenByIndex}.
function tokenByIndex(uint256 index_) public view virtual returns (uint256) { require(index_ < totalSupply, "ERC721Enumerable: Index out of bounds"); return index_; }
13,632,914
./partial_match/1/0x420D08Dad4fcd7896500d5E183D8BA934c919220/sources/EaselyFixedCollection.sol
Hash that the owner or alternate wallet must sign to enable a {mintAllow} for a user return Hash of message prefix and order hash per Ethereum format/
function _hashForAllowList( address allowedAddress, uint256 nonce, uint256 version, uint256 price, uint256 amount ) internal view returns (bytes32) { return keccak256(abi.encode(address(this), block.chainid, owner(), allowedAddress, nonce, version, price, amount)); }
2,825,429
./partial_match/1/0xfdB5Dee856A2709F9D356ABb6A38c391c6eBCe6C/sources/CountdownGriefingEscrow_Factory.sol
Deposit Stake. - tokens (ERC-20) are transfered from the caller and requires approval of this contract for appropriate amount. - if buyer already deposited the payment, finalize the escrow. Access Control: buyer OR operator State Machine: before finalize() OR before cancel() restrict access control restrict state machine deposit stake
function depositStake() public { require(isSeller(msg.sender) || Operated.isOperator(msg.sender), "only seller or operator"); require(_data.seller != address(0), "seller not yet set"); _depositStake(); }
4,386,929
// SPDX-License-Identifier: MIT // /** Babas is Babas */ // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC721/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}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _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); } } pragma solidity >=0.7.0 <0.9.0; contract Babas is ERC721Enumerable, Ownable { using Strings for uint256; string baseURI; string public baseExtension = ".json"; uint256 public cost = 0.03 ether; uint256 public maxSupply = 5000; uint256 public maxMintAmount = 20; bool public paused = true; bool public revealed = true; string public notRevealedUri; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= maxSupply); if (msg.sender != owner()) { require(msg.value >= cost * _mintAmount); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //only owner function reveal() public onlyOwner() { revealed = true; } function setCost(uint256 _newCost) public onlyOwner() { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner() { maxMintAmount = _newmaxMintAmount; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function pause(bool _state) public onlyOwner { paused = _state; } function withdraw() public payable onlyOwner { (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); require(success); } }
Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./
interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); Babas is Babas pragma solidity ^0.8.0; }
1,435,679
// SPDX-License-Identifier: MIT // Sources flattened with hardhat v2.6.1 https://hardhat.org // File @openzeppelin/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File @openzeppelin/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/utils/cryptography/[email protected] pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // File contracts/CryptoCrooks.sol pragma solidity ^0.8.0; contract CryptoCrooks is ERC721, ERC721Enumerable, Ownable { string public LICENSE_TEXT = "ALL RIGHTS TO TOKEN HOLDER"; string public CROOKS_PROVENANCE = ""; // IPFS URL WILL BE ADDED WHEN CROOKS ARE REVEALED string public nftBaseURI = ""; bool licenseLocked = false; // TEAM CAN'T EDIT THE LICENSE AFTER THIS GETS TRUE bool public saleIsActive = false; bool public preSaleIsActive = false; bytes32 public merkleTreeRoot; mapping(uint => string) public crookNames; // Custom names mapping(uint => string) public crookScenes; // Provenanced Scenes mapping(address => bool) public hasClaimed; // Has user claimed presale? // Address to transfer Fund fees to upon minting address payable public daoVaultAddress = payable(0x54Bc506b4EB3570522c062539b35E5b61853AbEc); uint public constant MAX_CROOKS = 5000; uint public constant maxCrookPurchase = 10; uint public constant daoShare = 80; // in %, Percentage of minting fee thats being payed to DAO on minting uint public crookReserve = 500; // Reserve 500 Crooks for team - Giveaways/Prizes etc uint public crookPresaleReserve = 250; // Reserve 250 Crooks for minting @ discount during presale phase uint256 public constant crookPrice = 80000000000000000; // 0.08 ETH uint256 public constant crookPresalePrice = 50000000000000000; // 0.05 ETH uint256 public constant changeCrookNamePrice = 10000000000000000; // 0.01 ETH uint256 public constant changeCrookScenePrice = 10000000000000000;// 0.01 ETH event LicenseIsLocked(string _licenseText); event PreSaleActivated(bool isActive); event PreSaleClaimed(address _by, uint _amount); event SaleActivated(bool isActive); event MintNFT(address _by, uint _amount); event DaoVaultAddressChanged(address payable _to); event DaoVaultFunded(uint256 amount); event CrookNameChanged(address _by, uint _tokenId, string _name); event CrookSceneChanged(address _by, uint _tokenId, string _name); constructor( bytes32 _merkleTreeRoot, address payable _daoVaultAddress, string memory _nftBaseURI ) ERC721("CryptoCrooksDAO", "CROOK") { merkleTreeRoot = _merkleTreeRoot; daoVaultAddress = _daoVaultAddress; nftBaseURI = _nftBaseURI; } /** START ERC721Enumerable Overrides **/ function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } /** END ERC721Enumerable Overrides **/ /** START MerkleTree **/ // Checks if a user is part of presale whitelist (using pre-generated MerkleTree) function verify(uint256 _amount, bytes32[] memory _proof) public view returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(msg.sender, _amount)); return MerkleProof.verify(_proof, merkleTreeRoot, leaf); } /** END MerkleTree **/ /** Custom baseURI **/ function baseURI () public view returns (string memory _uri) { return _baseURI(); } function setBaseURI (string memory _uri) public onlyOwner { nftBaseURI = _uri; } function _baseURI() internal view override returns (string memory) { return nftBaseURI; } /** END Custom baseURI **/ function setDaoVaultAddress(address payable _daoVaultAddress) public onlyOwner { daoVaultAddress = _daoVaultAddress; emit DaoVaultAddressChanged(_daoVaultAddress); } function setProvenanceHash(string memory _provenanceHash) public onlyOwner { CROOKS_PROVENANCE = _provenanceHash; } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(owner()).transfer(balance); } function flipPreSaleState() public onlyOwner { preSaleIsActive = !preSaleIsActive; emit PreSaleActivated(preSaleIsActive); } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; preSaleIsActive = false; // End presale emit SaleActivated(saleIsActive); } function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = this.balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = super.tokenOfOwnerByIndex(_owner, index); } return result; } } // Returns the license for tokens function tokenLicense(uint _id) public view returns(string memory) { require(_id < this.totalSupply(), "Choose a crook within range"); return LICENSE_TEXT; } // Locks the license to prevent further changes function lockLicense() public onlyOwner { licenseLocked = true; emit LicenseIsLocked(LICENSE_TEXT); } // Change the license function changeLicense(string memory _license) public onlyOwner { require(licenseLocked == false, "License already locked"); LICENSE_TEXT = _license; } // Overwriting forwardFunds function because otherwise we get a failed gas estimation error function _forwardFunds(uint256 _amount) internal { // Call returns a boolean value indicating success or failure. // This is the current recommended method to use. (bool success,) = daoVaultAddress.call{value: _amount}(''); require(success, 'Failed to forward funds'); } function _mintLoop(address _to, uint256 _amountToMint) internal { for (uint i = 0; i < _amountToMint; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_CROOKS) { _safeMint(_to, mintIndex); } } } // Mints amount of Crooks to specified address, and pays its funding to the DAO function _mintNFT(uint _amount) internal { uint256 fundAmount = (msg.value / 100) * daoShare; // Calculate 80% of sent funds _forwardFunds(fundAmount); // Transfer to DAO Vault emit DaoVaultFunded(fundAmount); _mintLoop(msg.sender, _amount); } // TEAM RESERVE MINT function mintTeamReserveNFTs(uint _reserveAmount) public onlyOwner { mintTeamReserveNFTsToAddress(msg.sender, _reserveAmount); } function mintTeamReserveNFTsToAddress(address _address, uint _reserveAmount) public onlyOwner { require(_reserveAmount > 0 && _reserveAmount <= crookReserve, "Trying to claim illegal amount"); crookReserve = crookReserve - _reserveAmount; _mintLoop(_address, _reserveAmount); } // FOR WHITELISTED PRESALE USERS (= Mentioned in MerkleTree) function claimPreSaleNFT(uint256 _amount, bytes32[] memory _proof) public payable { require(preSaleIsActive, "Presale must be active to reserve Crooks"); // Checks if user is part of presale Merkle Tree require(verify(_amount, _proof), "You have no presale claim"); require(!hasClaimed[msg.sender], "You have already claimed"); require(_amount > 0, "You need to claim more than 0 Crooks"); require(crookPresaleReserve > 0, "All presale Crooks have been claimed"); require(crookPresaleReserve - _amount >= 0, "Not enough presale Crooks left"); require(msg.value >= _amount * crookPresalePrice, "Ether value sent is not sufficient"); hasClaimed[msg.sender] = true; crookPresaleReserve = crookPresaleReserve - _amount; // Mint and transfer part of sent funds to CryptoCrooks DAO Vault _mintNFT(_amount); emit PreSaleClaimed(msg.sender, _amount); } // REGULAR MINTING function mintNFT(uint _amount) public payable { require(saleIsActive, "Sale must be active to mint Crooks"); require(_amount > 0 && _amount <= maxCrookPurchase, "You can only mint 10 crooks per transaction"); require(totalSupply() + _amount <= MAX_CROOKS, "Purchase would exceed max supply of Crooks"); require(msg.value >= crookPrice * _amount, "Ether value sent is not sufficient"); // Mint and transfer part of sent funds to CryptoCrooks DAO Vault _mintNFT(_amount); emit MintNFT(msg.sender, _amount); } function changeCrookName(uint _tokenId, string memory _name) public payable { require(ownerOf(_tokenId) == msg.sender, "Your wallet doesn't own this crook"); require(msg.value >= changeCrookNamePrice, "Ether value sent is not sufficient"); require(sha256(bytes(_name)) != sha256(bytes(crookNames[_tokenId])), "New name is same as current one"); crookNames[_tokenId] = _name; emit CrookNameChanged(msg.sender, _tokenId, _name); } function changeCrookScene(uint _tokenId, string memory _scene) public payable { require(this.ownerOf(_tokenId) == msg.sender, "Your wallet doesn't own this crook"); require(msg.value >= changeCrookScenePrice, "Ether value sent is not sufficient"); require(sha256(bytes(_scene)) != sha256(bytes(crookScenes[_tokenId])), "New scene is same as current one"); crookScenes[_tokenId] = _scene; emit CrookSceneChanged(msg.sender, _tokenId, _scene); } function getCrookScene(uint _tokenId) public view returns( string memory){ require( _tokenId < this.totalSupply(), "Choose a crook within range" ); return crookScenes[_tokenId]; } function getCrookName(uint _tokenId) public view returns( string memory ){ require( _tokenId < this.totalSupply(), "Choose a crook within range" ); return crookNames[_tokenId]; } // GET ALL CROOKS OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH function crookNamesOfOwner(address _owner) external view returns(string[] memory ) { uint256 tokenCount = this.balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new string[](0); } else { string[] memory result = new string[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = crookNames[this.tokenOfOwnerByIndex(_owner, index)] ; } return result; } } }
Return an empty array
function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = this.balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = super.tokenOfOwnerByIndex(_owner, index); } return result; } }
9,963,886
// TODO: Remove this mock once Chainlink supports v0.8 mocks pragma solidity ^0.8.0; import './token/LinkERC20.sol'; import './ERC677Token.sol'; contract LinkToken is LinkERC20, ERC677Token { uint private constant TOTAL_SUPPLY = 10**27; string private constant NAME = 'ChainLink Token'; string private constant SYMBOL = 'LINK'; constructor() ERC20(NAME, SYMBOL) public { _onCreate(); } /** * @dev Hook that is called when this contract is created. * Useful to override constructor behaviour in child contracts (e.g., LINK bridge tokens). * @notice Default implementation mints 10**27 tokens to msg.sender */ function _onCreate() internal virtual { _mint(msg.sender, TOTAL_SUPPLY); } /** * @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 override virtual validAddress(recipient) { super._transfer(sender, recipient, 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 override virtual validAddress(spender) { super._approve(owner, spender, amount); } // MODIFIERS modifier validAddress(address _recipient) { require(_recipient != address(this), "LinkToken: transfer/approve to this contract address"); _; } }
Hook that is called when this contract is created. Useful to override constructor behaviour in child contracts (e.g., LINK bridge tokens). Default implementation mints 1027 tokens to msg.sender/
function _onCreate() internal virtual { _mint(msg.sender, TOTAL_SUPPLY); }
6,369,774
./partial_match/42/0xf567Bc19381aA04fB235B4ABBBC4a51ac175A233/sources/YAMDelegate.sol
who The address to query. return The balance of the specified address./
function balanceOf(address who) external view returns (uint256) { return _yamBalances[who].mul(yamsScalingFactor).div(internalDecimals); }
3,489,226
./partial_match/1/0x7894760FF403394fc9a85730fD411b12E901E093/sources/QualityDigital.sol
New function to control selling
function setSellEnabled(bool _sellEnabled) external onlyOwner {
4,405,279
./full_match/1/0xa691c1f85448B28106aF5302E4ACfD1373bF327a/sources/contracts/PoolStakingLock.sol
Withdraw pending AUTO
function harvest() external nonReentrant { UserInfo storage user = userInfo[msg.sender]; _updatePool(); require(payOrLockupPending(user), "Harvests locked"); _updateRewardDebt(user); }
17,158,270
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "./ERC721A_M.sol"; import "./meltable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/interfaces/IERC721.sol"; ///////////////////////////////////////////////////////////////////////////////////////////////////// // // // ooo ooooo .oooooo. .oooooo..o .o. ooooo .oooooo. .oooooo. // // `88. .888' d8P' `Y8b d8P' `Y8 .888. `888' d8P' `Y8b d8P' `Y8b // // 888b d'888 888 888 Y88bo. .8"888. 888 888 888 888 // // 8 Y88. .P 888 888 888 `"Y8888o. .8' `888. 888 888 888 888 // // 8 `888' 888 888 888 `"Y88b .88ooo8888. 888 888 888 888 // // 8 Y 888 `88b d88' oo .d8P .8' `888. 888 `88b ooo `88b d88' // // o8o o888o `Y8bood8P' 8""88888P' o88o o8888o o888o `Y8bood8P' `Y8bood8P' // // // ///////////////////////////////////////////////////////////////////////////////////////////////////// contract MosaicoBrasileiro is ERC721A_M, IERC721Receiver, Ownable, Meltable { /// ================================ /// ============ Errors ============ /// ================================ error NonexistentToken(); error AlreadyMinted(); error WrongNFT(); error NotMosaicOwner(); error NotOwnerOfAll(); error NotAuthorized(); /// ================================= /// ============ Storage ============ /// ================================= address private immutable mosaicNftAddress; address private immutable slicerAddress; string private baseURI; /// ===================================== /// ============ Constructor ============ /// ===================================== constructor( string memory baseURI_, address slicerAddress_, address mosaicNftAddress_ ) ERC721A_M("MosaicoBrasileiro2022", "MOSAICO") { baseURI = baseURI_; slicerAddress = slicerAddress_; mosaicNftAddress = mosaicNftAddress_; } /// =================================== /// ============ Functions ============ /// =================================== /** * @notice Mints the 16 NFTs to an address. * * @dev Can only be called if the NFTs haven't been minted yet */ function mint(address to) private { if (totalSupply() != 0) revert AlreadyMinted(); _safeMint(to, 16); } /** * @notice Burns the 16 NFTs and sends the mosaic NFT to the msg.sender. * * @dev Can only be called if the msg.sender owns all the 16 NFTs and this address owns the mosaic NFT. */ function melt() external { if (balanceOf(msg.sender) != 16) revert NotOwnerOfAll(); _burnAll(); IERC721(mosaicNftAddress).safeTransferFrom(address(this), msg.sender, 1); _currentIndex = 1; } /** * @notice Safeguard function to mint the entire collection to an address who transferred * the mosaic NFT using `transferFrom`, instead of `safeTransferFrom` or `claimToMint` * * @dev Can only be by contract owner */ function emergencyMint(address previousOwner) external onlyOwner { if (IERC721(mosaicNftAddress).balanceOf(address(this)) == 0) revert NotMosaicOwner(); mint(previousOwner); } /** * @notice Mints 16 NFTs to the sender, in exchange for storing the mosaic NFT. * * @dev NFT owner needs to have approved this contract address as operator for the mosaic contract. * @dev One of the two ways to claim the entire collection, the other one being calling safeTransferFrom. */ function sendAndMint() external { if (IERC721(mosaicNftAddress).balanceOf(msg.sender) == 0) revert NotMosaicOwner(); IERC721(mosaicNftAddress).safeTransferFrom(msg.sender, address(this), 1); } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. */ function _baseURI() internal view override returns (string memory) { return baseURI; } /** * @notice ERC-2981 implementation * * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) { if (!_exists(tokenId)) revert NonexistentToken(); return (slicerAddress, salePrice / 10); } /** * @notice Mints 16 nfts to the sender of the mosaic NFT. * * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address from, uint256 tokenId, bytes memory ) external virtual override returns (bytes4) { if (msg.sender != mosaicNftAddress) revert WrongNFT(); if (tokenId != 1) revert WrongNFT(); mint(from); return this.onERC721Received.selector; } }
Burns the 16 NFTs and sends the mosaic NFT to the msg.sender. Can only be called if the msg.sender owns all the 16 NFTs and this address owns the mosaic NFT./
function melt() external { if (balanceOf(msg.sender) != 16) revert NotOwnerOfAll(); _burnAll(); IERC721(mosaicNftAddress).safeTransferFrom(address(this), msg.sender, 1); _currentIndex = 1; }
12,622,373
pragma solidity 0.5.12; contract RelatorioDeHorasTrabalhadas { uint256 mes; uint256 ano; uint256 dia1; uint256 dia2; uint256 dia3; uint256 dia4; uint256 dia5; uint256 dia6; uint256 dia7; uint256 dia8; uint256 dia9; uint256 dia10; uint256 dia11; uint256 dia12; uint256 dia13; uint256 dia14; uint256 dia15; uint256 dia16; uint256 dia17; uint256 dia18; uint256 dia19; uint256 dia20; uint256 dia21; uint256 dia22; uint256 dia23; uint256 dia24; uint256 dia25; uint256 dia26; uint256 dia27; uint256 dia28; uint256 dia29; uint256 dia30; uint256 dia31; //não consegui declarar os 30 dias, como fazer? constructor ( uint256 mesAtual, uint256 anoAtual, uint256 _dia1, uint256 _dia2, uint256 _dia3, uint256 _dia4, uint256 _dia5, uint256 _dia6, uint256 _dia7, uint256 _dia8, uint256 _dia9, uint256 _dia10, uint256 _dia11, uint256 _dia12, uint256 _dia13, uint256 _dia14) public /*uint256 _dia11, uint256 _dia12, uint256 _dia13, uint256 _dia14, uint256 _dia15 ) public */ { mes=mesAtual; ano=anoAtual; dia1=_dia1; dia2=_dia2; dia3=_dia3; dia4=_dia4; dia5=_dia5; dia6=_dia6; dia7=_dia7; dia8=_dia8; dia9=_dia9; dia10=_dia10; dia11=_dia11; dia12=_dia12; dia13=_dia13; dia14=_dia14; } /* uint256 _dia16, uint256 _dia17, uint256 _dia18, uint256 _dia19, uint256 _dia20, uint256 _dia21, uint256 _dia22, uint256 _dia23, uint256 _dia24, uint256 _dia25, uint256 _dia26, uint256 _dia27, uint256 _dia28, uint256 _dia29, uint256 _dia30, uint256 _dia31) public function LancamentoDeDeHoras (uint256) public view returns (uint) { dia1; } */ function totalDeHorasTrabalhadas () public view returns (uint256 numeroDeHorasTrabalhadas) { numeroDeHorasTrabalhadas= dia1+dia2+dia3+dia4+dia5+dia6+dia7+dia8+dia9+dia10+dia11+dia12+dia13+dia14; return numeroDeHorasTrabalhadas; } } contract PrestacaoDeServicos { string public prestador; string public empresa; uint256 public valorHora; bool[] public statusPagamento; address payable contaPrestador; address contaEmpresa; bool public pago; bool public retirado; event pagamentoRealizado (uint valor); constructor ( string memory nomePrestador, string memory nomeEmpresa, uint256 valorHoraTrabalho, address payable ncontaprestador, address ncontaempresa ) public { // require para que o contrato seja limitado a no m´áximo 66.000 ether require (valorHoraTrabalho<=300, "O VALOR DA HORA ULTRAPASSOU O LIMITE"); prestador = nomePrestador; empresa = nomeEmpresa; valorHora = valorHoraTrabalho; contaPrestador = ncontaprestador; contaEmpresa = ncontaempresa; } function vigenciaContrato () public view returns (uint dataInicioContrato, uint dataFinalContrato) { dataInicioContrato = now; dataFinalContrato = dataInicioContrato+365 days; } //data vencimento mensal a cada 30 dias (queria todo o dia 10, mas n~ão consegui). Tentei então a cada 30 dias, mas também não consegui function dataVencimentoMensal () public view returns (uint dataVencimentoMensal, uint dataInicioContrato) { dataVencimentoMensal=dataInicioContrato+30 days; for (uint i=1; i>30; i++) dataVencimentoMensal=dataVencimentoMensal+30; } function saldoNoContrato () public view returns (uint) { return address(this).balance; } //DÚVIDA: o pagamento está sendo efetuado no contrato, como o prestador retira? Estou conseguindo pagar, mas fica no contrato e não aparece na conta do prestador. function efetuarPagamento() public payable { require (msg.sender == contaEmpresa, "SOMENTE EMPRESA PODE PAGAR"); contaPrestador.transfer(address(this).balance); statusPagamento.push(true); emit pagamentoRealizado(msg.value); } } contract RemuneracaoFinal is PrestacaoDeServicos, RelatorioDeHorasTrabalhadas { uint256 valorHora; uint256 remuneracaoFinal; uint256 numeroDeHorasTrabalhadas; constructor () public { uint256 numeroDeHorasTrabalhadas; uint256 remuneracaoFinal; } function calculoremuneracaoFinal () public view returns (uint remuneracaoFinal) { remuneracaoFinal=valorHora*numeroDeHorasTrabalhadas; //condiç~ão para a ter uma remuneraç~ão m´ínima de 1.000 ether if (remuneracaoFinal<1000) { remuneracaoFinal = 1000; return remuneracaoFinal; } } }
não consegui declarar os 30 dias, como fazer?
{ uint256 mes; uint256 ano; uint256 dia1; uint256 dia2; uint256 dia3; uint256 dia4; uint256 dia5; uint256 dia6; uint256 dia7; uint256 dia8; uint256 dia9; uint256 dia10; uint256 dia11; uint256 dia12; uint256 dia13; uint256 dia14; uint256 dia15; uint256 dia16; uint256 dia17; uint256 dia18; uint256 dia19; uint256 dia20; uint256 dia21; uint256 dia22; uint256 dia23; uint256 dia24; uint256 dia25; uint256 dia26; uint256 dia27; uint256 dia28; uint256 dia29; uint256 dia30; uint256 dia31; constructor ( uint256 mesAtual, uint256 anoAtual, uint256 _dia1, uint256 _dia2, uint256 _dia3, uint256 _dia4, uint256 _dia5, uint256 _dia6, uint256 _dia7, uint256 _dia8, uint256 _dia9, uint256 _dia10, uint256 _dia11, uint256 _dia12, uint256 _dia13, uint256 _dia14) public uint256 _dia12, uint256 _dia13, uint256 _dia14, uint256 _dia15 ) public { mes=mesAtual; ano=anoAtual; dia1=_dia1; dia2=_dia2; dia3=_dia3; dia4=_dia4; dia5=_dia5; dia6=_dia6; dia7=_dia7; dia8=_dia8; dia9=_dia9; dia10=_dia10; dia11=_dia11; dia12=_dia12; dia13=_dia13; dia14=_dia14; } uint256 _dia17, uint256 _dia18, uint256 _dia19, uint256 _dia20, uint256 _dia21, uint256 _dia22, uint256 _dia23, uint256 _dia24, uint256 _dia25, uint256 _dia26, uint256 _dia27, uint256 _dia28, uint256 _dia29, uint256 _dia30, uint256 _dia31) public uint256 _dia16, function LancamentoDeDeHoras (uint256) public view returns (uint) { dia1; } function totalDeHorasTrabalhadas () public view returns (uint256 numeroDeHorasTrabalhadas) { numeroDeHorasTrabalhadas= dia1+dia2+dia3+dia4+dia5+dia6+dia7+dia8+dia9+dia10+dia11+dia12+dia13+dia14; return numeroDeHorasTrabalhadas; } }
1,052,275
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; // dependencies import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import {Context} from "@openzeppelin/contracts/utils/Context.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // interfaces import {IPerpetual} from "./interfaces/IPerpetual.sol"; import {IVault} from "./interfaces/IVault.sol"; // libraries import {LibMath} from "./lib/LibMath.sol"; import {LibPerpetual} from "./lib/LibPerpetual.sol"; import {IncreOwnable} from "./utils/IncreOwnable.sol"; import {MockStableSwap} from "./mocks/MockStableSwap.sol"; import "hardhat/console.sol"; contract Perpetual is IPerpetual, Context, IncreOwnable { using SafeCast for uint256; using SafeCast for int256; // parameterization int256 constant MIN_MARGIN = 25e15; // 2.5% int256 constant LIQUIDATION_FEE = 60e15; // 6% int256 constant PRECISION = 10e18; // global state MockStableSwap private market; LibPerpetual.GlobalPosition private globalPosition; LibPerpetual.Price[] private prices; mapping(IVault => bool) private vaultInitialized; // user state mapping(address => LibPerpetual.TraderPosition) private userPosition; mapping(address => IVault) private vaultUsed; constructor(uint256 _vQuote, uint256 _vBase) { market = new MockStableSwap(_vQuote, _vBase); } // global getter function getStableSwap() public view returns (address) { return address(market); } function isVault(address vaultAddress) public view returns (bool) { return vaultInitialized[IVault(vaultAddress)]; } function getLatestPrice() public view override returns (LibPerpetual.Price memory) { return getPrice(prices.length - 1); } function getPrice(uint256 period) public view override returns (LibPerpetual.Price memory) { return prices[period]; } function getGlobalPosition() public view override returns (LibPerpetual.GlobalPosition memory) { return globalPosition; } // user getter function getVault(address account) public view override returns (IVault) { return vaultUsed[account]; } function getUserPosition(address account) public view override returns (LibPerpetual.TraderPosition memory) { return userPosition[account]; } // functions function setVault(address vaultAddress) public onlyOwner { IVault vault = IVault(vaultAddress); require(vaultInitialized[vault] == false, "Vault is already initialized"); vaultInitialized[vault] = true; emit VaultRegistered(vaultAddress); } function setPrice(LibPerpetual.Price memory newPrice) external override { prices.push(newPrice); } function _verifyAndSetVault(IVault vault) internal { require(vaultInitialized[vault], "Vault is not initialized"); IVault oldVault = vaultUsed[_msgSender()]; if (address(oldVault) == address(0)) { // create new vault vaultUsed[_msgSender()] = vault; emit VaultAssigned(_msgSender(), address(vault)); } else { // check uses same vault require(oldVault == vault, "Uses other vault"); } } /// @notice Deposits tokens into the vault. Note that a vault can support multiple collateral tokens. function deposit( uint256 amount, IVault vault, IERC20 token ) external override { _verifyAndSetVault(vault); vault.deposit(_msgSender(), amount, token); emit Deposit(_msgSender(), address(token), amount); } /// @notice Withdraw tokens from the vault. Note that a vault can support multiple collateral tokens. function withdraw(uint256 amount, IERC20 token) external override { require(getUserPosition(_msgSender()).notional == 0, "Has open position"); IVault vault = vaultUsed[_msgSender()]; vault.withdraw(_msgSender(), amount, token); emit Withdraw(_msgSender(), address(token), amount); } /// @notice Buys long Quote derivatives /// @param amount Amount of Quote tokens to be bought /// @dev No checks are done if bought amount exceeds allowance function openPosition(uint256 amount, LibPerpetual.Side direction) external override returns (uint256) { LibPerpetual.TraderPosition storage user = userPosition[_msgSender()]; LibPerpetual.GlobalPosition storage global = globalPosition; require(user.notional == 0, "Trader position is not allowed to have position open"); uint256 quoteBought = _openPosition(user, global, direction, amount); emit OpenPosition(_msgSender(), uint128(block.timestamp), direction, amount, quoteBought); return quoteBought; } function _openPosition( LibPerpetual.TraderPosition storage user, LibPerpetual.GlobalPosition storage global, LibPerpetual.Side direction, uint256 amount ) internal returns (uint256) { // buy derivative tokens user.side = direction; uint256 quoteBought = _openPositionOnMarket(amount, direction); // set trader position user.notional = amount.toInt256(); user.positionSize = quoteBought.toInt256(); user.profit = 0; user.timeStamp = global.timeStamp; user.cumFundingRate = global.cumFundingRate; return quoteBought; } function _openPositionOnMarket(uint256 amount, LibPerpetual.Side direction) internal returns (uint256) { uint256 quoteBought = 0; if (direction == LibPerpetual.Side.Long) { quoteBought = market.mintVBase(amount); } else if (direction == LibPerpetual.Side.Short) { quoteBought = market.burnVBase(amount); } return quoteBought; } /// @notice Closes position from account holder function closePosition() external override { LibPerpetual.TraderPosition storage user = userPosition[_msgSender()]; LibPerpetual.GlobalPosition storage global = globalPosition; // get information about position _closePosition(user, global); // apply changes to collateral IVault userVault = vaultUsed[_msgSender()]; userVault.settleProfit(_msgSender(), user.profit); } function _closePosition(LibPerpetual.TraderPosition storage user, LibPerpetual.GlobalPosition storage global) internal { uint256 amount = (user.positionSize).toUint256(); LibPerpetual.Side direction = user.side; // settle funding rate _settle(user, global); // sell derivative tokens uint256 quoteSold = _closePositionOnMarket(amount, direction); // set trader position user.profit += _calculatePnL(user.notional, quoteSold.toInt256()); user.notional = 0; user.positionSize = 0; } // get information about position function _calculatePnL(int256 boughtPrice, int256 soldPrice) internal pure returns (int256) { return soldPrice - boughtPrice; } /// notional sell derivative tokens on (external) market function _closePositionOnMarket(uint256 amount, LibPerpetual.Side direction) internal returns (uint256) { uint256 quoteSold = 0; if (direction == LibPerpetual.Side.Long) { quoteSold = market.mintVQuote(amount); } else { quoteSold = market.burnVQuote(amount); } return quoteSold; } /// @notice Settle funding rate function settle(address account) public override { LibPerpetual.TraderPosition storage user = userPosition[account]; LibPerpetual.GlobalPosition storage global = globalPosition; _settle(user, global); } function _settle(LibPerpetual.TraderPosition storage user, LibPerpetual.GlobalPosition storage global) internal { if (user.notional != 0 && user.timeStamp < global.timeStamp) { // update user variables when position opened before last update int256 upcomingFundingPayment = getFundingPayments(user, global); _applyFundingPayment(user, upcomingFundingPayment); emit Settlement(_msgSender(), user.timeStamp, upcomingFundingPayment); } // update user variables to global state user.timeStamp = global.timeStamp; user.cumFundingRate = global.cumFundingRate; } /// @notice Apply funding payments function _applyFundingPayment(LibPerpetual.TraderPosition storage user, int256 payments) internal { user.profit += payments; } /// @notice Calculate missed funing payments function getFundingPayments(LibPerpetual.TraderPosition memory user, LibPerpetual.GlobalPosition memory global) public pure returns (int256) { /* Funding rates (as defined in our protocol) are paid from shorts to longs case 1: user is long => has missed receiving funding payments (positive or negative) case 2: user is short => has missed making funding payments (positive or negative) comment: Making an negative funding payment is equvalent to receiving a positive one. */ int256 upcomingFundingRate = 0; int256 upcomingFundingPayment = 0; if (user.cumFundingRate != global.cumFundingRate) { if (user.side == LibPerpetual.Side.Long) { upcomingFundingRate = global.cumFundingRate - user.cumFundingRate; } else { upcomingFundingRate = user.cumFundingRate - global.cumFundingRate; } upcomingFundingPayment = LibMath.mul(upcomingFundingRate, user.notional); } return upcomingFundingPayment; } function marginIsValid(address account) public view override returns (bool) { return marginRatio(account) <= MIN_MARGIN; } /// @notice Calculate the margin Ratio of some account function marginRatio(address account) public view override returns (int256) { LibPerpetual.TraderPosition memory user = getUserPosition(account); LibPerpetual.GlobalPosition memory global = getGlobalPosition(); IVault userVault = getVault(account); // calcuate margin ratio = = (margin + pnl + fundingPayments) / position.getNotional() int256 margin = userVault.getReserveValue(account); int256 fundingPayments = getFundingPayments(user, global); int256 unrealizedPnl = 0; /// toDO: requires implementation of curve pool; int256 profit = getUserPosition(account).profit; return LibMath.div(margin + unrealizedPnl + fundingPayments + profit, user.notional); } function liquidate(address account, IVault liquidatorVault) external { require(!marginIsValid(account), "Margin is not valid"); address liquidator = _msgSender(); // load information about state LibPerpetual.TraderPosition storage user = userPosition[account]; LibPerpetual.GlobalPosition storage global = globalPosition; int256 notionalAmount = user.notional; // get information about position _closePosition(user, global); // liquidation costs int256 liquidationFee = (notionalAmount * LIQUIDATION_FEE) / PRECISION; // profits - liquidationFee gets paid out int256 reducedProfit = user.profit - liquidationFee; // substract fee from user account IVault userVault = vaultUsed[account]; userVault.settleProfit(account, reducedProfit); // add fee to liquidator account _verifyAndSetVault(liquidatorVault); liquidatorVault.settleProfit(liquidator, liquidationFee); emit LiquidationCall(account, _msgSender(), uint128(block.timestamp), notionalAmount); } }
notional sell derivative tokens on (external) market
function _closePositionOnMarket(uint256 amount, LibPerpetual.Side direction) internal returns (uint256) { uint256 quoteSold = 0; if (direction == LibPerpetual.Side.Long) { quoteSold = market.mintVQuote(amount); quoteSold = market.burnVQuote(amount); } return quoteSold; }
994,505
/** *Submitted for verification at Etherscan.io on 2021-03-08 */ pragma solidity ^0.7.6; library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(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)); } } 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); } } } } 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) { // 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; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } 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; } interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } 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 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; } contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable { function __ERC20Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); } function __ERC20Pausable_init_unchained() internal initializer { } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } uint256[50] private __gap; } abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } using SafeMathUpgradeable for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } uint256[50] private __gap; } abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } /** * @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"); } } /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal virtual view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } } /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin { _upgradeTo(newImplementation); (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override virtual { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } } /** * @title InitializableUpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } contract PUNDIXTokenProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, address _admin, bytes memory _data) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(_logic, _data); assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(_admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); } } library ECDSAUpgradeable { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-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)); } } library CountersUpgradeable { using SafeMathUpgradeable for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } abstract contract EIP712Upgradeable is Initializable { /* solhint-disable var-name-mixedcase */ bytes32 private _HASHED_NAME; bytes32 private _HASHED_VERSION; bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ function __EIP712_init(string memory name, string memory version) internal initializer { __EIP712_init_unchained(name, version); } function __EIP712_init_unchained(string memory name, string memory version) internal initializer { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash()); } function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) { return keccak256( abi.encode( typeHash, name, version, _getChainId(), address(this) ) ); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } /** * @dev The hash of the name parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712NameHash() internal virtual view returns (bytes32) { return _HASHED_NAME; } /** * @dev The hash of the version parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712VersionHash() internal virtual view returns (bytes32) { return _HASHED_VERSION; } uint256[50] private __gap; } interface IERC20PermitUpgradeable { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; mapping (address => CountersUpgradeable.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private _PERMIT_TYPEHASH; /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ function __ERC20Permit_init(string memory name) internal initializer { __Context_init_unchained(); __EIP712_init_unchained(name, "1"); __ERC20Permit_init_unchained(name); } function __ERC20Permit_init_unchained(string memory name) internal initializer { _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); } /** * @dev See {IERC20Permit-permit}. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256( abi.encode( _PERMIT_TYPEHASH, owner, spender, value, _nonces[owner].current(), deadline ) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSAUpgradeable.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _nonces[owner].increment(); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } uint256[49] private __gap; } contract TokenRecipient { function tokenFallback(address _sender, uint256 _value, bytes memory _extraData) public virtual returns (bool) {} } contract PUNDIXToken is Initializable, ContextUpgradeable, AccessControlUpgradeable, ERC20BurnableUpgradeable, ERC20PausableUpgradeable, ERC20PermitUpgradeable { bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); function initialize(address to) public virtual initializer { __Context_init_unchained(); __AccessControl_init_unchained(); __ERC20_init_unchained("Pundi X Token", "PUNDIX"); __ERC20Burnable_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); __ERC20Permit_init("PUNDIX"); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(ADMIN_ROLE, _msgSender()); _mint(to, 258498693019069996455928086); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) { super._beforeTokenTransfer(from, to, amount); } function pause() public virtual { require(hasRole(ADMIN_ROLE, _msgSender()), "must have admin role to pause"); _pause(); } function unpause() public virtual { require(hasRole(ADMIN_ROLE, _msgSender()), "must have admin role to unpause"); _unpause(); } function transferERCToken(address tokenContractAddress, address to, uint256 amount) public { require(hasRole(ADMIN_ROLE, _msgSender()), "must have admin role to transfer other ERC20"); require(IERC20Upgradeable(tokenContractAddress).transfer(to, amount)); } function transferAndCall(address recipient, uint256 amount, bytes memory data) public { require(recipient != address(0), "transfer to the zero address"); require(amount <= balanceOf(recipient), "insufficient balance"); transfer(recipient, amount); require(TokenRecipient(recipient).tokenFallback(msg.sender, amount, data)); } }
Contract initializer. _logic Address of the initial implementation. _data Data to send as msg.data to the implementation to initialize the proxied contract. It should include the signature and the parameters of the function to be called, as described in This parameter is optional, if no data is given the initialization call to proxied contract will be skipped./
function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } }
7,899,409
./full_match/53935/0x794C07912474351b3134E6D6B3B7b3b4A07cbAAa/sources/contracts/dex/UniswapV2Pair.sol
this low-level function should be called from a contract which performs important safety checks scope for _token{0,1}, avoids stack too deep errors scope for reserve{0,1}Adjusted, avoids stack too deep errors
function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external lock { require(amount0Out > 0 || amount1Out > 0, "UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT"); require(amount0Out < _reserve0 && amount1Out < _reserve1, "UniswapV2: INSUFFICIENT_LIQUIDITY"); uint256 balance0; uint256 balance1; { address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, "UniswapV2: INVALID_TO"); if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); } uint256 amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint256 amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, "UniswapV2: INSUFFICIENT_INPUT_AMOUNT"); { uint256 balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); uint256 balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); require(balance0Adjusted.mul(balance1Adjusted) >= uint256(_reserve0).mul(_reserve1).mul(1000**2), "UniswapV2: K"); } _update(balance0, balance1, _reserve0, _reserve1); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); }
3,786,349