file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./partial_match/1/0xa6d8C77FFf3CDcc43804275aD9997b603a7817c5/sources/src/ButtonswapRouter.sol
@inheritdoc IButtonswapRouter/
function getBurnSwappedAmounts(address tokenA, address tokenB, uint256 liquidity) external view virtual override returns (uint256 tokenOutA, uint256 swappedReservoirAmountA) { return ButtonswapLibrary.getBurnSwappedAmounts(factory, tokenA, tokenB, liquidity); }
3,642,055
// File: contracts/PRBMathCommon.sol pragma solidity >=0.8.0; /// @dev Common mathematical functions used in both PRBMathSD59x18 and PRBMathUD60x18. Note that this shared library /// does not always assume the signed 59.18-decimal fixed-point or the unsigned 60.18-decimal fixed-point // representation. When it does not, it is annonated in the function's NatSpec documentation. library PRBMathCommon { /// @dev How many trailing decimals can be represented. uint256 internal constant SCALE = 1e18; /// @dev Largest power of two divisor of SCALE. uint256 internal constant SCALE_LPOTD = 262144; /// @dev SCALE inverted mod 2^256. uint256 internal constant SCALE_INVERSE = 78156646155174841979727994598816262306175212592076161876661508869554232690281; /// @notice Calculates the binary exponent of x using the binary fraction method. /// @dev Uses 128.128-bit fixed-point numbers - it is the most efficient way. /// @param x The exponent as an unsigned 128.128-bit fixed-point number. /// @return result The result as an unsigned 60x18 decimal fixed-point number. function exp2(uint256 x) internal pure returns (uint256 result) { unchecked { // Start from 0.5 in the 128.128-bit fixed-point format. We need to use uint256 because the intermediary // may get very close to 2^256, which doesn't fit in int256. result = 0x80000000000000000000000000000000; // Multiply the result by root(2, 2^-i) when the bit at position i is 1. None of the intermediary results overflows // because the initial result is 2^127 and all magic factors are less than 2^129. if (x & 0x80000000000000000000000000000000 > 0) result = (result * 0x16A09E667F3BCC908B2FB1366EA957D3E) >> 128; if (x & 0x40000000000000000000000000000000 > 0) result = (result * 0x1306FE0A31B7152DE8D5A46305C85EDED) >> 128; if (x & 0x20000000000000000000000000000000 > 0) result = (result * 0x1172B83C7D517ADCDF7C8C50EB14A7920) >> 128; if (x & 0x10000000000000000000000000000000 > 0) result = (result * 0x10B5586CF9890F6298B92B71842A98364) >> 128; if (x & 0x8000000000000000000000000000000 > 0) result = (result * 0x1059B0D31585743AE7C548EB68CA417FE) >> 128; if (x & 0x4000000000000000000000000000000 > 0) result = (result * 0x102C9A3E778060EE6F7CACA4F7A29BDE9) >> 128; if (x & 0x2000000000000000000000000000000 > 0) result = (result * 0x10163DA9FB33356D84A66AE336DCDFA40) >> 128; if (x & 0x1000000000000000000000000000000 > 0) result = (result * 0x100B1AFA5ABCBED6129AB13EC11DC9544) >> 128; if (x & 0x800000000000000000000000000000 > 0) result = (result * 0x10058C86DA1C09EA1FF19D294CF2F679C) >> 128; if (x & 0x400000000000000000000000000000 > 0) result = (result * 0x1002C605E2E8CEC506D21BFC89A23A011) >> 128; if (x & 0x200000000000000000000000000000 > 0) result = (result * 0x100162F3904051FA128BCA9C55C31E5E0) >> 128; if (x & 0x100000000000000000000000000000 > 0) result = (result * 0x1000B175EFFDC76BA38E31671CA939726) >> 128; if (x & 0x80000000000000000000000000000 > 0) result = (result * 0x100058BA01FB9F96D6CACD4B180917C3E) >> 128; if (x & 0x40000000000000000000000000000 > 0) result = (result * 0x10002C5CC37DA9491D0985C348C68E7B4) >> 128; if (x & 0x20000000000000000000000000000 > 0) result = (result * 0x1000162E525EE054754457D5995292027) >> 128; if (x & 0x10000000000000000000000000000 > 0) result = (result * 0x10000B17255775C040618BF4A4ADE83FD) >> 128; if (x & 0x8000000000000000000000000000 > 0) result = (result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAC) >> 128; if (x & 0x4000000000000000000000000000 > 0) result = (result * 0x100002C5C89D5EC6CA4D7C8ACC017B7CA) >> 128; if (x & 0x2000000000000000000000000000 > 0) result = (result * 0x10000162E43F4F831060E02D839A9D16D) >> 128; if (x & 0x1000000000000000000000000000 > 0) result = (result * 0x100000B1721BCFC99D9F890EA06911763) >> 128; if (x & 0x800000000000000000000000000 > 0) result = (result * 0x10000058B90CF1E6D97F9CA14DBCC1629) >> 128; if (x & 0x400000000000000000000000000 > 0) result = (result * 0x1000002C5C863B73F016468F6BAC5CA2C) >> 128; if (x & 0x200000000000000000000000000 > 0) result = (result * 0x100000162E430E5A18F6119E3C02282A6) >> 128; if (x & 0x100000000000000000000000000 > 0) result = (result * 0x1000000B1721835514B86E6D96EFD1BFF) >> 128; if (x & 0x80000000000000000000000000 > 0) result = (result * 0x100000058B90C0B48C6BE5DF846C5B2F0) >> 128; if (x & 0x40000000000000000000000000 > 0) result = (result * 0x10000002C5C8601CC6B9E94213C72737B) >> 128; if (x & 0x20000000000000000000000000 > 0) result = (result * 0x1000000162E42FFF037DF38AA2B219F07) >> 128; if (x & 0x10000000000000000000000000 > 0) result = (result * 0x10000000B17217FBA9C739AA5819F44FA) >> 128; if (x & 0x8000000000000000000000000 > 0) result = (result * 0x1000000058B90BFCDEE5ACD3C1CEDC824) >> 128; if (x & 0x4000000000000000000000000 > 0) result = (result * 0x100000002C5C85FE31F35A6A30DA1BE51) >> 128; if (x & 0x2000000000000000000000000 > 0) result = (result * 0x10000000162E42FF0999CE3541B9FFFD0) >> 128; if (x & 0x1000000000000000000000000 > 0) result = (result * 0x100000000B17217F80F4EF5AADDA45554) >> 128; if (x & 0x800000000000000000000000 > 0) result = (result * 0x10000000058B90BFBF8479BD5A81B51AE) >> 128; if (x & 0x400000000000000000000000 > 0) result = (result * 0x1000000002C5C85FDF84BD62AE30A74CD) >> 128; if (x & 0x200000000000000000000000 > 0) result = (result * 0x100000000162E42FEFB2FED257559BDAA) >> 128; if (x & 0x100000000000000000000000 > 0) result = (result * 0x1000000000B17217F7D5A7716BBA4A9AF) >> 128; if (x & 0x80000000000000000000000 > 0) result = (result * 0x100000000058B90BFBE9DDBAC5E109CCF) >> 128; if (x & 0x40000000000000000000000 > 0) result = (result * 0x10000000002C5C85FDF4B15DE6F17EB0E) >> 128; if (x & 0x20000000000000000000000 > 0) result = (result * 0x1000000000162E42FEFA494F1478FDE05) >> 128; if (x & 0x10000000000000000000000 > 0) result = (result * 0x10000000000B17217F7D20CF927C8E94D) >> 128; if (x & 0x8000000000000000000000 > 0) result = (result * 0x1000000000058B90BFBE8F71CB4E4B33E) >> 128; if (x & 0x4000000000000000000000 > 0) result = (result * 0x100000000002C5C85FDF477B662B26946) >> 128; if (x & 0x2000000000000000000000 > 0) result = (result * 0x10000000000162E42FEFA3AE53369388D) >> 128; if (x & 0x1000000000000000000000 > 0) result = (result * 0x100000000000B17217F7D1D351A389D41) >> 128; if (x & 0x800000000000000000000 > 0) result = (result * 0x10000000000058B90BFBE8E8B2D3D4EDF) >> 128; if (x & 0x400000000000000000000 > 0) result = (result * 0x1000000000002C5C85FDF4741BEA6E77F) >> 128; if (x & 0x200000000000000000000 > 0) result = (result * 0x100000000000162E42FEFA39FE95583C3) >> 128; if (x & 0x100000000000000000000 > 0) result = (result * 0x1000000000000B17217F7D1CFB72B45E3) >> 128; if (x & 0x80000000000000000000 > 0) result = (result * 0x100000000000058B90BFBE8E7CC35C3F2) >> 128; if (x & 0x40000000000000000000 > 0) result = (result * 0x10000000000002C5C85FDF473E242EA39) >> 128; if (x & 0x20000000000000000000 > 0) result = (result * 0x1000000000000162E42FEFA39F02B772C) >> 128; if (x & 0x10000000000000000000 > 0) result = (result * 0x10000000000000B17217F7D1CF7D83C1A) >> 128; if (x & 0x8000000000000000000 > 0) result = (result * 0x1000000000000058B90BFBE8E7BDCBE2E) >> 128; if (x & 0x4000000000000000000 > 0) result = (result * 0x100000000000002C5C85FDF473DEA871F) >> 128; if (x & 0x2000000000000000000 > 0) result = (result * 0x10000000000000162E42FEFA39EF44D92) >> 128; if (x & 0x1000000000000000000 > 0) result = (result * 0x100000000000000B17217F7D1CF79E949) >> 128; if (x & 0x800000000000000000 > 0) result = (result * 0x10000000000000058B90BFBE8E7BCE545) >> 128; if (x & 0x400000000000000000 > 0) result = (result * 0x1000000000000002C5C85FDF473DE6ECA) >> 128; if (x & 0x200000000000000000 > 0) result = (result * 0x100000000000000162E42FEFA39EF366F) >> 128; if (x & 0x100000000000000000 > 0) result = (result * 0x1000000000000000B17217F7D1CF79AFA) >> 128; if (x & 0x80000000000000000 > 0) result = (result * 0x100000000000000058B90BFBE8E7BCD6E) >> 128; if (x & 0x40000000000000000 > 0) result = (result * 0x10000000000000002C5C85FDF473DE6B3) >> 128; if (x & 0x20000000000000000 > 0) result = (result * 0x1000000000000000162E42FEFA39EF359) >> 128; if (x & 0x10000000000000000 > 0) result = (result * 0x10000000000000000B17217F7D1CF79AC) >> 128; // Multiply the result by the integer part 2^n + 1. We have to shift by one bit extra because we have already divided // by two when we set the result equal to 0.5 above. result = result << ((x >> 128) + 1); // Convert the result to the signed 60.18-decimal fixed-point format. result = PRBMathCommon.mulDiv(result, 1e18, 2**128); } } /// @notice Finds the zero-based index of the first one in the binary representation of x. /// @dev See the note on msb in the "Find First Set" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set /// @param x The uint256 number for which to find the index of the most significant bit. /// @return msb The index of the most significant bit as an uint256. function mostSignificantBit(uint256 x) internal pure returns (uint256 msb) { if (x >= 2**128) { x >>= 128; msb += 128; } if (x >= 2**64) { x >>= 64; msb += 64; } if (x >= 2**32) { x >>= 32; msb += 32; } if (x >= 2**16) { x >>= 16; msb += 16; } if (x >= 2**8) { x >>= 8; msb += 8; } if (x >= 2**4) { x >>= 4; msb += 4; } if (x >= 2**2) { x >>= 2; msb += 2; } if (x >= 2**1) { // No need to shift x any more. msb += 1; } } /// @notice Calculates floor(x*y÷denominator) with full precision. /// /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv. /// /// Requirements: /// - The denominator cannot be zero. /// - The result must fit within uint256. /// /// Caveats: /// - This function does not work with fixed-point numbers. /// /// @param x The multiplicand as an uint256. /// @param y The multiplier as an uint256. /// @param denominator The divisor as an uint256. /// @return result The result as an uint256. function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { // 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. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. Also prevents denominator == 0. require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. unchecked { // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 lpotdod = denominator & (~denominator + 1); assembly { // Divide denominator by lpotdod. denominator := div(denominator, lpotdod) // Divide [prod1 prod0] by lpotdod. prod0 := div(prod0, lpotdod) // Flip lpotdod such that it is 2**256 / lpotdod. If lpotdod is zero, then it becomes one. lpotdod := add(div(sub(0, lpotdod), lpotdod), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * lpotdod; // Invert denominator mod 2**256. Now that denominator is an odd number, it has an inverse modulo 2**256 such // that denominator * inv = 1 mod 2**256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2**4 uint256 inverse = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2**8 inverse *= 2 - denominator * inverse; // inverse mod 2**16 inverse *= 2 - denominator * inverse; // inverse mod 2**32 inverse *= 2 - denominator * inverse; // inverse mod 2**64 inverse *= 2 - denominator * inverse; // inverse mod 2**128 inverse *= 2 - denominator * inverse; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2**256. Since the precoditions guarantee that the outcome is // less than 2**256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /// @notice Calculates floor(x*y÷1e18) with full precision. /// /// @dev Variant of "mulDiv" with constant folding, i.e. in which the denominator is always 1e18. Before returning the /// final result, we add 1 if (x * y) % SCALE >= HALF_SCALE. Without this, 6.6e-19 would be truncated to 0 instead of /// being rounded to 1e-18. See "Listing 6" and text above it at https://accu.org/index.php/journals/1717. /// /// Requirements: /// - The result must fit within uint256. /// /// Caveats: /// - The body is purposely left uncommented; see the NatSpec comments in "PRBMathCommon.mulDiv" to understand how this works. /// - It is assumed that the result can never be type(uint256).max when x and y solve the following two queations: /// 1) x * y = type(uint256).max * SCALE /// 2) (x * y) % SCALE >= SCALE / 2 /// /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number. /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function mulDivFixedPoint(uint256 x, uint256 y) internal pure returns (uint256 result) { uint256 prod0; uint256 prod1; assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } uint256 remainder; uint256 roundUpUnit; assembly { remainder := mulmod(x, y, SCALE) roundUpUnit := gt(remainder, 499999999999999999) } if (prod1 == 0) { unchecked { result = (prod0 / SCALE) + roundUpUnit; return result; } } require(SCALE > prod1); assembly { result := add( mul( or( div(sub(prod0, remainder), SCALE_LPOTD), mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, SCALE_LPOTD), SCALE_LPOTD), 1)) ), SCALE_INVERSE ), roundUpUnit ) } } /// @notice Calculates the square root of x, rounding down. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Caveats: /// - This function does not work with fixed-point numbers. /// /// @param x The uint256 number for which to calculate the square root. /// @return result The result as an uint256. function sqrt(uint256 x) internal pure returns (uint256 result) { if (x == 0) { return 0; } // Calculate the square root of the perfect square of a power of two that is the closest to x. uint256 xAux = uint256(x); result = 1; if (xAux >= 0x100000000000000000000000000000000) { xAux >>= 128; result <<= 64; } if (xAux >= 0x10000000000000000) { xAux >>= 64; result <<= 32; } if (xAux >= 0x100000000) { xAux >>= 32; result <<= 16; } if (xAux >= 0x10000) { xAux >>= 16; result <<= 8; } if (xAux >= 0x100) { xAux >>= 8; result <<= 4; } if (xAux >= 0x10) { xAux >>= 4; result <<= 2; } if (xAux >= 0x8) { result <<= 1; } // The operations can never overflow because the result is max 2^127 when it enters this block. unchecked { result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; // Seven iterations should be enough uint256 roundedDownResult = x / result; return result >= roundedDownResult ? roundedDownResult : result; } } } // File: contracts/PRBMathSD59x18.sol pragma solidity >=0.8.0; /// @title PRBMathSD59x18 /// @author Paul Razvan Berg /// @notice Smart contract library for advanced fixed-point math. It works with int256 numbers considered to have 18 /// trailing decimals. We call this number representation signed 59.18-decimal fixed-point, since the numbers can have /// a sign and there can be up to 59 digits in the integer part and up to 18 decimals in the fractional part. The numbers /// are bound by the minimum and the maximum values permitted by the Solidity type int256. library PRBMathSD59x18 { /// @dev log2(e) as a signed 59.18-decimal fixed-point number. int256 internal constant LOG2_E = 1442695040888963407; /// @dev Half the SCALE number. int256 internal constant HALF_SCALE = 5e17; /// @dev The maximum value a signed 59.18-decimal fixed-point number can have. int256 internal constant MAX_SD59x18 = 57896044618658097711785492504343953926634992332820282019728792003956564819967; /// @dev The maximum whole value a signed 59.18-decimal fixed-point number can have. int256 internal constant MAX_WHOLE_SD59x18 = 57896044618658097711785492504343953926634992332820282019728000000000000000000; /// @dev The minimum value a signed 59.18-decimal fixed-point number can have. int256 internal constant MIN_SD59x18 = -57896044618658097711785492504343953926634992332820282019728792003956564819968; /// @dev The minimum whole value a signed 59.18-decimal fixed-point number can have. int256 internal constant MIN_WHOLE_SD59x18 = -57896044618658097711785492504343953926634992332820282019728000000000000000000; /// @dev How many trailing decimals can be represented. int256 internal constant SCALE = 1e18; /// INTERNAL FUNCTIONS /// /// @notice Calculate the absolute value of x. /// /// @dev Requirements: /// - x must be greater than MIN_SD59x18. /// /// @param x The number to calculate the absolute value for. /// @param result The absolute value of x. function abs(int256 x) internal pure returns (int256 result) { unchecked { require(x > MIN_SD59x18); result = x < 0 ? -x : x; } } /// @notice Calculates arithmetic average of x and y, rounding down. /// @param x The first operand as a signed 59.18-decimal fixed-point number. /// @param y The second operand as a signed 59.18-decimal fixed-point number. /// @return result The arithmetic average as a signed 59.18-decimal fixed-point number. function avg(int256 x, int256 y) internal pure returns (int256 result) { // The operations can never overflow. unchecked { // The last operand checks if both x and y are odd and if that is the case, we add 1 to the result. We need // to do this because if both numbers are odd, the 0.5 remainder gets truncated twice. result = (x >> 1) + (y >> 1) + (x & y & 1); } } /// @notice Yields the least greatest signed 59.18 decimal fixed-point number greater than or equal to x. /// /// @dev Optimised for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x must be less than or equal to MAX_WHOLE_SD59x18. /// /// @param x The signed 59.18-decimal fixed-point number to ceil. /// @param result The least integer greater than or equal to x, as a signed 58.18-decimal fixed-point number. function ceil(int256 x) internal pure returns (int256 result) { require(x <= MAX_WHOLE_SD59x18); unchecked { int256 remainder = x % SCALE; if (remainder == 0) { result = x; } else { // Solidity uses C fmod style, which returns a modulus with the same sign as x. result = x - remainder; if (x > 0) { result += SCALE; } } } } /// @notice Divides two signed 59.18-decimal fixed-point numbers, returning a new signed 59.18-decimal fixed-point number. /// /// @dev Variant of "mulDiv" that works with signed numbers. Works by computing the signs and the absolute values separately. /// /// Requirements: /// - All from "PRBMathCommon.mulDiv". /// - None of the inputs can be type(int256).min. /// - y cannot be zero. /// - The result must fit within int256. /// /// Caveats: /// - All from "PRBMathCommon.mulDiv". /// /// @param x The numerator as a signed 59.18-decimal fixed-point number. /// @param y The denominator as a signed 59.18-decimal fixed-point number. /// @param result The quotient as a signed 59.18-decimal fixed-point number. function div(int256 x, int256 y) internal pure returns (int256 result) { require(x > type(int256).min); require(y > type(int256).min); // Get hold of the absolute values of x and y. uint256 ax; uint256 ay; unchecked { ax = x < 0 ? uint256(-x) : uint256(x); ay = y < 0 ? uint256(-y) : uint256(y); } // Compute the absolute value of (x*SCALE)÷y. The result must fit within int256. uint256 resultUnsigned = PRBMathCommon.mulDiv(ax, uint256(SCALE), ay); require(resultUnsigned <= uint256(type(int256).max)); // Get the signs of x and y. uint256 sx; uint256 sy; assembly { sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) } // XOR over sx and sy. This is basically checking whether the inputs have the same sign. If yes, the result // should be positive. Otherwise, it should be negative. result = sx ^ sy == 1 ? -int256(resultUnsigned) : int256(resultUnsigned); } /// @notice Returns Euler's number as a signed 59.18-decimal fixed-point number. /// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant). function e() internal pure returns (int256 result) { result = 2718281828459045235; } /// @notice Calculates the natural exponent of x. /// /// @dev Based on the insight that e^x = 2^(x * log2(e)). /// /// Requirements: /// - All from "log2". /// - x must be less than 88722839111672999628. /// /// @param x The exponent as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function exp(int256 x) internal pure returns (int256 result) { // Without this check, the value passed to "exp2" would be less than -59794705707972522261. if (x < -41446531673892822322) { return 0; } // Without this check, the value passed to "exp2" would be greater than 128e18. require(x < 88722839111672999628); // Do the fixed-point multiplication inline to save gas. unchecked { int256 doubleScaleProduct = x * LOG2_E; result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE); } } /// @notice Calculates the binary exponent of x using the binary fraction method. /// /// @dev See https://ethereum.stackexchange.com/q/79903/24693. /// /// Requirements: /// - x must be 128e18 or less. /// - The result must fit within MAX_SD59x18. /// /// Caveats: /// - For any x less than -59794705707972522261, the result is zero. /// /// @param x The exponent as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function exp2(int256 x) internal pure returns (int256 result) { // This works because 2^-x = 1/2^x. if (x < 0) { // 2**59.794705707972522262 is the maximum number whose inverse does not equal zero. if (x < -59794705707972522261) { return 0; } // Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE. unchecked { result = 1e36 / exp2(-x); } return result; } else { // 2**128 doesn't fit within the 128.128-bit fixed-point representation. require(x < 128e18); unchecked { // Convert x to the 128.128-bit fixed-point format. uint256 x128x128 = (uint256(x) << 128) / uint256(SCALE); // Safe to convert the result to int256 directly because the maximum input allowed is 128e18. result = int256(PRBMathCommon.exp2(x128x128)); } } } /// @notice Yields the greatest signed 59.18 decimal fixed-point number less than or equal to x. /// /// @dev Optimised for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x must be greater than or equal to MIN_WHOLE_SD59x18. /// /// @param x The signed 59.18-decimal fixed-point number to floor. /// @param result The greatest integer less than or equal to x, as a signed 58.18-decimal fixed-point number. function floor(int256 x) internal pure returns (int256 result) { require(x >= MIN_WHOLE_SD59x18); unchecked { int256 remainder = x % SCALE; if (remainder == 0) { result = x; } else { // Solidity uses C fmod style, which returns a modulus with the same sign as x. result = x - remainder; if (x < 0) { result -= SCALE; } } } } /// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right /// of the radix point for negative numbers. /// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part /// @param x The signed 59.18-decimal fixed-point number to get the fractional part of. /// @param result The fractional part of x as a signed 59.18-decimal fixed-point number. function frac(int256 x) internal pure returns (int256 result) { unchecked { result = x % SCALE; } } /// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down. /// /// @dev Requirements: /// - x * y must fit within MAX_SD59x18, lest it overflows. /// - x * y cannot be negative. /// /// @param x The first operand as a signed 59.18-decimal fixed-point number. /// @param y The second operand as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function gm(int256 x, int256 y) internal pure returns (int256 result) { if (x == 0) { return 0; } unchecked { // Checking for overflow this way is faster than letting Solidity do it. int256 xy = x * y; require(xy / x == y); // The product cannot be negative. require(xy >= 0); // We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE // during multiplication. See the comments within the "sqrt" function. result = int256(PRBMathCommon.sqrt(uint256(xy))); } } /// @notice Calculates 1 / x, rounding towards zero. /// /// @dev Requirements: /// - x cannot be zero. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the inverse. /// @return result The inverse as a signed 59.18-decimal fixed-point number. function inv(int256 x) internal pure returns (int256 result) { unchecked { // 1e36 is SCALE * SCALE. result = 1e36 / x; } } /// @notice Calculates the natural logarithm of x. /// /// @dev Based on the insight that ln(x) = log2(x) / log2(e). /// /// Requirements: /// - All from "log2". /// /// Caveats: /// - All from "log2". /// - This doesn't return exactly 1 for 2718281828459045235, for that we would need more fine-grained precision. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the natural logarithm. /// @return result The natural logarithm as a signed 59.18-decimal fixed-point number. function ln(int256 x) internal pure returns (int256 result) { // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x) // can return is 195205294292027477728. unchecked { result = (log2(x) * SCALE) / LOG2_E; } } /// @notice Calculates the common logarithm of x. /// /// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common /// logarithm based on the insight that log10(x) = log2(x) / log2(10). /// /// Requirements: /// - All from "log2". /// /// Caveats: /// - All from "log2". /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the common logarithm. /// @return result The common logarithm as a signed 59.18-decimal fixed-point number. function log10(int256 x) internal pure returns (int256 result) { require(x > 0); // Note that the "mul" in this block is the assembly mul operation, not the "mul" function defined in this contract. // prettier-ignore assembly { switch x case 1 { result := mul(SCALE, sub(0, 18)) } case 10 { result := mul(SCALE, sub(1, 18)) } case 100 { result := mul(SCALE, sub(2, 18)) } case 1000 { result := mul(SCALE, sub(3, 18)) } case 10000 { result := mul(SCALE, sub(4, 18)) } case 100000 { result := mul(SCALE, sub(5, 18)) } case 1000000 { result := mul(SCALE, sub(6, 18)) } case 10000000 { result := mul(SCALE, sub(7, 18)) } case 100000000 { result := mul(SCALE, sub(8, 18)) } case 1000000000 { result := mul(SCALE, sub(9, 18)) } case 10000000000 { result := mul(SCALE, sub(10, 18)) } case 100000000000 { result := mul(SCALE, sub(11, 18)) } case 1000000000000 { result := mul(SCALE, sub(12, 18)) } case 10000000000000 { result := mul(SCALE, sub(13, 18)) } case 100000000000000 { result := mul(SCALE, sub(14, 18)) } case 1000000000000000 { result := mul(SCALE, sub(15, 18)) } case 10000000000000000 { result := mul(SCALE, sub(16, 18)) } case 100000000000000000 { result := mul(SCALE, sub(17, 18)) } case 1000000000000000000 { result := 0 } case 10000000000000000000 { result := SCALE } case 100000000000000000000 { result := mul(SCALE, 2) } case 1000000000000000000000 { result := mul(SCALE, 3) } case 10000000000000000000000 { result := mul(SCALE, 4) } case 100000000000000000000000 { result := mul(SCALE, 5) } case 1000000000000000000000000 { result := mul(SCALE, 6) } case 10000000000000000000000000 { result := mul(SCALE, 7) } case 100000000000000000000000000 { result := mul(SCALE, 8) } case 1000000000000000000000000000 { result := mul(SCALE, 9) } case 10000000000000000000000000000 { result := mul(SCALE, 10) } case 100000000000000000000000000000 { result := mul(SCALE, 11) } case 1000000000000000000000000000000 { result := mul(SCALE, 12) } case 10000000000000000000000000000000 { result := mul(SCALE, 13) } case 100000000000000000000000000000000 { result := mul(SCALE, 14) } case 1000000000000000000000000000000000 { result := mul(SCALE, 15) } case 10000000000000000000000000000000000 { result := mul(SCALE, 16) } case 100000000000000000000000000000000000 { result := mul(SCALE, 17) } case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) } case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) } case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) } case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) } case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) } case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) } case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) } case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) } case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) } case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) } case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) } case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) } case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) } case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) } case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) } case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) } case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) } case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) } case 1000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 36) } case 10000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 37) } case 100000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 38) } case 1000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 39) } case 10000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 40) } case 100000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 41) } case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 42) } case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 43) } case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 44) } case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 45) } case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 46) } case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 47) } case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 48) } case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 49) } case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 50) } case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 51) } case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 52) } case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 53) } case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 54) } case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 55) } case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 56) } case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 57) } case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 58) } default { result := MAX_SD59x18 } } if (result == MAX_SD59x18) { // Do the fixed-point division inline to save gas. The denominator is log2(10). unchecked { result = (log2(x) * SCALE) / 332192809488736234; } } } /// @notice Calculates the binary logarithm of x. /// /// @dev Based on the iterative approximation algorithm. /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation /// /// Requirements: /// - x must be greater than zero. /// /// Caveats: /// - The results are nor perfectly accurate to the last digit, due to the lossy precision of the iterative approximation. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the binary logarithm. /// @return result The binary logarithm as a signed 59.18-decimal fixed-point number. function log2(int256 x) internal pure returns (int256 result) { require(x > 0); unchecked { // This works because log2(x) = -log2(1/x). int256 sign; if (x >= SCALE) { sign = 1; } else { sign = -1; // Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE. assembly { x := div(1000000000000000000000000000000000000, x) } } // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n). uint256 n = PRBMathCommon.mostSignificantBit(uint256(x / SCALE)); // The integer part of the logarithm as a signed 59.18-decimal fixed-point number. The operation can't overflow // because n is maximum 255, SCALE is 1e18 and sign is either 1 or -1. result = int256(n) * SCALE; // This is y = x * 2^(-n). int256 y = x >> n; // If y = 1, the fractional part is zero. if (y == SCALE) { return result * sign; } // Calculate the fractional part via the iterative approximation. // The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster. for (int256 delta = int256(HALF_SCALE); delta > 0; delta >>= 1) { y = (y * y) / SCALE; // Is y^2 > 2 and so in the range [2,4)? if (y >= 2 * SCALE) { // Add the 2^(-m) factor to the logarithm. result += delta; // Corresponds to z/2 on Wikipedia. y >>= 1; } } result *= sign; } } /// @notice Multiplies two signed 59.18-decimal fixed-point numbers together, returning a new signed 59.18-decimal /// fixed-point number. /// /// @dev Variant of "mulDiv" that works with signed numbers and employs constant folding, i.e. the denominator is /// alawys 1e18. /// /// Requirements: /// - All from "PRBMathCommon.mulDivFixedPoint". /// - The result must fit within MAX_SD59x18. /// /// Caveats: /// - The body is purposely left uncommented; see the NatSpec comments in "PRBMathCommon.mulDiv" to understand how this works. /// /// @param x The multiplicand as a signed 59.18-decimal fixed-point number. /// @param y The multiplier as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function mul(int256 x, int256 y) internal pure returns (int256 result) { require(x > MIN_SD59x18); require(y > MIN_SD59x18); unchecked { uint256 ax; uint256 ay; ax = x < 0 ? uint256(-x) : uint256(x); ay = y < 0 ? uint256(-y) : uint256(y); uint256 resultUnsigned = PRBMathCommon.mulDivFixedPoint(ax, ay); require(resultUnsigned <= uint256(MAX_SD59x18)); uint256 sx; uint256 sy; assembly { sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) } result = sx ^ sy == 1 ? -int256(resultUnsigned) : int256(resultUnsigned); } } /// @notice Retrieves PI as a signed 59.18-decimal fixed-point number. function pi() internal pure returns (int256 result) { result = 3141592653589793238; } /// @notice Raises x (signed 59.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the /// famous algorithm "exponentiation by squaring". /// /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring /// /// Requirements: /// - All from "abs" and "PRBMathCommon.mulDivFixedPoint". /// - The result must fit within MAX_SD59x18. /// /// Caveats: /// - All from "PRBMathCommon.mulDivFixedPoint". /// - Assumes 0^0 is 1. /// /// @param x The base as a signed 59.18-decimal fixed-point number. /// @param y The exponent as an uint256. /// @return result The result as a signed 59.18-decimal fixed-point number. function pow(int256 x, uint256 y) internal pure returns (int256 result) { uint256 absX = uint256(abs(x)); // Calculate the first iteration of the loop in advance. uint256 absResult = y & 1 > 0 ? absX : uint256(SCALE); // Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster. for (y >>= 1; y > 0; y >>= 1) { absX = PRBMathCommon.mulDivFixedPoint(absX, absX); // Equivalent to "y % 2 == 1" but faster. if (y & 1 > 0) { absResult = PRBMathCommon.mulDivFixedPoint(absResult, absX); } } // The result must fit within the 59.18-decimal fixed-point representation. require(absResult <= uint256(MAX_SD59x18)); // Is the base negative and the exponent an odd number? bool isNegative = x < 0 && y & 1 == 1; result = isNegative ? -int256(absResult) : int256(absResult); } /// @notice Returns 1 as a signed 59.18-decimal fixed-point number. function scale() internal pure returns (int256 result) { result = SCALE; } /// @notice Calculates the square root of x, rounding down. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Requirements: /// - x cannot be negative. /// - x must be less than MAX_SD59x18 / SCALE. /// /// Caveats: /// - The maximum fixed-point number permitted is 57896044618658097711785492504343953926634.992332820282019729. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the square root. /// @return result The result as a signed 59.18-decimal fixed-point . function sqrt(int256 x) internal pure returns (int256 result) { require(x >= 0); require(x < 57896044618658097711785492504343953926634992332820282019729); unchecked { // Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two signed // 59.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root). result = int256(PRBMathCommon.sqrt(uint256(x * SCALE))); } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // 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); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) 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/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) 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 Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/Staking.sol /* ************************************************* * * Abbey Technology GmbH; https://abbey.ch/ * * An ERC20 'stake and earn' smart contract that distributes * token rewards to stakers over time. * * An account with some balance of ERC20 tokens can deposit them * into this staking contract. This contract has a pool of reward * tokens which it distributes to stakers over time. As time goes * by, the staker will earn reward tokens and, after the lock-up * term expires, stakers claim rewards and withdraw their deposits. * * The longer tokens are staked for, the higher the earned reward. * If tokens are withdrawn prior to the staker-pledged lock-up term, * then only the original deposit-amount of tokens is returned, * without reward. * * Token reward-givers must be designated by the original ERC20 * token contract creator, and reward-givers determine the annual * percentage yield (APY) per ERC20 token instance. * * Staking is only allowed when there is sufficient collateral * for token-rewards deposited in the contract by a reward-giver. * * Any ERC20 smart contract may use this contract, free of charge * or commission, to provide a 'stake and earn' service to hodlers. * * APY formula is (1+i)^(n/12)^a * where i=target 12 month APY * n=number of months locked * a=scaling factor 1 <= a <= 2 * ************************************************* */ pragma solidity 0.8.13; /** * @title Upstream Staking contract, lock up tokens for a period of time to get rewards. * @author Abbey Technology GmbH */ contract Staking is Ownable { /** * @notice The details of staked tokens */ struct Stake { // The symbol of the contract this stake is for. string symbol; // The number of tokens staked. 1 token = 1 Eth. uint256 quantity; // The number of months the tokens are staked for, 1-maxDuration. uint256 duration; // The maximum number of months tokens can be staked for. int256 maxDuration; // The max percent return at the time of the stake. 1% = 1 Eth. uint256 percent; // The value that determines the exponentiality of the return. uint256 aValue; // The date the stake was committed, used to determine when it has vested (or not!). uint256 date; } /** * @notice Details of a listing that can be staked on this contract. */ struct TokenDetails { // The address of the token contract. address tokenAddress; // The maximum number of months (in wei) tokens can be staked for before they must be withdrawn or rolled over. int256 maxDuration; // The maximum percent of the stake returned if comitted for the full maxDuration. uint256 maxPercent; // The exponentiality of the return, higher values skew rewards towards longer staking. // An a-value of 1.5 is in eth i.e. 1500000000000000000. uint256 aValue; // The address that manages the reward pool, not necessarily the owner of the ERC20 contract. address poolAdmin; // The number of tokens pledged by the issuer for rewards. uint256 rewardPool; // The number of reward tokens if all current stakes pay out. These come directly from the tokenPool. uint256 reservedPool; } // The average number of days in one month. int256 constant daysInMonth = 30; // Approximation of seconds in a month to compare timestamps. Public for unit test access. uint256 public constant secondsInMonth = uint256(daysInMonth) * 24 * 60 * 60; /** * @notice All symbols that can be staked in this contract. */ string[] public symbols; /** * @notice An address can have multiple stakes in multiple tokens. */ mapping(address => mapping (string /*symbol*/ => Stake[])) public stakes; /** * @notice The list of symbols held by an address. */ mapping(address => string[]) public symbolsByAddress; /** * @notice Map an ERC20 token's symbol to the staking details. All values are 0 if staking is not supported for that symbol. */ mapping(string => TokenDetails) public tokenContracts; /** * @notice Return the list of symbols that can be staked in this contract. */ function allSymbols() public view returns (string[] memory) { return symbols; } /** * @notice For an address return the symbols of the stakes. */ function mySymbols(address who) public view returns (string[] memory) { return symbolsByAddress[who]; } /** * @notice Return all stakes for a user against a single ERC20 token. */ function myStakes(address who, string memory symbol) public view returns (Stake[] memory) { return stakes[who][symbol]; } // The pool admin of a listing has added or removed tokens from the pool used as staking rewards. event PoolSizeChanged(address indexed who, string symbol, uint256 oldQuantity, uint256 newQuantity); // Details of a user staking tokens, the parameters they provided as well as the ERC20 reward parameters at the time of the stake. event TokensStaked(address indexed who, string symbol, uint256 quantity, int256 duration, int256 maxDuration, uint256 maxPercent, uint256 aValue, uint256 timestamp); // Details of tokens claimed by a user. event TokensClaimed(address indexed who, string symbol, uint256 totalTokens); /** @notice Add an ERC20 token contract so that holders of its tokens can stake them. This also allows the ERC20 owner * to modify the parameters of future stakes. * * @dev To remove an ERC20 contract (staking no longer supported), update the details to set the address to 0x0. * * @param tokenAddress The contract address. * @param symbol Can be a vanity name or the actual ERC20 Symbol value. * @param maxDuration The maximum number of months tokens can be staked. e.g. 12 for 1 year. * @param maxPercent The maximum return on the tokens if staked for maxDuration. e.g. 50% is 0.5x10^18. * @param aValue The exponentiality of the return, a higher value favours longer staking. e.g. 1.3 is 1.3x10^18. * @param admin The wallet that is allowed to modify the reward pool. */ function setTokenContract(address tokenAddress, string memory symbol, int256 maxDuration, uint256 maxPercent, uint256 aValue, address admin) public { require(!equals(symbol, ""), "Symbol must be set"); require(maxPercent == 0 || maxPercent >= 10000000000000000, "Minimum percent is 0.01%"); require(maxDuration <= 60, "Duration is limited to 5 years"); Ownable own = Ownable(tokenAddress); require(own.owner() == _msgSender(), "You do not own this contract"); TokenDetails memory existing = tokenContracts[symbol]; if(existing.tokenAddress != address(0)) require(existing.tokenAddress == tokenAddress, "Address already set for Symbol"); else symbols.push(symbol); tokenContracts[symbol] = TokenDetails(tokenAddress, maxDuration, maxPercent, aValue, admin, existing.rewardPool, existing.reservedPool); } /** @notice Commit tokens to this contract in order to get a reward. See calculateReturn or * calculateReturnParams to calculate the return under various scenarios. * * @param symbol The ERC20 symbol of the token being staked. * @param quantity The number of tokens to state (1 token = 1x10^18). * @param duration The numnber of months the tokens are staked for (int wei). */ function createStake(string memory symbol, uint256 quantity, int256 duration) public { TokenDetails memory token = tokenContracts[symbol]; require(token.tokenAddress != address(0x0), "Unknown symbol"); require(token.maxPercent != 0, "New stakes are disabled"); require(duration > 0, "Must stake for at least 1 month"); require(duration <= int256(token.maxDuration), "Maximum staking time exceeded"); ERC20 erc20 = ERC20(token.tokenAddress); require(quantity > 0, "Attempt to stake zero tokens"); require(quantity <= erc20.balanceOf(_msgSender()), "Insufficient tokens"); require(erc20.allowance(_msgSender(), address(this)) >= quantity, "Approval to staking contract insufficient"); // Ensure the pool can cover the reward at maturity; add this stake's reward to the total. uint256 reward = uint256(calculateReturn(symbol, quantity, duration)) - quantity; require(reward <= token.rewardPool-token.reservedPool, "Insufficient reward pool"); tokenContracts[symbol].reservedPool += reward; erc20.transferFrom(_msgSender(), address(this), quantity); uint256 timestamp = block.timestamp; Stake memory s = Stake(symbol, quantity, uint256(duration), token.maxDuration, token.maxPercent, token.aValue, timestamp); stakes[_msgSender()][symbol].push(s); string[] memory syms = symbolsByAddress[_msgSender()]; for(uint256 i=0; i<syms.length; i++) { if(equals(syms[i], symbol)) return; } symbolsByAddress[_msgSender()].push(symbol); } /** * @notice Use an ERC20 symbol to get the current staking parameters and calculate the return for the given * number of tokens staked for the specified number of months. * * @param symbol The ERC20 symbol of the token. * @param tokens The number of tokens to stake. * @param months The number of months to stake the tokens, in wei. */ function calculateReturn(string memory symbol, uint256 tokens, int256 months) public view returns (int256) { TokenDetails memory token = tokenContracts[symbol]; require(token.tokenAddress != address(0x0), "Unknown symbol"); return calculateReturnParams(tokens, months, token.maxDuration, token.maxPercent, token.aValue); } /** * @notice Calculate the total number of tokens returned for the given parameters. * Called when a user claims their stake, or can be called directly by a user before staking tokens to * determine their return under various conditions. * * @param tokens The total number of tokens staked. 1 token is 1 eth (1x10^18). * @param months The number of months to stake the tokens, in wei. * @param maxMonths The maximum number of months the tokens can be staked for, in wei. * @param percent The Maximum percentage gained if tokens are staked for maxMonths. 1% is 1 eth. * @param aValue The algo parameter that determines how logarithmic shorter vs longer stakes pay out. * @return Returns the sum of the tokens staked plus tokens gained from staking. */ function calculateReturnParams(uint256 tokens, int256 months, int256 maxMonths, uint256 percent, uint256 aValue) public pure returns (int256) { require(months >= 0, "Stake time cannot be negative."); // Nothing earned, just return the original stake. if(months == 0) return int256(tokens); // If the max staking time is used just return the staked tokens times the // max return. Otherwise it needs to be calculated below. if(aValue > 0 && months == maxMonths) return PRBMathSD59x18.mul(int256(tokens), int256(1 ether + percent)); int256 totalDays = PRBMathSD59x18.mul(int256(months * 1 ether), daysInMonth); int256 logTime = PRBMathSD59x18.ln(PRBMathSD59x18.div(totalDays, daysInMonth * maxMonths)); int256 logTimeByA = PRBMathSD59x18.mul(int256(aValue), logTime); int256 expLogTimeByA = PRBMathSD59x18.exp(int256(logTimeByA)); int256 totalPercent = int256(percent + 1 ether); int256 logPercent = PRBMathSD59x18.ln(totalPercent); int256 mainMul = PRBMathSD59x18.mul(logPercent, expLogTimeByA); int256 finalExp = PRBMathSD59x18.exp(mainMul); int256 total = PRBMathSD59x18.mul(int256(tokens), finalExp); return total; } /** * @notice Allow the address nominated by the issuer of the ERC20 tokens to * increase the size of the reward pool.else * * @param symbol The ERC20 token symbol. * @param quantity The number of tokens to add to the pool. */ function increaseRewardPool(string memory symbol, uint256 quantity) public { TokenDetails memory token = tokenContracts[symbol]; require(token.tokenAddress != address(0x0), "Unknown symbol"); require(_msgSender() == token.poolAdmin, "You are not pool admin"); ERC20 erc20 = ERC20(token.tokenAddress); require(quantity <= erc20.balanceOf(_msgSender()), "Insufficient tokens"); require(erc20.allowance(_msgSender(), address(this)) >= quantity, "Approval to staking contract insufficient"); uint256 oldQuantity = token.rewardPool; erc20.transferFrom(_msgSender(), address(this), quantity); tokenContracts[symbol].rewardPool = tokenContracts[symbol].rewardPool + quantity; emit PoolSizeChanged(_msgSender(), symbol, oldQuantity, tokenContracts[symbol].rewardPool); } /** * @notice Whether stakes have vested or not, claim all and return the tokens to * the caller. If they have vested the reward is inlcluded, if not vested just * the original tokens are returned. * * @param symbol The ERC20 token symbol. */ function withdrawAndClaimAll(string memory symbol) public { withdrawAndClaim(symbol, true); } /** * @notice Transfer the tokens (plus reward) of only vested stakes to the caller. * Leave unvested stakes in place. * * @param symbol The ERC20 token symbol. */ function withdrawAndClaimVested(string memory symbol) public { withdrawAndClaim(symbol, false); } /** * @notice Core function to handle claims. * * @param symbol The ERC20 token symbol. * @param forced True to withdraw unvested tokens without reward, false to leave * unvested stakes in place. */ function withdrawAndClaim(string memory symbol, bool forced) private { TokenDetails memory token = tokenContracts[symbol]; require(token.tokenAddress != address(0x0), "Unknown symbol"); Stake[] memory stakesBySymbol = stakes[_msgSender()][symbol]; if(stakesBySymbol.length == 0) { return; } uint256 totalTokens = 0; uint256 totalReward = 0; for(uint256 i = 0; i<stakesBySymbol.length; i++) { uint256 stakeTokens = getTokenCount(stakesBySymbol[i], forced); Stake memory s = stakesBySymbol[i]; if(stakeTokens > 0) { // If the stake has not vested we need to return the reserved reward tokens to the reward pool. if(!hasVested(s.date, s.duration)) { int256 full = calculateReturnParams(s.quantity, int256(s.duration), s.maxDuration, s.percent, s.aValue); tokenContracts[symbol].reservedPool -= (uint256(full) - s.quantity); } totalReward += stakeTokens - s.quantity; totalTokens += stakeTokens; stakes[_msgSender()][symbol][i] = Stake("", 0, 0, 0, 0, 0, 0); } } if(totalTokens > 0) { ERC20 erc20 = ERC20(token.tokenAddress); erc20.transfer(_msgSender(), totalTokens); tokenContracts[symbol].rewardPool -= totalReward; tokenContracts[symbol].reservedPool -= totalReward; emit TokensClaimed(_msgSender(), symbol, totalTokens); } } /** * @notice Check if the timestamp of the stake plus the duration in months is * older than the current time. * * @param date The epoch time the stake was created. * @param duration The number of months the tokens were staked for. * * @return True if the vested date is in the past, false if not. */ function hasVested(uint256 date, uint256 duration) public view returns (bool) { uint256 vestedDate = date + (duration * secondsInMonth); if(block.timestamp > vestedDate) return true; return false; } /** * @notice Accumulate the rewards of any vested stakes and combine them into a single * stake with a new duration and optinally add some new tokens that have already been * approved. * * @param symbol The ERC20 symbol of the tokens. * @param quantity Zero or more tokens to add to the total. * @param duration The number of months to stake the tokens for. */ function rolloverVested(string memory symbol, uint256 quantity, uint256 duration) public { TokenDetails memory token = tokenContracts[symbol]; require(token.tokenAddress != address(0x0), "Unknown symbol"); require(duration > 0, "Must stake for at least 1 month"); require(int256(duration) <= token.maxDuration, "Maximum staking time exceeded"); ERC20 erc20 = ERC20(token.tokenAddress); require(quantity <= erc20.balanceOf(_msgSender()), "Insufficient tokens"); require(erc20.allowance(_msgSender(), address(this)) >= quantity, "Approval to staking contract insufficient"); // Exit if the user has no stakes. Stake[] memory stakesBySymbol = stakes[_msgSender()][symbol]; if(stakesBySymbol.length == 0) { return; } // Default to outside the array for uninitialised. uint256 reuseStake = stakesBySymbol.length; uint256 totalTokens = quantity; uint256 totalReward = 0; for(uint256 i = 0; i<stakesBySymbol.length; i++) { uint256 stakeTokens = getTokenCount(stakesBySymbol[i], false); if(stakeTokens > 0) { totalReward += stakeTokens - stakesBySymbol[i].quantity; totalTokens += stakeTokens; if(reuseStake == stakesBySymbol.length) reuseStake = i; else stakes[_msgSender()][symbol][i] = Stake("", 0, 0, 0, 0, 0, 0); } } if(reuseStake == stakesBySymbol.length) return; // Ensure the pool can cover the reward at maturity; add this stake's reward to the total. uint256 newReward = uint256(calculateReturn(symbol, totalTokens, int256(duration))) - totalTokens; require(newReward <= token.rewardPool-token.reservedPool, "Insufficient reward pool"); tokenContracts[symbol].rewardPool -= totalReward; tokenContracts[symbol].reservedPool -= totalReward; tokenContracts[symbol].reservedPool += newReward; stakes[_msgSender()][symbol][reuseStake].quantity = totalTokens; stakes[_msgSender()][symbol][reuseStake].duration = duration; stakes[_msgSender()][symbol][reuseStake].maxDuration = token.maxDuration; stakes[_msgSender()][symbol][reuseStake].percent = token.maxPercent; stakes[_msgSender()][symbol][reuseStake].aValue = token.aValue; stakes[_msgSender()][symbol][reuseStake].date = block.timestamp; emit TokensClaimed(_msgSender(), symbol, totalTokens); } /** * @notice If the stake has vested calculate the reward and return that. If not vested return 0 (do nothing), * unless the 'forced' flag is set in which case exit the stake early and return the original staked * tokens without any reward. * * @param stake The details of the stake. * @param forced Used to exit early without reward if the stake has not yet vested. */ function getTokenCount(Stake memory stake, bool forced) public view returns (uint256) { if(hasVested(stake.date, stake.duration)) { return uint256(calculateReturnParams(stake.quantity, int256(stake.duration), stake.maxDuration, stake.percent, stake.aValue)); } else if(forced) { return stake.quantity; } else { return 0; } } /** * @notice Allow the ERC20 owner/admin remove extra reward pool tokens. Stake rewards * must be left in the pool. * * @param symbol The symbol of the ERC20 contract. * @param quantity The number of tokens to withdraw. */ function withdrawRewardPool(string memory symbol, uint256 quantity) public { TokenDetails memory token = tokenContracts[symbol]; require(token.tokenAddress != address(0x0), "Unknown symbol"); require(_msgSender() == token.poolAdmin, "You are not pool admin"); uint256 maxWithdraw = token.rewardPool - token.reservedPool; ERC20 erc20 = ERC20(token.tokenAddress); require(quantity <= maxWithdraw, "Insufficient reward pool"); uint256 oldQuantity = token.rewardPool; erc20.transfer(_msgSender(), quantity); tokenContracts[symbol].rewardPool = tokenContracts[symbol].rewardPool - quantity; emit PoolSizeChanged(_msgSender(), symbol, oldQuantity, tokenContracts[symbol].rewardPool); } function equals(string memory _a, string memory _b) public pure returns (bool) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); if(a.length != b.length) return false; for (uint256 i=0; i<a.length; i++) { if(a[i] != b[i]) return false; } return true; } }
Transfer the tokens (plus reward) of only vested stakes to the caller. Leave unvested stakes in place. symbol The ERC20 token symbol./
function withdrawAndClaimVested(string memory symbol) public { withdrawAndClaim(symbol, false); }
9,853,584
./partial_match/3/0xB2B9614178c975a05217A678C7Ae525184EEeebC/sources/luckyEth.sol
This payable bet function allow player to bet with numbers and do validation for unique number It also validate length and not allow Player to rebet in same lottery _numbers are the bet numbers betted by Player/
function bet(uint[] memory _numbers) external payable{ require(checkUniqueAndValid(_numbers, 53), "invalid data, either greater value or non unique."); require(_numbers.length >= 7 && _numbers.length <= 15, 'Wrong data length'); require(msg.value == bet_amount, "bet amount not valid"); require(is_open, "lottery is closed"); require(checkUniqueBet(msg.sender,lottery_players[lottery_id])," Player already betted"); Player memory player = Player ({ bet: msg.value, numbers: _numbers, match_result: 0 } ); lottery_plyr_[lottery_id][msg.sender] = player; lottery_players[lottery_id].push(msg.sender); }
5,066,105
pragma solidity ^0.4.18; contract MPTToken { string public name ; // token name string public symbol ; // token symbol uint256 public decimals ; // token digit mapping (address => uint256) public balanceOf; mapping (address => bool) public frozenAccount; mapping (address => uint256) public frozenBalance; mapping (address => mapping (address => uint256)) public allowance; uint256 public totalSupply = 0; bool public stopped = false; // stopflag: true is stoped,false is not stoped uint256 constant valueFounder = 300000000000000000; address owner = 0x0; modifier isOwner { assert(owner == msg.sender); _; } modifier isRunning { assert (!stopped); _; } modifier validAddress { assert(0x0 != msg.sender); _; } function MPTToken(address _addressFounder,uint256 _initialSupply, string _tokenName, uint8 _decimalUnits, string _tokenSymbol) public { owner = msg.sender; if (_addressFounder == 0x0) _addressFounder = msg.sender; if (_initialSupply == 0) _initialSupply = valueFounder; totalSupply = _initialSupply; // Set the totalSupply name = _tokenName; // Set the name for display symbol = _tokenSymbol; // Set the symbol for display decimals = _decimalUnits; // Amount of decimals for display purposes balanceOf[_addressFounder] = totalSupply; Transfer(0x0, _addressFounder, totalSupply); } /* stop contract */ function stop() public isOwner { stopped = true; } /* start contract */ function start() public isOwner { stopped = false; } /* set contract name */ function setName(string _name) public isOwner { name = _name; } /* set contract owner */ function setOwner(address _owner) public isOwner { owner = _owner; } /* send coins */ function transfer(address _to, uint256 _value) public isRunning validAddress returns (bool success) { require(!frozenAccount[msg.sender]); require(balanceOf[msg.sender] - frozenBalance[msg.sender] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; Transfer(msg.sender, _to, _value); return true; } /* freeze account of target */ function freezeAccount(address _target) public isOwner { frozenAccount[_target] = true; FrozenFunds(_target, true); } /* unfreeze account of target */ function unfreezeAccount(address _target) public isOwner { frozenAccount[_target] = false; FrozenFunds(_target, false); } /* freeze Balance of target */ function freezeBalance(address _target,uint256 _value) public isOwner { frozenBalance[_target] = _value; FrozenCoins(_target, _value); } /* unfreeze Balance of target */ function unfreezeBalance(address _target) public isOwner { frozenBalance[_target] = 0; FrozenCoins(_target, 0); } /* burn coins */ function burn(uint256 _value) public { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; balanceOf[0x0] += _value; Transfer(msg.sender, 0x0, _value); } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(!frozenAccount[msg.sender]); require(balanceOf[_from] - frozenBalance[_from] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); require(allowance[_from][msg.sender] >= _value) ; // Check allowance balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event FrozenFunds(address _target, bool _frozen); event FrozenCoins(address _target, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
freeze Balance of target /
function freezeBalance(address _target,uint256 _value) public isOwner { frozenBalance[_target] = _value; FrozenCoins(_target, _value); }
1,606,143
./full_match/7700/0x9B2a63F27661A468E2da22226b64A4914144f195/sources/contracts/mixins/AgentMask.sol
Returns a token balance key given a user and token address. /
function tokenKey (address user, address token) pure internal returns (bytes32) { return keccak256(abi.encode(user, token)); }
4,651,175
//Address: 0x7c5be04b71a9cdd4243372e23d5fcb278428465c //Contract name: AssetViV //Balance: 0 Ether //Verification Date: 5/23/2018 //Transacion Count: 2 // CODE STARTS HERE pragma solidity 0.4.24; /** * @title Vivalid Token Contract * @dev ViV is an ERC-20 Standar Compliant Token * For more info https://vivalid.io */ /** * @title SafeMath by OpenZeppelin (partially) * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @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 Admin parameters * @dev Define administration parameters for this contract */ contract admined { //This token contract is administered address public admin; //Admin address is public bool public lockSupply; //Burn Lock flag /** * @dev Contract constructor * define initial administrator */ constructor() internal { admin = msg.sender; //Set initial admin to contract creator emit Admined(admin); } modifier onlyAdmin() { //A modifier to define admin-only functions require(msg.sender == admin); _; } modifier supplyLock() { //A modifier to lock mint and burn transactions require(lockSupply == false); _; } /** * @dev Function to set new admin address * @param _newAdmin The address to transfer administration to */ function transferAdminship(address _newAdmin) onlyAdmin public { //Admin can be transfered require(_newAdmin != 0); admin = _newAdmin; emit TransferAdminship(admin); } /** * @dev Function to set burn lock * This function will be used after the burn process finish */ function setSupplyLock(bool _flag) onlyAdmin public { //Only the admin can set a lock on supply lockSupply = _flag; emit SetSupplyLock(lockSupply); } //All admin actions have a log for public review event SetSupplyLock(bool _set); event TransferAdminship(address newAdminister); event Admined(address administer); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title ERC20Token * @notice Token definition contract */ contract ERC20Token is admined, ERC20 { //Standar definition of an ERC20Token using SafeMath for uint256; //SafeMath is used for uint256 operations mapping (address => uint256) internal balances; //A mapping of all balances per address mapping (address => mapping (address => uint256)) internal allowed; //A mapping of all allowances uint256 internal totalSupply_; /** * A mapping of frozen accounts and unfreeze dates * * In case your account balance is fronzen and you * think it's an error please contact the support team * * This function is only intended to lock specific wallets * as explained on project white paper */ mapping (address => bool) frozen; mapping (address => uint256) unfreezeDate; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @notice Get the balance of an _who address. * @param _who The address to be query. */ function balanceOf(address _who) public view returns (uint256) { return balances[_who]; } /** * @notice transfer _value tokens to address _to * @param _to The address to transfer to. * @param _value The amount to be transferred. * @return success with boolean value true if done */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); //Invalid transfer require(frozen[msg.sender]==false); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @notice Get the allowance of an specified address to use another address balance. * @param _owner The address of the owner of the tokens. * @param _spender The address of the allowed spender. * @return remaining with the allowance value */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @notice Transfer _value tokens from address _from to address _to using allowance msg.sender allowance on _from * @param _from The address where tokens comes. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @return success with boolean value true if done */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); //Invalid transfer require(frozen[_from]==false); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true; } /** * @notice Assign allowance _value to _spender address to use the msg.sender balance * @param _spender The address to be allowed to spend. * @param _value The amount to be allowed. * @return success with boolean value true */ function approve(address _spender, uint256 _value) public returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); //exploit mitigation allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Burn token of an specified address. * @param _burnedAmount amount to burn. */ function burnToken(uint256 _burnedAmount) onlyAdmin supplyLock public { balances[msg.sender] = SafeMath.sub(balances[msg.sender], _burnedAmount); totalSupply_ = SafeMath.sub(totalSupply_, _burnedAmount); emit Burned(msg.sender, _burnedAmount); } /** * @dev Frozen account handler * @param _target The address to being frozen. * @param _flag The status of the frozen * @param _timeInDays The amount of time the account becomes locked */ function setFrozen(address _target,bool _flag,uint256 _timeInDays) public { if(_flag == true){ require(msg.sender == admin); //Only admin require(frozen[_target] == false); //Not already frozen frozen[_target] = _flag; unfreezeDate[_target] = now.add(_timeInDays * 1 days); emit FrozenStatus(_target,_flag,unfreezeDate[_target]); } else { require(now >= unfreezeDate[_target]); frozen[_target] = _flag; emit FrozenStatus(_target,_flag,unfreezeDate[_target]); } } event Burned(address indexed _target, uint256 _value); event FrozenStatus(address indexed _target,bool _flag,uint256 _unfreezeDate); } /** * @title AssetViV * @notice ViV Token creation. * @dev ERC20 Token compliant */ contract AssetViV is ERC20Token { string public name = 'VIVALID'; uint8 public decimals = 18; string public symbol = 'ViV'; string public version = '1'; /** * @notice token contructor. */ constructor() public { totalSupply_ = 200000000 * 10 ** uint256(decimals); //Initial tokens supply 200M; balances[msg.sender] = totalSupply_; emit Transfer(0, this, totalSupply_); emit Transfer(this, msg.sender, totalSupply_); } /** * @notice Function to claim ANY token accidentally stuck on contract * In case of claim of stuck tokens please contact contract owners * Tokens to be claimed has to been strictly erc20 compliant * We use the ERC20 interface declared before */ function claimTokens(ERC20 _address, address _to) onlyAdmin public{ require(_to != address(0)); uint256 remainder = _address.balanceOf(this); //Check remainder tokens _address.transfer(_to,remainder); //Transfer tokens to creator } /** * @notice this contract will revert on direct non-function calls, also it's not payable * @dev Function to handle callback calls to contract */ function() public { revert(); } }
Transfer _value tokens from address _from to address _to using allowance msg.sender allowance on _from _from The address where tokens comes. _to The address to transfer to. _value The amount to be transferred. return success with boolean value true if done/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(frozen[_from]==false); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true; }
12,937,505
./full_match/80001/0x5828C287320288e130740ed538f3852fAD13995D/sources/contracts/longShort/template/LongShort.sol
/ TODO this is out of date but we should transfer this function to Market contract
- "Pending" - means the next price update hasn't happened or been enacted on by the updateSystemState function. - "Confirmed" - means the next price has been updated by the updateSystemState function. There is still - outstanding (lazy) computation that needs to be executed per user in the batch. - "Settled" - there is no more computation left for the user. - "Non-existent" - user has no next price actions. This function returns a calculated value only in the case of 'confirmed' next price actions. It should return zero for all other types of next price actions. @dev Used in SyntheticToken.sol balanceOf to allow for automatic reflection of next price actions. @param user The address of the user for whom to execute the function for. @param marketIndex An uint32 which uniquely identifies a market. @param isLong Whether it is for the long synthetic asset or the short synthetic asset. @return confirmedButNotSettledBalance The amount in wei of tokens that the user is owed. function getUsersConfirmedButNotSettledSynthBalance( address user, uint32 marketIndex, bool isLong ) external view virtual override requireMarketExists(marketIndex) returns (uint256 confirmedButNotSettledBalance) { uint256 currentMarketUpdateIndex = marketUpdateIndex[marketIndex]; uint256 userNextPrice_currentUpdateIndex_forMarket = userNextPrice_currentUpdateIndex[ marketIndex ][user]; if ( userNextPrice_currentUpdateIndex_forMarket != 0 && userNextPrice_currentUpdateIndex_forMarket <= currentMarketUpdateIndex ) { uint256 amountPaymentTokenDeposited = userNextPrice_paymentToken_depositAmount[marketIndex][ isLong ][user]; uint256 syntheticTokenPrice; uint256 syntheticTokenPriceOnOriginSideOfShift; if (isLong) { ( syntheticTokenPrice, syntheticTokenPriceOnOriginSideOfShift ) = get_syntheticToken_priceSnapshot( marketIndex, userNextPrice_currentUpdateIndex_forMarket ); ( syntheticTokenPriceOnOriginSideOfShift, syntheticTokenPrice ) = get_syntheticToken_priceSnapshot( marketIndex, userNextPrice_currentUpdateIndex_forMarket ); } if (amountPaymentTokenDeposited > 0) { confirmedButNotSettledBalance = _getAmountSyntheticToken( amountPaymentTokenDeposited, syntheticTokenPrice ); } uint256 amountSyntheticTokensToBeShiftedAwayFromOriginSide = userNextPrice_syntheticToken_toShiftAwayFrom_marketSide[ marketIndex ][!isLong][user]; if (amountSyntheticTokensToBeShiftedAwayFromOriginSide > 0) { confirmedButNotSettledBalance += _getEquivalentAmountSyntheticTokensOnTargetSide( amountSyntheticTokensToBeShiftedAwayFromOriginSide, syntheticTokenPriceOnOriginSideOfShift, syntheticTokenPrice ); } } } ╚══════════════════════════════════╝*/
846,037
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../interfaces/BPool.sol"; import "../interfaces/IPriceOracle.sol"; import "../misc/BNum.sol"; /** @title BalancerSharedPoolPriceProvider * @notice Price provider for a balancer pool token * It calculates the price using Chainlink as an external price source and the pool's tokens balances using the weighted arithmetic mean formula. * If there is a price deviation, instead of the balances, it uses a weighted geometric mean with the token's weights and constant value function V. */ contract BalancerSharedPoolPriceProvider is BNum { BPool public pool; address[] public tokens; uint256[] public weights; bool[] public isPeggedToEth; uint8[] public decimals; IPriceOracle public priceOracle; uint256 public immutable maxPriceDeviation; uint256 internal immutable K; uint256 internal immutable powerPrecision; uint256[][] internal approximationMatrix; /** * BalancerSharedPoolPriceProvider constructor. * @param _pool Balancer pool address. * @param _isPeggedToEth For each token, true if it is pegged to ETH (token order determined by pool.getFinalTokens()). * @param _decimals Number of decimals for each token (token order determined by pool.getFinalTokens()). * @param _priceOracle Aave price oracle. * @param _maxPriceDeviation Threshold of spot prices deviation: 10ˆ16 represents a 1% deviation. * @param _K //Constant K = 1 / (w1ˆw1 * .. * wn^wn) * @param _powerPrecision //Precision for power math function. * @param _approximationMatrix //Approximation matrix for gas optimization. */ constructor( BPool _pool, bool[] memory _isPeggedToEth, uint8[] memory _decimals, IPriceOracle _priceOracle, uint256 _maxPriceDeviation, uint256 _K, uint256 _powerPrecision, uint256[][] memory _approximationMatrix ) public { pool = _pool; //Get token list tokens = pool.getFinalTokens(); //This already checks for pool finalized uint256 length = tokens.length; //Validate contructor params require(length >= 2 && length <= 3, "ERR_INVALID_POOL_TOKENS_NUMBER"); require(_isPeggedToEth.length == length, "ERR_INVALID_PEGGED_LENGTH"); require(_decimals.length == length, "ERR_INVALID_DECIMALS_LENGTH"); for (uint8 i = 0; i < length; i++) { require(_decimals[i] <= 18, "ERR_INVALID_DECIMALS"); } require( _approximationMatrix.length == 0 || _approximationMatrix[0].length == length + 1, "ERR_INVALID_APPROX_MATRIX" ); require(_maxPriceDeviation < BONE, "ERR_INVALID_PRICE_DEVIATION"); require( _powerPrecision >= 1 && _powerPrecision <= BONE, "ERR_INVALID_POWER_PRECISION" ); require( address(_priceOracle) != address(0), "ERR_INVALID_PRICE_PROVIDER" ); //Get token normalized weights for (uint8 i = 0; i < length; i++) { weights.push(pool.getNormalizedWeight(tokens[i])); } isPeggedToEth = _isPeggedToEth; decimals = _decimals; priceOracle = _priceOracle; maxPriceDeviation = _maxPriceDeviation; K = _K; powerPrecision = _powerPrecision; approximationMatrix = _approximationMatrix; } /** * Returns the token balance in ethers by multiplying its balance with its price in ethers. * @param index Token index. */ function getEthBalanceByToken(uint256 index) internal view returns (uint256) { uint256 pi = isPeggedToEth[index] ? BONE : uint256(priceOracle.getAssetPrice(tokens[index])); require(pi > 0, "ERR_NO_ORACLE_PRICE"); uint256 missingDecimals = 18 - decimals[index]; uint256 bi = bmul( pool.getBalance(tokens[index]), BONE * 10**(missingDecimals) ); return bmul(bi, pi); } /** * Using the matrix approximation, returns a near base and exponentiation result, for num ^ weights[index] * @param index Token index. * @param num Base to approximate. */ function getClosestBaseAndExponetation(uint256 index, uint256 num) internal view returns (uint256, uint256) { uint256 length = approximationMatrix.length; uint256 k = index + 1; for (uint8 i = 0; i < length; i++) { if (approximationMatrix[i][0] >= num) { return (approximationMatrix[i][0], approximationMatrix[i][k]); } } return (0, 0); } /** * Returns true if there is a price deviation. * @param ethTotals Balance of each token in ethers. */ function hasDeviation(uint256[] memory ethTotals) internal view returns (bool) { //Check for a price deviation uint256 length = tokens.length; for (uint8 i = 0; i < length; i++) { for (uint8 o = 0; o < length; o++) { if (i != o) { uint256 price_deviation = bdiv( bdiv(ethTotals[i], weights[i]), bdiv(ethTotals[o], weights[o]) ); if ( price_deviation > (BONE + maxPriceDeviation) || price_deviation < (BONE - maxPriceDeviation) ) { return true; } } } } return false; } /** * Calculates the price of the pool token using the formula of weighted arithmetic mean. * @param ethTotals Balance of each token in ethers. */ function getArithmeticMean(uint256[] memory ethTotals) internal view returns (uint256) { uint256 totalEth = 0; uint256 length = tokens.length; for (uint8 i = 0; i < length; i++) { totalEth = badd(totalEth, ethTotals[i]); } return bdiv(totalEth, pool.totalSupply()); } /** * Returns the weighted token balance in ethers by calculating the balance in ether of the token to the power of its weight. * @param index Token index. */ function getWeightedEthBalanceByToken(uint256 index, uint256 ethTotal) internal view returns (uint256) { uint256 weight = weights[index]; (uint256 base, uint256 result) = getClosestBaseAndExponetation( index, ethTotal ); if (base == 0 || ethTotal < MAX_BPOW_BASE) { if (ethTotal < MAX_BPOW_BASE) { return bpowApprox(ethTotal, weight, powerPrecision); } else { return bmul( ethTotal, bpowApprox( bdiv(BONE, ethTotal), (BONE - weight), powerPrecision ) ); } } else { return bmul( result, bpowApprox(bdiv(ethTotal, base), weight, powerPrecision) ); } } /** * Calculates the price of the pool token using the formula of weighted geometric mean. * @param ethTotals Balance of each token in ethers. */ function getWeightedGeometricMean(uint256[] memory ethTotals) internal view returns (uint256) { uint256 mult = BONE; uint256 length = tokens.length; for (uint256 i = 0; i < length; i++) { mult = bmul(mult, getWeightedEthBalanceByToken(i, ethTotals[i])); } return bdiv(bmul(mult, K), pool.totalSupply()); } /** * Returns the pool's token price. * It calculates the price using Chainlink as an external price source and the pool's tokens balances using the weighted arithmetic mean formula. * If there is a price deviation, instead of the balances, it uses a weighted geometric mean with the token's weights and constant value function V. */ function latestAnswer() external view returns (uint256) { //Get token balances in ethers uint256[] memory ethTotals = new uint256[](tokens.length); uint256 length = tokens.length; for (uint256 i = 0; i < length; i++) { ethTotals[i] = getEthBalanceByToken(i); } if (hasDeviation(ethTotals)) { //Calculate the weighted geometric mean return getWeightedGeometricMean(ethTotals); } else { //Calculate the weighted arithmetic mean return getArithmeticMean(ethTotals); } } /** * Returns Balancer pool address. */ function getPool() external view returns (BPool) { return pool; } /** * Returns all tokens. */ function getTokens() external view returns (address[] memory) { return tokens; } /** * Returns all tokens's weights. */ function getWeights() external view returns (uint256[] memory) { return weights; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface BPool { function getFinalTokens() external view returns (address[] memory tokens); function getNormalizedWeight(address token) external view returns (uint); function getBalance(address token) external view returns (uint); function totalSupply() external view returns (uint); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /************ @title IPriceOracle interface @notice Interface for the Aave price oracle.*/ interface IPriceOracle { /*********** @dev returns the asset price in ETH */ function getAssetPrice(address _asset) external view returns (uint256); } // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // From https://github.com/balancer-labs/balancer-core/blob/master/contracts/BNum.sol pragma solidity 0.6.12; import "./BConst.sol"; contract BNum is BConst { function btoi(uint a) internal pure returns (uint) { return a / BONE; } function bfloor(uint a) internal pure returns (uint) { return btoi(a) * BONE; } function badd(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } function bsub(uint a, uint b) internal pure returns (uint) { (uint c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); return c; } function bsubSign(uint a, uint b) internal pure returns (uint, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } function bmul(uint a, uint b) internal pure returns (uint) { uint c0 = a * b; require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW"); uint c1 = c0 + (BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint c2 = c1 / BONE; return c2; } function bdiv(uint a, uint b) internal pure returns (uint) { require(b != 0, "ERR_DIV_ZERO"); uint c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint c2 = c1 / b; return c2; } // DSMath.wpow function bpowi(uint a, uint n) internal pure returns (uint) { uint z = n % 2 != 0 ? a : BONE; for (n /= 2; n != 0; n /= 2) { a = bmul(a, a); if (n % 2 != 0) { z = bmul(z, a); } } return z; } // Compute b^(e.w) by splitting it into (b^e)*(b^0.w). // Use `bpowi` for `b^e` and `bpowK` for k iterations // of approximation of b^0.w function bpow(uint base, uint exp) internal pure returns (uint) { require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW"); require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH"); uint whole = bfloor(exp); uint remain = bsub(exp, whole); uint wholePow = bpowi(base, btoi(whole)); if (remain == 0) { return wholePow; } uint partialResult = bpowApprox(base, remain, BPOW_PRECISION); return bmul(wholePow, partialResult); } function bpowApprox(uint base, uint exp, uint precision) internal pure returns (uint) { // term 0: uint a = exp; (uint x, bool xneg) = bsubSign(base, BONE); uint term = BONE; uint sum = term; bool negative = false; // term(k) = numer / denom // = (product(a - i - 1, i=1-->k) * x^k) / (k!) // each iteration, multiply previous term by (a-(k-1)) * x / k // continue until term is less than precision for (uint i = 1; term >= precision; i++) { uint bigK = i * BONE; (uint c, bool cneg) = bsubSign(a, bsub(bigK, BONE)); term = bmul(term, bmul(c, x)); term = bdiv(term, bigK); if (term == 0) break; if (xneg) negative = !negative; if (cneg) negative = !negative; if (negative) { sum = bsub(sum, term); } else { sum = badd(sum, term); } } return sum; } } // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // From // From https://github.com/balancer-labs/balancer-core/blob/master/contracts/BConst.sol pragma solidity 0.6.12; contract BConst { uint public constant BONE = 10**18; uint public constant MIN_BOUND_TOKENS = 2; uint public constant MAX_BOUND_TOKENS = 8; uint public constant MIN_FEE = BONE / 10**6; uint public constant MAX_FEE = BONE / 10; uint public constant EXIT_FEE = 0; uint public constant MIN_WEIGHT = BONE; uint public constant MAX_WEIGHT = BONE * 50; uint public constant MAX_TOTAL_WEIGHT = BONE * 50; uint public constant MIN_BALANCE = BONE / 10**12; uint public constant INIT_POOL_SUPPLY = BONE * 100; uint public constant MIN_BPOW_BASE = 1 wei; uint public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei; uint public constant BPOW_PRECISION = BONE / 10**10; uint public constant MAX_IN_RATIO = BONE / 2; uint public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei; }
Returns true if there is a price deviation. ethTotals Balance of each token in ethers./Check for a price deviation
function hasDeviation(uint256[] memory ethTotals) internal view returns (bool) { uint256 length = tokens.length; for (uint8 i = 0; i < length; i++) { for (uint8 o = 0; o < length; o++) { if (i != o) { uint256 price_deviation = bdiv( bdiv(ethTotals[i], weights[i]), bdiv(ethTotals[o], weights[o]) ); if ( price_deviation > (BONE + maxPriceDeviation) || price_deviation < (BONE - maxPriceDeviation) ) { return true; } } } } return false; }
14,820,244
// SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ============================ FXS1559_AMO =========================== // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian import "../Math/SafeMath.sol"; import "../FXS/FXS.sol"; import "../Frax/Frax.sol"; import "../ERC20/ERC20.sol"; import "../Frax/Pools/FraxPool.sol"; import "../Oracle/UniswapPairOracle.sol"; import "../Governance/AccessControl.sol"; import '../Misc_AMOs/FraxPoolInvestorForV2.sol'; import '../Uniswap/UniswapV2Router02_Modified.sol'; contract FXS1559_AMO is AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ ERC20 private collateral_token; FRAXStablecoin private FRAX; FRAXShares private FXS; FraxPoolInvestorForV2 private InvestorAMO; FraxPool private pool; IUniswapV2Router02 private UniRouterV2 = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public collateral_address; address public pool_address; address public owner_address; address public timelock_address; address public custodian_address; address public frax_address; address public fxs_address; address payable public UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public investor_amo_address = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; uint256 public immutable missing_decimals; uint256 private constant PRICE_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6; // Minimum collateral ratio needed for new FRAX minting uint256 public min_cr = 850000; // Amount the contract borrowed uint256 public minted_sum_historical = 0; uint256 public burned_sum_historical = 0; // FRAX -> FXS max slippage uint256 public max_slippage = 200000; // 20% // AMO profits bool public override_amo_profits = false; uint256 public overridden_amo_profit = 0; /* ========== CONSTRUCTOR ========== */ constructor( address _frax_contract_address, address _fxs_contract_address, address _pool_address, address _collateral_address, address _owner_address, address _custodian_address, address _timelock_address, address _investor_amo_address ) public { frax_address = _frax_contract_address; FRAX = FRAXStablecoin(_frax_contract_address); fxs_address = _fxs_contract_address; FXS = FRAXShares(_fxs_contract_address); pool_address = _pool_address; pool = FraxPool(_pool_address); collateral_address = _collateral_address; collateral_token = ERC20(_collateral_address); investor_amo_address = _investor_amo_address; InvestorAMO = FraxPoolInvestorForV2(_investor_amo_address); timelock_address = _timelock_address; owner_address = _owner_address; custodian_address = _custodian_address; missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock"); _; } modifier onlyCustodian() { require(msg.sender == custodian_address, "You are not the rewards custodian"); _; } /* ========== VIEWS ========== */ function unspentInvestorAMOProfit_E18() public view returns (uint256 unspent_profit_e18) { if (override_amo_profits){ unspent_profit_e18 = overridden_amo_profit; } else { uint256[5] memory allocations = InvestorAMO.showAllocations(); uint256 borrowed_USDC = InvestorAMO.borrowed_balance(); unspent_profit_e18 = allocations[1].add(allocations[2]).add(allocations[3]).sub(borrowed_USDC); unspent_profit_e18 = unspent_profit_e18.mul(10 ** missing_decimals); } } function cr_info() public view returns ( uint256 effective_collateral_ratio, uint256 global_collateral_ratio, uint256 excess_collateral_e18, uint256 frax_mintable ) { global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 frax_total_supply = FRAX.totalSupply(); uint256 global_collat_value = (FRAX.globalCollateralValue()).add(unspentInvestorAMOProfit_E18()); effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6 // Same as availableExcessCollatDV() in FraxPool if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR > 1 uint256 required_collat_dollar_value_d18 = (frax_total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio if (global_collat_value > required_collat_dollar_value_d18) { excess_collateral_e18 = global_collat_value.sub(required_collat_dollar_value_d18); frax_mintable = excess_collateral_e18.mul(COLLATERAL_RATIO_PRECISION).div(global_collateral_ratio); } else { excess_collateral_e18 = 0; frax_mintable = 0; } } /* ========== PUBLIC FUNCTIONS ========== */ // Needed for the Frax contract to not brick when this contract is added as a pool function collatDollarBalance() public view returns (uint256) { return 1e18; // Anti-brick } /* ========== RESTRICTED FUNCTIONS ========== */ // This contract is essentially marked as a 'pool' so it can call OnlyPools functions like pool_mint and pool_burn_from // on the main FRAX contract function _mintFRAXForSwap(uint256 frax_amount) internal { // Make sure the current CR isn't already too low require (FRAX.global_collateral_ratio() > min_cr, "Collateral ratio is already too low"); // Make sure the FRAX minting wouldn't push the CR down too much uint256 current_collateral_E18 = (FRAX.globalCollateralValue()); uint256 cur_frax_supply = FRAX.totalSupply(); uint256 new_frax_supply = cur_frax_supply.add(frax_amount); uint256 new_cr = (current_collateral_E18.mul(PRICE_PRECISION)).div(new_frax_supply); require (new_cr > min_cr, "Minting would cause collateral ratio to be too low"); // Mint the frax FRAX.pool_mint(address(this), frax_amount); } function _swapFRAXforFXS(uint256 frax_amount) internal returns (uint256 frax_spent, uint256 fxs_received) { // Get the FXS price uint256 fxs_price = FRAX.fxs_price(); // Approve the FRAX for the router FRAX.approve(UNISWAP_ROUTER_ADDRESS, frax_amount); address[] memory FRAX_FXS_PATH = new address[](2); FRAX_FXS_PATH[0] = frax_address; FRAX_FXS_PATH[1] = fxs_address; uint256 min_fxs_out = frax_amount.mul(PRICE_PRECISION).div(fxs_price); min_fxs_out = min_fxs_out.sub(min_fxs_out.mul(max_slippage).div(PRICE_PRECISION)); // Buy some FXS with FRAX (uint[] memory amounts) = UniRouterV2.swapExactTokensForTokens( frax_amount, min_fxs_out, FRAX_FXS_PATH, address(this), 2105300114 // A long time from now ); return (amounts[0], amounts[1]); } // Burn unneeded or excess FRAX function mintSwapBurn() public onlyByOwnerOrGovernance { (, , , uint256 mintable_frax) = cr_info(); _mintFRAXForSwap(mintable_frax); (, uint256 fxs_received_ ) = _swapFRAXforFXS(mintable_frax); burnFXS(fxs_received_); } // Burn unneeded or excess FRAX function burnFRAX(uint256 frax_amount) public onlyByOwnerOrGovernance { FRAX.burn(frax_amount); burned_sum_historical = burned_sum_historical.add(frax_amount); } // Burn unneeded FXS function burnFXS(uint256 amount) public onlyByOwnerOrGovernance { FXS.approve(address(this), amount); FXS.pool_burn_from(address(this), amount); } /* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */ function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function setPool(address _pool_address) external onlyByOwnerOrGovernance { pool_address = _pool_address; pool = FraxPool(_pool_address); } function setMinimumCollateralRatio(uint256 _min_cr) external onlyByOwnerOrGovernance { min_cr = _min_cr; } function setMaxSlippage(uint256 _max_slippage) external onlyByOwnerOrGovernance { max_slippage = _max_slippage; } function setAMOProfits(uint256 _overridden_amo_profit_e18, bool _override_amo_profits) external onlyByOwnerOrGovernance { overridden_amo_profit = _overridden_amo_profit_e18; // E18 override_amo_profits = _override_amo_profits; } function setRouter(address payable _router_address) external onlyByOwnerOrGovernance { UNISWAP_ROUTER_ADDRESS = _router_address; UniRouterV2 = IUniswapV2Router02(_router_address); } function setInvestorAMO(address _investor_amo_address) external onlyByOwnerOrGovernance { investor_amo_address = _investor_amo_address; InvestorAMO = FraxPoolInvestorForV2(_investor_amo_address); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard ERC20(tokenAddress).transfer(custodian_address, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } /* ========== EVENTS ========== */ event Recovered(address token, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================= FRAXShares (FXS) ========================= // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../Common/Context.sol"; import "../ERC20/ERC20Custom.sol"; import "../ERC20/IERC20.sol"; import "../Frax/Frax.sol"; import "../Math/SafeMath.sol"; import "../Governance/AccessControl.sol"; contract FRAXShares is ERC20Custom, AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ string public symbol; string public name; uint8 public constant decimals = 18; address public FRAXStablecoinAdd; uint256 public constant genesis_supply = 100000000e18; // 100M is printed upon genesis uint256 public FXS_DAO_min; // Minimum FXS required to join DAO groups address public owner_address; address public oracle_address; address public timelock_address; // Governance timelock address FRAXStablecoin private FRAX; bool public trackingVotes = true; // Tracking votes (only change if need to disable votes) // A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } // A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; // The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /* ========== MODIFIERS ========== */ modifier onlyPools() { require(FRAX.frax_pools(msg.sender) == true, "Only frax pools can mint new FRAX"); _; } modifier onlyByOwnerOrGovernance() { require(msg.sender == owner_address || msg.sender == timelock_address, "You are not an owner or the governance timelock"); _; } /* ========== CONSTRUCTOR ========== */ constructor( string memory _name, string memory _symbol, address _oracle_address, address _owner_address, address _timelock_address ) public { name = _name; symbol = _symbol; owner_address = _owner_address; oracle_address = _oracle_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _mint(owner_address, genesis_supply); // Do a checkpoint for the owner _writeCheckpoint(owner_address, 0, 0, uint96(genesis_supply)); } /* ========== RESTRICTED FUNCTIONS ========== */ function setOracle(address new_oracle) external onlyByOwnerOrGovernance { oracle_address = new_oracle; } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setFRAXAddress(address frax_contract_address) external onlyByOwnerOrGovernance { FRAX = FRAXStablecoin(frax_contract_address); } function setFXSMinDAO(uint256 min_FXS) external onlyByOwnerOrGovernance { FXS_DAO_min = min_FXS; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function mint(address to, uint256 amount) public onlyPools { _mint(to, amount); } // This function is what other frax pools will call to mint new FXS (similar to the FRAX mint) function pool_mint(address m_address, uint256 m_amount) external onlyPools { if(trackingVotes){ uint32 srcRepNum = numCheckpoints[address(this)]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0; uint96 srcRepNew = add96(srcRepOld, uint96(m_amount), "pool_mint new votes overflows"); _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // mint new votes trackVotes(address(this), m_address, uint96(m_amount)); } super._mint(m_address, m_amount); emit FXSMinted(address(this), m_address, m_amount); } // This function is what other frax pools will call to burn FXS function pool_burn_from(address b_address, uint256 b_amount) external onlyPools { if(trackingVotes){ trackVotes(b_address, address(this), uint96(b_amount)); uint32 srcRepNum = numCheckpoints[address(this)]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, uint96(b_amount), "pool_burn_from new votes underflows"); _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // burn votes } super._burnFrom(b_address, b_amount); emit FXSBurned(b_address, address(this), b_amount); } function toggleVotes() external onlyByOwnerOrGovernance { trackingVotes = !trackingVotes; } /* ========== OVERRIDDEN PUBLIC FUNCTIONS ========== */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { if(trackingVotes){ // Transfer votes trackVotes(_msgSender(), recipient, uint96(amount)); } _transfer(_msgSender(), recipient, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { if(trackingVotes){ // Transfer votes trackVotes(sender, recipient, uint96(amount)); } _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /* ========== PUBLIC FUNCTIONS ========== */ /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "FXS::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } /* ========== INTERNAL FUNCTIONS ========== */ // From compound's _moveDelegates // Keep track of votes. "Delegates" is a misnomer here function trackVotes(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "FXS::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "FXS::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address voter, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "FXS::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[voter][nCheckpoints - 1].votes = newVotes; } else { checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[voter] = nCheckpoints + 1; } emit VoterVotesChanged(voter, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } /* ========== EVENTS ========== */ /// @notice An event thats emitted when a voters account's vote balance changes event VoterVotesChanged(address indexed voter, uint previousBalance, uint newBalance); // Track FXS burned event FXSBurned(address indexed from, address indexed to, uint256 amount); // Track FXS minted event FXSMinted(address indexed from, address indexed to, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================= FRAXStablecoin (FRAX) ====================== // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../Common/Context.sol"; import "../ERC20/IERC20.sol"; import "../ERC20/ERC20Custom.sol"; import "../ERC20/ERC20.sol"; import "../Math/SafeMath.sol"; import "../FXS/FXS.sol"; import "./Pools/FraxPool.sol"; import "../Oracle/UniswapPairOracle.sol"; import "../Oracle/ChainlinkETHUSDPriceConsumer.sol"; import "../Governance/AccessControl.sol"; contract FRAXStablecoin is ERC20Custom, AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ enum PriceChoice { FRAX, FXS } ChainlinkETHUSDPriceConsumer private eth_usd_pricer; uint8 private eth_usd_pricer_decimals; UniswapPairOracle private fraxEthOracle; UniswapPairOracle private fxsEthOracle; string public symbol; string public name; uint8 public constant decimals = 18; address public owner_address; address public creator_address; address public timelock_address; // Governance timelock address address public controller_address; // Controller contract to dynamically adjust system parameters automatically address public fxs_address; address public frax_eth_oracle_address; address public fxs_eth_oracle_address; address public weth_address; address public eth_usd_consumer_address; uint256 public constant genesis_supply = 2000000e18; // 2M FRAX (only for testing, genesis supply will be 5k on Mainnet). This is to help with establishing the Uniswap pools, as they need liquidity // The addresses in this array are added by the oracle and these contracts are able to mint frax address[] public frax_pools_array; // Mapping is also used for faster verification mapping(address => bool) public frax_pools; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 public global_collateral_ratio; // 6 decimals of precision, e.g. 924102 = 0.924102 uint256 public redemption_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee uint256 public minting_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee uint256 public frax_step; // Amount to change the collateralization ratio by upon refreshCollateralRatio() uint256 public refresh_cooldown; // Seconds to wait before being able to run refreshCollateralRatio() again uint256 public price_target; // The price of FRAX at which the collateral ratio will respond to; this value is only used for the collateral ratio mechanism and not for minting and redeeming which are hardcoded at $1 uint256 public price_band; // The bound above and below the price target at which the refreshCollateralRatio() will not change the collateral ratio address public DEFAULT_ADMIN_ADDRESS; bytes32 public constant COLLATERAL_RATIO_PAUSER = keccak256("COLLATERAL_RATIO_PAUSER"); bool public collateral_ratio_paused = false; /* ========== MODIFIERS ========== */ modifier onlyCollateralRatioPauser() { require(hasRole(COLLATERAL_RATIO_PAUSER, msg.sender)); _; } modifier onlyPools() { require(frax_pools[msg.sender] == true, "Only frax pools can call this function"); _; } modifier onlyByOwnerOrGovernance() { require(msg.sender == owner_address || msg.sender == timelock_address || msg.sender == controller_address, "You are not the owner, controller, or the governance timelock"); _; } modifier onlyByOwnerGovernanceOrPool() { require( msg.sender == owner_address || msg.sender == timelock_address || frax_pools[msg.sender] == true, "You are not the owner, the governance timelock, or a pool"); _; } /* ========== CONSTRUCTOR ========== */ constructor( string memory _name, string memory _symbol, address _creator_address, address _timelock_address ) public { name = _name; symbol = _symbol; creator_address = _creator_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); DEFAULT_ADMIN_ADDRESS = _msgSender(); owner_address = _creator_address; _mint(creator_address, genesis_supply); grantRole(COLLATERAL_RATIO_PAUSER, creator_address); grantRole(COLLATERAL_RATIO_PAUSER, timelock_address); frax_step = 2500; // 6 decimals of precision, equal to 0.25% global_collateral_ratio = 1000000; // Frax system starts off fully collateralized (6 decimals of precision) refresh_cooldown = 3600; // Refresh cooldown period is set to 1 hour (3600 seconds) at genesis price_target = 1000000; // Collateral ratio will adjust according to the $1 price target at genesis price_band = 5000; // Collateral ratio will not adjust if between $0.995 and $1.005 at genesis } /* ========== VIEWS ========== */ // Choice = 'FRAX' or 'FXS' for now function oracle_price(PriceChoice choice) internal view returns (uint256) { // Get the ETH / USD price first, and cut it down to 1e6 precision uint256 eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals); uint256 price_vs_eth; if (choice == PriceChoice.FRAX) { price_vs_eth = uint256(fraxEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FRAX if you put in PRICE_PRECISION WETH } else if (choice == PriceChoice.FXS) { price_vs_eth = uint256(fxsEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FXS if you put in PRICE_PRECISION WETH } else revert("INVALID PRICE CHOICE. Needs to be either 0 (FRAX) or 1 (FXS)"); // Will be in 1e6 format return eth_usd_price.mul(PRICE_PRECISION).div(price_vs_eth); } // Returns X FRAX = 1 USD function frax_price() public view returns (uint256) { return oracle_price(PriceChoice.FRAX); } // Returns X FXS = 1 USD function fxs_price() public view returns (uint256) { return oracle_price(PriceChoice.FXS); } function eth_usd_price() public view returns (uint256) { return uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals); } // This is needed to avoid costly repeat calls to different getter functions // It is cheaper gas-wise to just dump everything and only use some of the info function frax_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { return ( oracle_price(PriceChoice.FRAX), // frax_price() oracle_price(PriceChoice.FXS), // fxs_price() totalSupply(), // totalSupply() global_collateral_ratio, // global_collateral_ratio() globalCollateralValue(), // globalCollateralValue minting_fee, // minting_fee() redemption_fee, // redemption_fee() uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals) //eth_usd_price ); } // Iterate through all frax pools and calculate all value of collateral in all pools globally function globalCollateralValue() public view returns (uint256) { uint256 total_collateral_value_d18 = 0; for (uint i = 0; i < frax_pools_array.length; i++){ // Exclude null addresses if (frax_pools_array[i] != address(0)){ total_collateral_value_d18 = total_collateral_value_d18.add(FraxPool(frax_pools_array[i]).collatDollarBalance()); } } return total_collateral_value_d18; } /* ========== PUBLIC FUNCTIONS ========== */ // There needs to be a time interval that this can be called. Otherwise it can be called multiple times per expansion. uint256 public last_call_time; // Last time the refreshCollateralRatio function was called function refreshCollateralRatio() public { require(collateral_ratio_paused == false, "Collateral Ratio has been paused"); uint256 frax_price_cur = frax_price(); require(block.timestamp - last_call_time >= refresh_cooldown, "Must wait for the refresh cooldown since last refresh"); // Step increments are 0.25% (upon genesis, changable by setFraxStep()) if (frax_price_cur > price_target.add(price_band)) { //decrease collateral ratio if(global_collateral_ratio <= frax_step){ //if within a step of 0, go to 0 global_collateral_ratio = 0; } else { global_collateral_ratio = global_collateral_ratio.sub(frax_step); } } else if (frax_price_cur < price_target.sub(price_band)) { //increase collateral ratio if(global_collateral_ratio.add(frax_step) >= 1000000){ global_collateral_ratio = 1000000; // cap collateral ratio at 1.000000 } else { global_collateral_ratio = global_collateral_ratio.add(frax_step); } } last_call_time = block.timestamp; // Set the time of the last expansion } /* ========== RESTRICTED FUNCTIONS ========== */ // Used by pools when user redeems function pool_burn_from(address b_address, uint256 b_amount) public onlyPools { super._burnFrom(b_address, b_amount); emit FRAXBurned(b_address, msg.sender, b_amount); } // This function is what other frax pools will call to mint new FRAX function pool_mint(address m_address, uint256 m_amount) public onlyPools { super._mint(m_address, m_amount); emit FRAXMinted(msg.sender, m_address, m_amount); } // Adds collateral addresses supported, such as tether and busd, must be ERC20 function addPool(address pool_address) public onlyByOwnerOrGovernance { require(frax_pools[pool_address] == false, "address already exists"); frax_pools[pool_address] = true; frax_pools_array.push(pool_address); } // Remove a pool function removePool(address pool_address) public onlyByOwnerOrGovernance { require(frax_pools[pool_address] == true, "address doesn't exist already"); // Delete from the mapping delete frax_pools[pool_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < frax_pools_array.length; i++){ if (frax_pools_array[i] == pool_address) { frax_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function setRedemptionFee(uint256 red_fee) public onlyByOwnerOrGovernance { redemption_fee = red_fee; } function setMintingFee(uint256 min_fee) public onlyByOwnerOrGovernance { minting_fee = min_fee; } function setFraxStep(uint256 _new_step) public onlyByOwnerOrGovernance { frax_step = _new_step; } function setPriceTarget (uint256 _new_price_target) public onlyByOwnerOrGovernance { price_target = _new_price_target; } function setRefreshCooldown(uint256 _new_cooldown) public onlyByOwnerOrGovernance { refresh_cooldown = _new_cooldown; } function setFXSAddress(address _fxs_address) public onlyByOwnerOrGovernance { fxs_address = _fxs_address; } function setETHUSDOracle(address _eth_usd_consumer_address) public onlyByOwnerOrGovernance { eth_usd_consumer_address = _eth_usd_consumer_address; eth_usd_pricer = ChainlinkETHUSDPriceConsumer(eth_usd_consumer_address); eth_usd_pricer_decimals = eth_usd_pricer.getDecimals(); } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setController(address _controller_address) external onlyByOwnerOrGovernance { controller_address = _controller_address; } function setPriceBand(uint256 _price_band) external onlyByOwnerOrGovernance { price_band = _price_band; } // Sets the FRAX_ETH Uniswap oracle address function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance { frax_eth_oracle_address = _frax_oracle_addr; fraxEthOracle = UniswapPairOracle(_frax_oracle_addr); weth_address = _weth_address; } // Sets the FXS_ETH Uniswap oracle address function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance { fxs_eth_oracle_address = _fxs_oracle_addr; fxsEthOracle = UniswapPairOracle(_fxs_oracle_addr); weth_address = _weth_address; } function toggleCollateralRatio() public onlyCollateralRatioPauser { collateral_ratio_paused = !collateral_ratio_paused; } /* ========== EVENTS ========== */ // Track FRAX burned event FRAXBurned(address indexed from, address indexed to, uint256 amount); // Track FRAX minted event FRAXMinted(address indexed from, address indexed to, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "../Common/Context.sol"; import "./IERC20.sol"; import "../Math/SafeMath.sol"; import "../Utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address.approve(address spender, uint256 amount) */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of `from`'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of `from`'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ============================= FraxPool ============================= // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../../Math/SafeMath.sol"; import "../../FXS/FXS.sol"; import "../../Frax/Frax.sol"; import "../../ERC20/ERC20.sol"; import "../../Oracle/UniswapPairOracle.sol"; import "../../Governance/AccessControl.sol"; import "./FraxPoolLibrary.sol"; contract FraxPool is AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ ERC20 private collateral_token; address private collateral_address; address private owner_address; address private frax_contract_address; address private fxs_contract_address; address private timelock_address; FRAXShares private FXS; FRAXStablecoin private FRAX; UniswapPairOracle private collatEthOracle; address public collat_eth_oracle_address; address private weth_address; uint256 public minting_fee; uint256 public redemption_fee; uint256 public buyback_fee; uint256 public recollat_fee; mapping (address => uint256) public redeemFXSBalances; mapping (address => uint256) public redeemCollateralBalances; uint256 public unclaimedPoolCollateral; uint256 public unclaimedPoolFXS; mapping (address => uint256) public lastRedeemed; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_MAX = 1e6; // Number of decimals needed to get to 18 uint256 private immutable missing_decimals; // Pool_ceiling is the total units of collateral that a pool contract can hold uint256 public pool_ceiling = 0; // Stores price of the collateral, if price is paused uint256 public pausedPrice = 0; // Bonus rate on FXS minted during recollateralizeFRAX(); 6 decimals of precision, set to 0.75% on genesis uint256 public bonus_rate = 7500; // Number of blocks to wait before being able to collectRedemption() uint256 public redemption_delay = 1; // AccessControl Roles bytes32 private constant MINT_PAUSER = keccak256("MINT_PAUSER"); bytes32 private constant REDEEM_PAUSER = keccak256("REDEEM_PAUSER"); bytes32 private constant BUYBACK_PAUSER = keccak256("BUYBACK_PAUSER"); bytes32 private constant RECOLLATERALIZE_PAUSER = keccak256("RECOLLATERALIZE_PAUSER"); bytes32 private constant COLLATERAL_PRICE_PAUSER = keccak256("COLLATERAL_PRICE_PAUSER"); // AccessControl state variables bool public mintPaused = false; bool public redeemPaused = false; bool public recollateralizePaused = false; bool public buyBackPaused = false; bool public collateralPricePaused = false; /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock"); _; } modifier notRedeemPaused() { require(redeemPaused == false, "Redeeming is paused"); _; } modifier notMintPaused() { require(mintPaused == false, "Minting is paused"); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _frax_contract_address, address _fxs_contract_address, address _collateral_address, address _creator_address, address _timelock_address, uint256 _pool_ceiling ) public { FRAX = FRAXStablecoin(_frax_contract_address); FXS = FRAXShares(_fxs_contract_address); frax_contract_address = _frax_contract_address; fxs_contract_address = _fxs_contract_address; collateral_address = _collateral_address; timelock_address = _timelock_address; owner_address = _creator_address; collateral_token = ERC20(_collateral_address); pool_ceiling = _pool_ceiling; missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); grantRole(MINT_PAUSER, timelock_address); grantRole(REDEEM_PAUSER, timelock_address); grantRole(RECOLLATERALIZE_PAUSER, timelock_address); grantRole(BUYBACK_PAUSER, timelock_address); grantRole(COLLATERAL_PRICE_PAUSER, timelock_address); } /* ========== VIEWS ========== */ // Returns dollar value of collateral held in this Frax pool function collatDollarBalance() public view returns (uint256) { if(collateralPricePaused == true){ return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(pausedPrice).div(PRICE_PRECISION); } else { uint256 eth_usd_price = FRAX.eth_usd_price(); uint256 eth_collat_price = collatEthOracle.consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals))); uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price); return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6); } } // Returns the value of excess collateral held in this Frax pool, compared to what is needed to maintain the global collateral ratio function availableExcessCollatDV() public view returns (uint256) { uint256 total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR > 1 uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio if (global_collat_value > required_collat_dollar_value_d18) return global_collat_value.sub(required_collat_dollar_value_d18); else return 0; } /* ========== PUBLIC FUNCTIONS ========== */ // Returns the price of the pool collateral in USD function getCollateralPrice() public view returns (uint256) { if(collateralPricePaused == true){ return pausedPrice; } else { uint256 eth_usd_price = FRAX.eth_usd_price(); return eth_usd_price.mul(PRICE_PRECISION).div(collatEthOracle.consult(weth_address, PRICE_PRECISION * (10 ** missing_decimals))); } } function setCollatETHOracle(address _collateral_weth_oracle_address, address _weth_address) external onlyByOwnerOrGovernance { collat_eth_oracle_address = _collateral_weth_oracle_address; collatEthOracle = UniswapPairOracle(_collateral_weth_oracle_address); weth_address = _weth_address; } // We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency function mint1t1FRAX(uint256 collateral_amount, uint256 FRAX_out_min) external notMintPaused { uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); require(FRAX.global_collateral_ratio() >= COLLATERAL_RATIO_MAX, "Collateral ratio must be >= 1"); require((collateral_token.balanceOf(address(this))).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "[Pool's Closed]: Ceiling reached"); (uint256 frax_amount_d18) = FraxPoolLibrary.calcMint1t1FRAX( getCollateralPrice(), collateral_amount_d18 ); //1 FRAX for each $1 worth of collateral frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); //remove precision at the end require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached"); collateral_token.transferFrom(msg.sender, address(this), collateral_amount); FRAX.pool_mint(msg.sender, frax_amount_d18); } // 0% collateral-backed function mintAlgorithmicFRAX(uint256 fxs_amount_d18, uint256 FRAX_out_min) external notMintPaused { uint256 fxs_price = FRAX.fxs_price(); require(FRAX.global_collateral_ratio() == 0, "Collateral ratio must be 0"); (uint256 frax_amount_d18) = FraxPoolLibrary.calcMintAlgorithmicFRAX( fxs_price, // X FXS / 1 USD fxs_amount_d18 ); frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached"); FXS.pool_burn_from(msg.sender, fxs_amount_d18); FRAX.pool_mint(msg.sender, frax_amount_d18); } // Will fail if fully collateralized or fully algorithmic // > 0% and < 100% collateral-backed function mintFractionalFRAX(uint256 collateral_amount, uint256 fxs_amount, uint256 FRAX_out_min) external notMintPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); require(collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "Pool ceiling reached, no more FRAX can be minted with this collateral"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); FraxPoolLibrary.MintFF_Params memory input_params = FraxPoolLibrary.MintFF_Params( fxs_price, getCollateralPrice(), fxs_amount, collateral_amount_d18, global_collateral_ratio ); (uint256 mint_amount, uint256 fxs_needed) = FraxPoolLibrary.calcMintFractionalFRAX(input_params); mint_amount = (mint_amount.mul(uint(1e6).sub(minting_fee))).div(1e6); require(FRAX_out_min <= mint_amount, "Slippage limit reached"); require(fxs_needed <= fxs_amount, "Not enough FXS inputted"); FXS.pool_burn_from(msg.sender, fxs_needed); collateral_token.transferFrom(msg.sender, address(this), collateral_amount); FRAX.pool_mint(msg.sender, mint_amount); } // Redeem collateral. 100% collateral-backed function redeem1t1FRAX(uint256 FRAX_amount, uint256 COLLATERAL_out_min) external notRedeemPaused { require(FRAX.global_collateral_ratio() == COLLATERAL_RATIO_MAX, "Collateral ratio must be == 1"); // Need to adjust for decimals of collateral uint256 FRAX_amount_precision = FRAX_amount.div(10 ** missing_decimals); (uint256 collateral_needed) = FraxPoolLibrary.calcRedeem1t1FRAX( getCollateralPrice(), FRAX_amount_precision ); collateral_needed = (collateral_needed.mul(uint(1e6).sub(redemption_fee))).div(1e6); require(collateral_needed <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_needed, "Slippage limit reached"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); } // Will fail if fully collateralized or algorithmic // Redeem FRAX for collateral and FXS. > 0% and < 100% collateral-backed function redeemFractionalFRAX(uint256 FRAX_amount, uint256 FXS_out_min, uint256 COLLATERAL_out_min) external notRedeemPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); uint256 col_price_usd = getCollateralPrice(); uint256 FRAX_amount_post_fee = (FRAX_amount.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); uint256 fxs_dollar_value_d18 = FRAX_amount_post_fee.sub(FRAX_amount_post_fee.mul(global_collateral_ratio).div(PRICE_PRECISION)); uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price); // Need to adjust for decimals of collateral uint256 FRAX_amount_precision = FRAX_amount_post_fee.div(10 ** missing_decimals); uint256 collateral_dollar_value = FRAX_amount_precision.mul(global_collateral_ratio).div(PRICE_PRECISION); uint256 collateral_amount = collateral_dollar_value.mul(PRICE_PRECISION).div(col_price_usd); require(collateral_amount <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_amount, "Slippage limit reached [collateral]"); require(FXS_out_min <= fxs_amount, "Slippage limit reached [FXS]"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount); redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount); unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); FXS.pool_mint(address(this), fxs_amount); } // Redeem FRAX for FXS. 0% collateral-backed function redeemAlgorithmicFRAX(uint256 FRAX_amount, uint256 FXS_out_min) external notRedeemPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio == 0, "Collateral ratio must be 0"); uint256 fxs_dollar_value_d18 = FRAX_amount; fxs_dollar_value_d18 = (fxs_dollar_value_d18.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); //apply fees uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price); redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount); unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount); lastRedeemed[msg.sender] = block.number; require(FXS_out_min <= fxs_amount, "Slippage limit reached"); // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); FXS.pool_mint(address(this), fxs_amount); } // After a redemption happens, transfer the newly minted FXS and owed collateral from this pool // contract to the user. Redemption is split into two functions to prevent flash loans from being able // to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system. function collectRedemption() external { require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Must wait for redemption_delay blocks before collecting redemption"); bool sendFXS = false; bool sendCollateral = false; uint FXSAmount; uint CollateralAmount; // Use Checks-Effects-Interactions pattern if(redeemFXSBalances[msg.sender] > 0){ FXSAmount = redeemFXSBalances[msg.sender]; redeemFXSBalances[msg.sender] = 0; unclaimedPoolFXS = unclaimedPoolFXS.sub(FXSAmount); sendFXS = true; } if(redeemCollateralBalances[msg.sender] > 0){ CollateralAmount = redeemCollateralBalances[msg.sender]; redeemCollateralBalances[msg.sender] = 0; unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount); sendCollateral = true; } if(sendFXS == true){ FXS.transfer(msg.sender, FXSAmount); } if(sendCollateral == true){ collateral_token.transfer(msg.sender, CollateralAmount); } } // When the protocol is recollateralizing, we need to give a discount of FXS to hit the new CR target // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get FXS for adding collateral // This function simply rewards anyone that sends collateral to a pool with the same amount of FXS + the bonus rate // Anyone can call this function to recollateralize the protocol and take the extra FXS value from the bonus rate as an arb opportunity function recollateralizeFRAX(uint256 collateral_amount, uint256 FXS_out_min) external { require(recollateralizePaused == false, "Recollateralize is paused"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); uint256 fxs_price = FRAX.fxs_price(); uint256 frax_total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); (uint256 collateral_units, uint256 amount_to_recollat) = FraxPoolLibrary.calcRecollateralizeFRAXInner( collateral_amount_d18, getCollateralPrice(), global_collat_value, frax_total_supply, global_collateral_ratio ); uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals); uint256 fxs_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate).sub(recollat_fee)).div(fxs_price); require(FXS_out_min <= fxs_paid_back, "Slippage limit reached"); collateral_token.transferFrom(msg.sender, address(this), collateral_units_precision); FXS.pool_mint(msg.sender, fxs_paid_back); } // Function can be called by an FXS holder to have the protocol buy back FXS with excess collateral value from a desired collateral pool // This can also happen if the collateral ratio > 1 function buyBackFXS(uint256 FXS_amount, uint256 COLLATERAL_out_min) external { require(buyBackPaused == false, "Buyback is paused"); uint256 fxs_price = FRAX.fxs_price(); FraxPoolLibrary.BuybackFXS_Params memory input_params = FraxPoolLibrary.BuybackFXS_Params( availableExcessCollatDV(), fxs_price, getCollateralPrice(), FXS_amount ); (uint256 collateral_equivalent_d18) = (FraxPoolLibrary.calcBuyBackFXS(input_params)).mul(uint(1e6).sub(buyback_fee)).div(1e6); uint256 collateral_precision = collateral_equivalent_d18.div(10 ** missing_decimals); require(COLLATERAL_out_min <= collateral_precision, "Slippage limit reached"); // Give the sender their desired collateral and burn the FXS FXS.pool_burn_from(msg.sender, FXS_amount); collateral_token.transfer(msg.sender, collateral_precision); } /* ========== RESTRICTED FUNCTIONS ========== */ function toggleMinting() external { require(hasRole(MINT_PAUSER, msg.sender)); mintPaused = !mintPaused; } function toggleRedeeming() external { require(hasRole(REDEEM_PAUSER, msg.sender)); redeemPaused = !redeemPaused; } function toggleRecollateralize() external { require(hasRole(RECOLLATERALIZE_PAUSER, msg.sender)); recollateralizePaused = !recollateralizePaused; } function toggleBuyBack() external { require(hasRole(BUYBACK_PAUSER, msg.sender)); buyBackPaused = !buyBackPaused; } function toggleCollateralPrice(uint256 _new_price) external { require(hasRole(COLLATERAL_PRICE_PAUSER, msg.sender)); // If pausing, set paused price; else if unpausing, clear pausedPrice if(collateralPricePaused == false){ pausedPrice = _new_price; } else { pausedPrice = 0; } collateralPricePaused = !collateralPricePaused; } // Combined into one function due to 24KiB contract memory limit function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee) external onlyByOwnerOrGovernance { pool_ceiling = new_ceiling; bonus_rate = new_bonus_rate; redemption_delay = new_redemption_delay; minting_fee = new_mint_fee; redemption_fee = new_redeem_fee; buyback_fee = new_buyback_fee; recollat_fee = new_recollat_fee; } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } /* ========== EVENTS ========== */ } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import '../Uniswap/Interfaces/IUniswapV2Factory.sol'; import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; import '../Math/FixedPoint.sol'; import '../Uniswap/UniswapV2OracleLibrary.sol'; import '../Uniswap/UniswapV2Library.sol'; // Fixed window oracle that recomputes the average price for the entire period once every period // Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period contract UniswapPairOracle { using FixedPoint for *; address owner_address; address timelock_address; uint public PERIOD = 3600; // 1 hour TWAP (time-weighted average price) uint public CONSULT_LENIENCY = 120; // Used for being able to consult past the period end bool public ALLOW_STALE_CONSULTS = false; // If false, consult() will fail if the TWAP is stale IUniswapV2Pair public immutable pair; address public immutable token0; address public immutable token1; uint public price0CumulativeLast; uint public price1CumulativeLast; uint32 public blockTimestampLast; FixedPoint.uq112x112 public price0Average; FixedPoint.uq112x112 public price1Average; modifier onlyByOwnerOrGovernance() { require(msg.sender == owner_address || msg.sender == timelock_address, "You are not an owner or the governance timelock"); _; } constructor(address factory, address tokenA, address tokenB, address _owner_address, address _timelock_address) public { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB)); pair = _pair; token0 = _pair.token0(); token1 = _pair.token1(); price0CumulativeLast = _pair.price0CumulativeLast(); // Fetch the current accumulated price value (1 / 0) price1CumulativeLast = _pair.price1CumulativeLast(); // Fetch the current accumulated price value (0 / 1) uint112 reserve0; uint112 reserve1; (reserve0, reserve1, blockTimestampLast) = _pair.getReserves(); require(reserve0 != 0 && reserve1 != 0, 'UniswapPairOracle: NO_RESERVES'); // Ensure that there's liquidity in the pair owner_address = _owner_address; timelock_address = _timelock_address; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function setTimelock(address _timelock_address) external onlyByOwnerOrGovernance { timelock_address = _timelock_address; } function setPeriod(uint _period) external onlyByOwnerOrGovernance { PERIOD = _period; } function setConsultLeniency(uint _consult_leniency) external onlyByOwnerOrGovernance { CONSULT_LENIENCY = _consult_leniency; } function setAllowStaleConsults(bool _allow_stale_consults) external onlyByOwnerOrGovernance { ALLOW_STALE_CONSULTS = _allow_stale_consults; } // Check if update() can be called instead of wasting gas calling it function canUpdate() public view returns (bool) { uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired return (timeElapsed >= PERIOD); } function update() external { (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired // Ensure that at least one full period has passed since the last update require(timeElapsed >= PERIOD, 'UniswapPairOracle: PERIOD_NOT_ELAPSED'); // Overflow is desired, casting never truncates // Cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)); price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)); price0CumulativeLast = price0Cumulative; price1CumulativeLast = price1Cumulative; blockTimestampLast = blockTimestamp; } // Note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint amountIn) external view returns (uint amountOut) { uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired // Ensure that the price is not stale require((timeElapsed < (PERIOD + CONSULT_LENIENCY)) || ALLOW_STALE_CONSULTS, 'UniswapPairOracle: PRICE_IS_STALE_NEED_TO_CALL_UPDATE'); if (token == token0) { amountOut = price0Average.mul(amountIn).decode144(); } else { require(token == token1, 'UniswapPairOracle: INVALID_TOKEN'); amountOut = price1Average.mul(amountIn).decode144(); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../Utils/EnumerableSet.sol"; import "../Utils/Address.sol"; import "../Common/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; //bytes32(uint256(0x4B437D01b575618140442A4975db38850e3f8f5f) << 96); /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================= FraxPoolInvestorForV2 ====================== // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian import "../Math/SafeMath.sol"; import "../FXS/FXS.sol"; import "../Frax/Frax.sol"; import "../ERC20/ERC20.sol"; import "../ERC20/Variants/Comp.sol"; import "../Oracle/UniswapPairOracle.sol"; import "../Governance/AccessControl.sol"; import "../Frax/Pools/FraxPool.sol"; import "./yearn/IyUSDC_V2_Partial.sol"; import "./aave/IAAVELendingPool_Partial.sol"; import "./aave/IAAVE_aUSDC_Partial.sol"; import "./compound/ICompComptrollerPartial.sol"; import "./compound/IcUSDC_Partial.sol"; // Lower APY: yearn, AAVE, Compound // Higher APY: KeeperDAO, BZX, Harvest contract FraxPoolInvestorForV2 is AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ ERC20 private collateral_token; FRAXShares private FXS; FRAXStablecoin private FRAX; FraxPool private pool; // Pools and vaults IyUSDC_V2_Partial private yUSDC_V2 = IyUSDC_V2_Partial(0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9); IAAVELendingPool_Partial private aaveUSDC_Pool = IAAVELendingPool_Partial(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); IAAVE_aUSDC_Partial private aaveUSDC_Token = IAAVE_aUSDC_Partial(0xBcca60bB61934080951369a648Fb03DF4F96263C); IcUSDC_Partial private cUSDC = IcUSDC_Partial(0x39AA39c021dfbaE8faC545936693aC917d5E7563); // Reward Tokens Comp private COMP = Comp(0xc00e94Cb662C3520282E6f5717214004A7f26888); ICompComptrollerPartial private CompController = ICompComptrollerPartial(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address public collateral_address; address public pool_address; address public owner_address; address public timelock_address; address public custodian_address; address public weth_address = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 public immutable missing_decimals; uint256 private constant PRICE_PRECISION = 1e6; // Max amount of collateral this contract can borrow from the FraxPool uint256 public borrow_cap = uint256(20000e6); // Amount the contract borrowed uint256 public borrowed_balance = 0; uint256 public borrowed_historical = 0; uint256 public paid_back_historical = 0; // Allowed strategies (can eventually be made into an array) bool public allow_yearn = true; bool public allow_aave = true; bool public allow_compound = true; /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock"); _; } modifier onlyCustodian() { require(msg.sender == custodian_address, "You are not the rewards custodian"); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _frax_contract_address, address _fxs_contract_address, address _pool_address, address _collateral_address, address _owner_address, address _custodian_address, address _timelock_address ) public { FRAX = FRAXStablecoin(_frax_contract_address); FXS = FRAXShares(_fxs_contract_address); pool_address = _pool_address; pool = FraxPool(_pool_address); collateral_address = _collateral_address; collateral_token = ERC20(_collateral_address); timelock_address = _timelock_address; owner_address = _owner_address; custodian_address = _custodian_address; missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /* ========== VIEWS ========== */ function showAllocations() external view returns (uint256[5] memory allocations) { // IMPORTANT // Should ONLY be used externally, because it may fail if any one of the functions below fail // All numbers given are assuming xyzUSDC, etc. is converted back to actual USDC allocations[0] = collateral_token.balanceOf(address(this)); // Unallocated allocations[1] = (yUSDC_V2.balanceOf(address(this))).mul(yUSDC_V2.pricePerShare()).div(1e6); // yearn allocations[2] = aaveUSDC_Token.balanceOf(address(this)); // AAVE allocations[3] = (cUSDC.balanceOf(address(this)).mul(cUSDC.exchangeRateStored()).div(1e18)); // Compound. Note that cUSDC is E8 uint256 sum_tally = 0; for (uint i = 1; i < 5; i++){ if (allocations[i] > 0){ sum_tally = sum_tally.add(allocations[i]); } } allocations[4] = sum_tally; // Total Staked } function showRewards() external view returns (uint256[1] memory rewards) { // IMPORTANT // Should ONLY be used externally, because it may fail if COMP.balanceOf() fails rewards[0] = COMP.balanceOf(address(this)); // COMP } /* ========== PUBLIC FUNCTIONS ========== */ // Needed for the Frax contract to function function collatDollarBalance() external view returns (uint256) { // Needs to mimic the FraxPool value and return in E18 // Only thing different should be borrowed_balance vs balanceOf() if(pool.collateralPricePaused() == true){ return borrowed_balance.mul(10 ** missing_decimals).mul(pool.pausedPrice()).div(PRICE_PRECISION); } else { uint256 eth_usd_price = FRAX.eth_usd_price(); uint256 eth_collat_price = UniswapPairOracle(pool.collat_eth_oracle_address()).consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals))); uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price); return borrowed_balance.mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6); } } // This is basically a workaround to transfer USDC from the FraxPool to this investor contract // This contract is essentially marked as a 'pool' so it can call OnlyPools functions like pool_mint and pool_burn_from // on the main FRAX contract // It mints FRAX from nothing, and redeems it on the target pool for collateral and FXS // The burn can be called separately later on function mintRedeemPart1(uint256 frax_amount) public onlyByOwnerOrGovernance { require(allow_yearn || allow_aave || allow_compound, 'All strategies are currently off'); uint256 redemption_fee = pool.redemption_fee(); uint256 col_price_usd = pool.getCollateralPrice(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 redeem_amount_E6 = (frax_amount.mul(uint256(1e6).sub(redemption_fee))).div(1e6).div(10 ** missing_decimals); uint256 expected_collat_amount = redeem_amount_E6.mul(global_collateral_ratio).div(1e6); expected_collat_amount = expected_collat_amount.mul(1e6).div(col_price_usd); require(borrowed_balance.add(expected_collat_amount) <= borrow_cap, "Borrow cap reached"); borrowed_balance = borrowed_balance.add(expected_collat_amount); borrowed_historical = borrowed_historical.add(expected_collat_amount); // Mint the frax FRAX.pool_mint(address(this), frax_amount); // Redeem the frax FRAX.approve(address(pool), frax_amount); pool.redeemFractionalFRAX(frax_amount, 0, 0); } function mintRedeemPart2() public onlyByOwnerOrGovernance { pool.collectRedemption(); } function giveCollatBack(uint256 amount) public onlyByOwnerOrGovernance { // Still paying back principal if (amount <= borrowed_balance) { borrowed_balance = borrowed_balance.sub(amount); } // Pure profits else { borrowed_balance = 0; } paid_back_historical = paid_back_historical.add(amount); collateral_token.transfer(address(pool), amount); } function burnFXS(uint256 amount) public onlyByOwnerOrGovernance { FXS.approve(address(this), amount); FXS.pool_burn_from(address(this), amount); } /* ========== yearn V2 ========== */ function yDepositUSDC(uint256 USDC_amount) public onlyByOwnerOrGovernance { require(allow_yearn, 'yearn strategy is currently off'); collateral_token.approve(address(yUSDC_V2), USDC_amount); yUSDC_V2.deposit(USDC_amount); } // E6 function yWithdrawUSDC(uint256 yUSDC_amount) public onlyByOwnerOrGovernance { yUSDC_V2.withdraw(yUSDC_amount); } /* ========== AAVE V2 ========== */ function aaveDepositUSDC(uint256 USDC_amount) public onlyByOwnerOrGovernance { require(allow_aave, 'AAVE strategy is currently off'); collateral_token.approve(address(aaveUSDC_Pool), USDC_amount); aaveUSDC_Pool.deposit(collateral_address, USDC_amount, address(this), 0); } // E6 function aaveWithdrawUSDC(uint256 aUSDC_amount) public onlyByOwnerOrGovernance { aaveUSDC_Pool.withdraw(collateral_address, aUSDC_amount, address(this)); } /* ========== Compound cUSDC + COMP ========== */ function compoundMint_cUSDC(uint256 USDC_amount) public onlyByOwnerOrGovernance { require(allow_compound, 'Compound strategy is currently off'); collateral_token.approve(address(cUSDC), USDC_amount); cUSDC.mint(USDC_amount); } // E8 function compoundRedeem_cUSDC(uint256 cUSDC_amount) public onlyByOwnerOrGovernance { // NOTE that cUSDC is E8, NOT E6 cUSDC.redeem(cUSDC_amount); } function compoundCollectCOMP() public onlyByOwnerOrGovernance { address[] memory cTokens = new address[](1); cTokens[0] = address(cUSDC); CompController.claimComp(address(this), cTokens); // CompController.claimComp(address(this), ); } /* ========== Custodian ========== */ function withdrawRewards() public onlyCustodian { COMP.transfer(custodian_address, COMP.balanceOf(address(this))); } /* ========== RESTRICTED FUNCTIONS ========== */ function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function setWethAddress(address _weth_address) external onlyByOwnerOrGovernance { weth_address = _weth_address; } function setMiscRewardsCustodian(address _custodian_address) external onlyByOwnerOrGovernance { custodian_address = _custodian_address; } function setPool(address _pool_address) external onlyByOwnerOrGovernance { pool_address = _pool_address; pool = FraxPool(_pool_address); } function setBorrowCap(uint256 _borrow_cap) external onlyByOwnerOrGovernance { borrow_cap = _borrow_cap; } function setAllowedStrategies(bool _yearn, bool _aave, bool _compound) external onlyByOwnerOrGovernance { allow_yearn = _yearn; allow_aave = _aave; allow_compound = _compound; } function emergencyRecoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard ERC20(tokenAddress).transfer(custodian_address, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } /* ========== EVENTS ========== */ event Recovered(address token, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import './Interfaces/IUniswapV2Factory.sol'; import './TransferHelper.sol'; import './Interfaces/IUniswapV2Router02.sol'; import './UniswapV2Library.sol'; import '../Math/SafeMath.sol'; import '../ERC20/IERC20.sol'; import '../ERC20/IWETH.sol'; contract UniswapV2Router02_Modified is IUniswapV2Router02 { using SafeMath for uint; address public immutable override factory; address public immutable override WETH; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED'); _; } constructor(address _factory, address _WETH) public { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) { IUniswapV2Factory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IUniswapV2Pair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = UniswapV2Library.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); TransferHelper.safeTransferFrom(WETH, msg.sender, pair, amountETH); // IWETH(WETH).transferFrom(msg.sender, pair, amountETH); // IWETH(WETH).deposit{value: amountETH}(); // assert(IWETH(WETH).transfer(pair, amountETH)); // require(false, "HELLO: HOW ARE YOU TODAY!"); liquidity = IUniswapV2Pair(pair).mint(to); // << PROBLEM IS HERE // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to); (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountA, uint amountB) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountToken, uint amountETH) { address pair = UniswapV2Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountETH) { address pair = UniswapV2Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UniswapV2Library.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { // for (uint i; i < path.length - 1; i++) { // (address input, address output) = (path[i], path[i + 1]); // (address token0,) = UniswapV2Library.sortTokens(input, output); // IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)); // uint amountInput; // uint amountOutput; // { // scope to avoid stack too deep errors // (uint reserve0, uint reserve1,) = pair.getReserves(); // (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); // amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); // amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput); // } // (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); // address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; // pair.swap(amount0Out, amount1Out, to, new bytes(0)); // } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { // TransferHelper.safeTransferFrom( // path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn // ); // uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); // _swapSupportingFeeOnTransferTokens(path, to); // require( // IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, // 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT' // ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { // require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); // uint amountIn = msg.value; // IWETH(WETH).deposit{value: amountIn}(); // assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn)); // uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); // _swapSupportingFeeOnTransferTokens(path, to); // require( // IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, // 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT' // ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { // require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); // TransferHelper.safeTransferFrom( // path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn // ); // _swapSupportingFeeOnTransferTokens(path, address(this)); // uint amountOut = IERC20(WETH).balanceOf(address(this)); // require(amountOut >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); // IWETH(WETH).withdraw(amountOut); // TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return UniswapV2Library.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { return UniswapV2Library.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { return UniswapV2Library.getAmountsIn(factory, amountOut, path); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "../Common/Context.sol"; import "./IERC20.sol"; import "../Math/SafeMath.sol"; import "../Utils/Address.sol"; // Due to compiling issues, _name, _symbol, and _decimals were removed /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Custom is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address.approve(address spender, uint256 amount) */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of `from`'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of `from`'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "../Common/Context.sol"; import "../Math/SafeMath.sol"; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "./AggregatorV3Interface.sol"; contract ChainlinkETHUSDPriceConsumer { AggregatorV3Interface internal priceFeed; constructor() public { priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } function getDecimals() public view returns (uint8) { return priceFeed.decimals(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../Math/SafeMath.sol"; library FraxPoolLibrary { using SafeMath for uint256; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; // ================ Structs ================ // Needed to lower stack size struct MintFF_Params { uint256 fxs_price_usd; uint256 col_price_usd; uint256 fxs_amount; uint256 collateral_amount; uint256 col_ratio; } struct BuybackFXS_Params { uint256 excess_collateral_dollar_value_d18; uint256 fxs_price_usd; uint256 col_price_usd; uint256 FXS_amount; } // ================ Functions ================ function calcMint1t1FRAX(uint256 col_price, uint256 collateral_amount_d18) public pure returns (uint256) { return (collateral_amount_d18.mul(col_price)).div(1e6); } function calcMintAlgorithmicFRAX(uint256 fxs_price_usd, uint256 fxs_amount_d18) public pure returns (uint256) { return fxs_amount_d18.mul(fxs_price_usd).div(1e6); } // Must be internal because of the struct function calcMintFractionalFRAX(MintFF_Params memory params) internal pure returns (uint256, uint256) { // Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error // The contract must check the proper ratio was sent to mint FRAX. We do this by seeing the minimum mintable FRAX based on each amount uint256 fxs_dollar_value_d18; uint256 c_dollar_value_d18; // Scoping for stack concerns { // USD amounts of the collateral and the FXS fxs_dollar_value_d18 = params.fxs_amount.mul(params.fxs_price_usd).div(1e6); c_dollar_value_d18 = params.collateral_amount.mul(params.col_price_usd).div(1e6); } uint calculated_fxs_dollar_value_d18 = (c_dollar_value_d18.mul(1e6).div(params.col_ratio)) .sub(c_dollar_value_d18); uint calculated_fxs_needed = calculated_fxs_dollar_value_d18.mul(1e6).div(params.fxs_price_usd); return ( c_dollar_value_d18.add(calculated_fxs_dollar_value_d18), calculated_fxs_needed ); } function calcRedeem1t1FRAX(uint256 col_price_usd, uint256 FRAX_amount) public pure returns (uint256) { return FRAX_amount.mul(1e6).div(col_price_usd); } // Must be internal because of the struct function calcBuyBackFXS(BuybackFXS_Params memory params) internal pure returns (uint256) { // If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible FXS with the desired collateral require(params.excess_collateral_dollar_value_d18 > 0, "No excess collateral to buy back!"); // Make sure not to take more than is available uint256 fxs_dollar_value_d18 = params.FXS_amount.mul(params.fxs_price_usd).div(1e6); require(fxs_dollar_value_d18 <= params.excess_collateral_dollar_value_d18, "You are trying to buy back more than the excess!"); // Get the equivalent amount of collateral based on the market value of FXS provided uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(1e6).div(params.col_price_usd); //collateral_equivalent_d18 = collateral_equivalent_d18.sub((collateral_equivalent_d18.mul(params.buyback_fee)).div(1e6)); return ( collateral_equivalent_d18 ); } // Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization) function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) { uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6 // Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize return target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow // return(recollateralization_left); } function calcRecollateralizeFRAXInner( uint256 collateral_amount, uint256 col_price, uint256 global_collat_value, uint256 frax_total_supply, uint256 global_collateral_ratio ) public pure returns (uint256, uint256) { uint256 collat_value_attempted = collateral_amount.mul(col_price).div(1e6); uint256 effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6 uint256 recollat_possible = (global_collateral_ratio.mul(frax_total_supply).sub(frax_total_supply.mul(effective_collateral_ratio))).div(1e6); uint256 amount_to_recollat; if(collat_value_attempted <= recollat_possible){ amount_to_recollat = collat_value_attempted; } else { amount_to_recollat = recollat_possible; } return (amount_to_recollat.mul(1e6).div(col_price), amount_to_recollat); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import './Babylonian.sol'; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; uint private constant Q112 = uint(1) << RESOLUTION; uint private constant Q224 = Q112 << RESOLUTION; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // take the reciprocal of a UQ112x112 function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; import '../Math/FixedPoint.sol'; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import './Interfaces/IUniswapV2Pair.sol'; import './Interfaces/IUniswapV2Factory.sol'; import "../Math/SafeMath.sol"; library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // Less efficient than the CREATE2 method below function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = IUniswapV2Factory(factory).getPair(token0, token1); } // calculates the CREATE2 address for a pair without making any external calls function pairForCreate2(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); // this matches the CREATE2 in UniswapV2Factory.createPair } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT /** *Submitted for verification at Etherscan.io on 2020-03-04 */ pragma solidity 0.6.11; pragma experimental ABIEncoderV2; contract Comp { /// @notice EIP-20 token name for this token string public constant name = "Compound"; /// @notice EIP-20 token symbol for this token string public constant symbol = "COMP"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public constant totalSupply = 10000000e18; // 10 million Comp /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 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 The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Comp token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { 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) public { 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), "Comp::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce"); require(now <= expiry, "Comp::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 (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Comp::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]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "Comp::_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 safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import '../../ERC20/IERC20.sol'; // https://etherscan.io/address/0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9 // Some functions were omitted for brevity. See the contract for details interface IyUSDC_V2_Partial is IERC20 { function balance() external returns (uint); function available() external returns (uint); function earn() external; function deposit(uint _amount) external; function withdraw(uint _shares) external; function pricePerShare() external view returns (uint); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import '../../ERC20/IERC20.sol'; // Original at https://etherscan.io/address/0xc6845a5c768bf8d7681249f8927877efda425baf#code // Address [0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9] used is a proxy // Some functions were omitted for brevity. See the contract for details interface IAAVELendingPool_Partial is IERC20 { /** * @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); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import '../../ERC20/IERC20.sol'; // Original at https://etherscan.io/address/0xbCe3076b0d8EB2f640D4089A4929fE8c1a438213#code // Address [0xBcca60bB61934080951369a648Fb03DF4F96263C] used is a proxy // Some functions were omitted for brevity. See the contract for details interface IAAVE_aUSDC_Partial is IERC20 { } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // Original at https://etherscan.io/address/0xbe7616B06f71e363A310Aa8CE8aD99654401ead7#code // Address [0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B] used is a proxy // Some functions were omitted for brevity. See the contract for details interface ICompComptrollerPartial { function claimComp(address holder) external; function claimComp(address holder, address[] memory cTokens) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import '../../ERC20/IERC20.sol'; // Original at https://etherscan.io/address/0x39aa39c021dfbae8fac545936693ac917d5e7563#code // Some functions were omitted for brevity. See the contract for details // https://compound.finance/docs/ctokens interface IcUSDC_Partial is IERC20 { function mint(uint mintAmount) external returns (uint); // redeemAmount = # of cUSDC function redeem(uint redeemAmount) external returns (uint); // redeemAmount = # of USDC function redeemUnderlying(uint redeemAmount) external returns (uint); // Multiply this by the E8 balance of cUSDC, then divide the product by E16 function exchangeRateStored() external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function transferFrom(address src, address dst, uint wad) external returns (bool); function withdraw(uint) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); }
From compound's _moveDelegates Keep track of votes. "Delegates" is a misnomer here
function trackVotes(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "FXS::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "FXS::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } }
220,976
// SPDX-License-Identifier: GPL-3.0 /// @title The Wizards DAO Auction House // LICENSE // AuctionHouse.sol is a modified version of the Nouns's Auction house. // https://github.com/nounsDAO/nouns-monorepo/blob/master/packages/nouns-contracts/contracts/NounsAuctionHouse.sol // // AuctionHouse.sol source code Copyright Zora licensed under the GPL-3.0 license. // With modifications by Nounders DAO and Wizards DAO. pragma solidity ^0.8.6; import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IAuctionHouse} from "./IAuctionHouse.sol"; import {IWizardToken} from "../IWizards.sol"; import {IWETH} from "../IWETH.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract AuctionHouse is IAuctionHouse, PausableUpgradeable, ReentrancyGuardUpgradeable, OwnableUpgradeable { using SafeMath for uint256; // The address of the creators of WizardDAO address public creatorsDAO; address public daoWallet; uint256 public creatorFeePercent; // The Wizards ERC721 token contract IWizardToken public wizards; // The address of the WETH contract address public weth; // The minimum amount of time left in an auction after a new bid is created uint256 public timeBuffer; // The minimum price accepted in an auction uint256 public reservePrice; // The minimum percentage difference between the last bid amount and the current bid uint8 public minBidIncrementPercentage; // The duration of a single auction uint256 public duration; // The maximum amount of wizards that can be minted. uint256 public wizardCap; // we have reached the cap for total supply of wizards. bool public reachedCap; // The last wizardId minted for an auction. uint256 public lastWizardId; // The oneOfOneId to mint. uint48 public oneOfOneId; // To include 1-1 wizards in the auction bool public auctionOneOfOne; // RH: // Whitelist addresses mapping(uint256 => address) public whitelistAddrs; // Number of addresses in the current whitelist uint256 public whitelistSize; // The active auctions mapping(uint256 => IAuctionHouse.Auction) public auctions; uint8 public auctionCount; /** * @notice Require that the sender is the creators DAO. */ modifier onlyCreatorsDAO() { require(msg.sender == creatorsDAO, "Sender is not the creators DAO"); _; } /** * @notice Initialize the auction house and base contracts, * populate configuration values, and pause the contract. * @dev This function can only be called once. */ function initialize( IWizardToken _wizards, address _creatorsDAO, address _daoWallet, address _weth, uint256 _timeBuffer, uint256 _reservePrice, uint8 _minBidIncrementPercentage, uint256 _duration, bool _auctionOneOfOne, uint256 _wizardCap ) external initializer { __Pausable_init(); __ReentrancyGuard_init(); __Ownable_init(); _pause(); creatorsDAO = _creatorsDAO; daoWallet = _daoWallet; // total of 5 wizards can be auctioned at a given time. auctionCount = 5; creatorFeePercent = 10; auctionOneOfOne = _auctionOneOfOne; wizards = _wizards; weth = _weth; timeBuffer = _timeBuffer; reservePrice = _reservePrice; minBidIncrementPercentage = _minBidIncrementPercentage; duration = _duration; wizardCap = _wizardCap; } /** * @notice Set the creators wallet address. * @dev Only callable by WizardsDAO. */ function setCreatorsDAO(address _creatorsDAO) external override onlyCreatorsDAO { creatorsDAO = _creatorsDAO; emit CreatorsDAOUpdated(_creatorsDAO); } /** * @notice Set the WizardsDAO wallet address. * @dev Only callable by owner. */ function setDAOWallet(address _daoWallet) external override onlyOwner { daoWallet = _daoWallet; emit DAOWalletUpdated(_daoWallet); } /** * @notice Settle all current auctions, mint new Wizards, and put them up for auction. */ function settleCurrentAndCreateNewAuction() external override nonReentrant whenNotPaused { require(lastWizardId < wizardCap, "All wizards have been auctioned"); // ensure all auctions have ended. for (uint256 i = 5; i >= 1; i--) { require( block.timestamp >= auctions[i].endTime, "All auctions have not completed" ); } // settle past auctions for (uint256 i = 1; i <= 5; i++) { _settleAuction(i); } // RH: // refresh whitelist if whitelistDay if (auctions[1].isWhitelistDay) { _refreshWhitelist(); } // start 5 new auctions for (uint256 i = 1; i <= 5; i++) { if (lastWizardId <= wizardCap && !reachedCap) { _createAuction(i); } } if ((lastWizardId == wizardCap) || reachedCap) { emit AuctionCapReached(wizardCap); } } /** * @notice Settle the current auction. * @dev This function can only be called when the contract is paused. */ function settleAuction(uint256 aId) external override whenPaused nonReentrant { _settleAuction(aId); } /** * @notice Create a bid for a Wizard with a given amount. * @dev This contract only accepts payment in ETH. */ function createBid(uint256 wizardId, uint256 aId) external payable override nonReentrant { IAuctionHouse.Auction memory _auction = auctions[aId]; require( (aId <= auctionCount) && (aId >= 1), "Auction Id is not currently open" ); require(_auction.wizardId == wizardId, "Wizard not up for auction"); require(block.timestamp < _auction.endTime, "Auction expired"); require(msg.value >= reservePrice, "Must send at least reservePrice"); require( msg.value >= _auction.amount + ((_auction.amount * minBidIncrementPercentage) / 100), "Must send more than last bid by minBidIncrementPercentage amount" ); // RH: // ensure bidder is in whitelist if (_auction.isWhitelistDay) { bool bidderInWhitelist; for (uint256 i = 0; i < whitelistSize; i += 1) { if (whitelistAddrs[i] == msg.sender) { bidderInWhitelist = true; break; } } require(bidderInWhitelist, "Bidder is not on whitelist"); } address payable lastBidder = _auction.bidder; // refund the last bidder, if applicable if (lastBidder != address(0)) { _safeTransferETHWithFallback(lastBidder, _auction.amount); } auctions[aId].amount = msg.value; auctions[aId].bidder = payable(msg.sender); // Extend the auction if the bid was received within `timeBuffer` of the auction end time bool extended = _auction.endTime - block.timestamp < timeBuffer; if (extended) { auctions[aId].endTime = _auction.endTime = block.timestamp + timeBuffer; } emit AuctionBid( _auction.wizardId, aId, msg.sender, msg.value, extended ); if (extended) { emit AuctionExtended(_auction.wizardId, aId, _auction.endTime); } } /** * @notice Pause the auction house. * @dev This function can only be called by the owner when the * contract is unpaused. While no new auctions can be started when paused, * anyone can settle an ongoing auction. */ function pause() external override onlyOwner { _pause(); } /** * @notice Unpause the auction house. * @dev This function can only be called by the owner when the * contract is paused. If required, this function will start a new auction. */ function unpause() external override onlyOwner { _unpause(); for (uint256 i = 1; i <= 5; i++) { IAuctionHouse.Auction memory _a = auctions[i]; if (_a.startTime == 0 || _a.settled) { if (lastWizardId <= wizardCap && !reachedCap) { _createAuction(i); } } } if ((lastWizardId == wizardCap) || reachedCap) { emit AuctionCapReached(wizardCap); } } /** * @notice Set the auction time buffer. * @dev Only callable by the owner. */ function setTimeBuffer(uint256 _timeBuffer) external override onlyOwner { timeBuffer = _timeBuffer; emit AuctionTimeBufferUpdated(_timeBuffer); } /** * @notice Set whether we should auction 1-1's. * @dev Only callable by the owner. */ function setAuctionOneOfOne(bool _auctionOneOfOne) external override onlyOwner { auctionOneOfOne = _auctionOneOfOne; emit AuctionOneOfOne(_auctionOneOfOne); } /** * @notice Set the auction reserve price. * @dev Only callable by the owner. */ function setReservePrice(uint256 _reservePrice) external override onlyOwner { reservePrice = _reservePrice; emit AuctionReservePriceUpdated(_reservePrice); } /** * @notice Set the max number of wizards that can be auctioned off. * @dev Only callable by the owner. */ function setWizardCap(uint256 _cap) external override onlyOwner { wizardCap = _cap; emit AuctionCapUpdated(_cap); } /** * @notice Set the auction minimum bid increment percentage. * @dev Only callable by the owner. */ function setMinBidIncrementPercentage(uint8 _minBidIncrementPercentage) external override onlyOwner { minBidIncrementPercentage = _minBidIncrementPercentage; emit AuctionMinBidIncrementPercentageUpdated( _minBidIncrementPercentage ); } /** * @notice Set oneOfOneId to mint for the next auction. * @dev Only callable by the owner. */ function setOneOfOneId(uint48 _oneOfOneId) external override onlyOwner { oneOfOneId = _oneOfOneId; } // RH: /** * @notice Set whitelist addresses for the next whitelist day * @dev Only callable by the owner. */ function setWhitelistAddresses(address[] calldata _whitelistAddrs) external override onlyOwner { for (uint256 i = 0; i < _whitelistAddrs.length; i += 1) { whitelistAddrs[i] = _whitelistAddrs[i]; } whitelistSize = _whitelistAddrs.length; } // RH: /** * @notice Remove whitelist restriction for any reason, but keep auction going * @dev Only callable by the owner. */ function stopWhitelistDay() external override onlyOwner { whitelistSize = 0; for (uint256 i = 1; i <= 5; i += 1) { auctions[i].isWhitelistDay = false; } } /** * @notice Create an auction. * @dev Store the auction details in the `auction` state variable and emit an AuctionCreated event. * If the mint reverts, the minter was updated without pausing this contract first. To remedy this, * catch the revert and pause this contract. */ function _createAuction(uint256 aId) internal { // every 5th auction is a 1-1 if 1-1 minting is enabled. if (aId % 5 == 0 && auctionOneOfOne) { try wizards.mintOneOfOne(oneOfOneId) returns ( uint256 wizardId, bool isOneOfOne ) { lastWizardId = wizardId; uint256 startTime = block.timestamp; uint256 endTime = startTime + duration; bool isWhitelistDay = whitelistSize > 0; // RH: auctions[aId] = Auction({ wizardId: wizardId, amount: 0, startTime: startTime, endTime: endTime, bidder: payable(0), settled: false, isWhitelistDay: isWhitelistDay }); // RH: emit AuctionCreated( wizardId, aId, startTime, endTime, isOneOfOne, isWhitelistDay ); } catch Error(string memory reason) { if ( keccak256(abi.encodePacked(reason)) != keccak256(abi.encodePacked("All wizards have been minted")) ) { // if we have issues minting a 1-1 we should mint a regular wiz // and disable 1-1 minting. _mintGeneratedWizard(aId); auctionOneOfOne = false; } else { reachedCap = true; _pause(); } } return; } _mintGeneratedWizard(aId); } /** * @notice Mint a generated wizard. */ function _mintGeneratedWizard(uint256 aId) internal { try wizards.mint() returns (uint256 wizardId) { lastWizardId = wizardId; uint256 startTime = block.timestamp; uint256 endTime = startTime + duration; bool isWhitelistDay = whitelistSize > 0; // RH: auctions[aId] = Auction({ wizardId: wizardId, amount: 0, startTime: startTime, endTime: endTime, bidder: payable(0), settled: false, isWhitelistDay: isWhitelistDay }); emit AuctionCreated( wizardId, aId, startTime, endTime, false, isWhitelistDay ); } catch Error(string memory reason) { if ( keccak256(abi.encodePacked(reason)) != keccak256(abi.encodePacked("All wizards have been minted")) ) { _pause(); } else { reachedCap = true; _pause(); } } } /** * @notice Settle an auction, finalizing the bid and paying out to the owner. * @dev If there are no bids, the Wizard is burned. */ function _settleAuction(uint256 aId) internal { IAuctionHouse.Auction memory _auction = auctions[aId]; require(_auction.startTime != 0, "Auction hasn't begun"); require(!_auction.settled, "Auction has already been settled"); require( block.timestamp >= _auction.endTime, "Auction hasn't completed" ); auctions[aId].settled = true; if (_auction.bidder == address(0)) { wizards.burn(_auction.wizardId); } else { wizards.transferFrom( address(this), _auction.bidder, _auction.wizardId ); } if (_auction.amount > 0) { uint256 amount = _auction.amount; uint256 creatorsShare = amount.mul(creatorFeePercent).div(100); _safeTransferETHWithFallback(creatorsDAO, creatorsShare); uint256 daoShare = amount.sub(creatorsShare); _safeTransferETHWithFallback(daoWallet, daoShare); } emit AuctionSettled( _auction.wizardId, aId, _auction.bidder, _auction.amount ); } // RH: /** * @notice set whitelistSize to 0 after whitelist day */ function _refreshWhitelist() internal { whitelistSize = 0; } /** * @notice Transfer ETH. If the ETH transfer fails, wrap the ETH and try send it as WETH. */ function _safeTransferETHWithFallback(address to, uint256 amount) internal { if (!_safeTransferETH(to, amount)) { IWETH(weth).deposit{value: amount}(); IERC20(weth).transfer(to, amount); } } /** * @notice Transfer ETH and return the success status. * @dev This function only forwards 30,000 gas to the callee. */ function _safeTransferETH(address to, uint256 value) internal returns (bool) { (bool success, ) = to.call{value: value, gas: 30_000}(new bytes(0)); return success; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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: GPL-3.0 /// @title Interface for Wizard Auction Houses pragma solidity ^0.8.6; // RH: interface IAuctionHouse { struct Auction { // ID for the Wizard (ERC721 token ID) uint256 wizardId; // The current highest bid amount uint256 amount; // The time that the auction started uint256 startTime; // The time that the auction is scheduled to end uint256 endTime; // The address of the current highest bid address payable bidder; // Whether or not the auction has been settled bool settled; // Whether or not it's a whitelist day bool isWhitelistDay; } // RH: updated event event AuctionCreated( uint256 indexed wizardId, uint256 indexed aId, uint256 startTime, uint256 endTime, bool oneOfOne, bool isWhitelistDay ); event AuctionCapUpdated(uint256 indexed cap); event AuctionCapReached(uint256 indexed cap); event AuctionBid( uint256 indexed wizardId, uint256 indexed aId, address sender, uint256 value, bool extended ); event AuctionExtended( uint256 indexed wizardId, uint256 indexed aId, uint256 endTime ); event AuctionSettled( uint256 indexed wizardId, uint256 indexed aId, address winner, uint256 amount ); event AuctionTimeBufferUpdated(uint256 timeBuffer); event AuctionOneOfOne(bool auctionOneOfOne); event AuctionReservePriceUpdated(uint256 reservePrice); event AuctionMinBidIncrementPercentageUpdated( uint256 minBidIncrementPercentage ); event CreatorsDAOUpdated(address creatorsDAO); event DAOWalletUpdated(address daoWallet); function settleAuction(uint256 aId) external; function settleCurrentAndCreateNewAuction() external; function createBid(uint256 wizardId, uint256 aid) external payable; function pause() external; function unpause() external; function setAuctionOneOfOne(bool auctionOneOfOne) external; function setCreatorsDAO(address creatorsDAO) external; function setDAOWallet(address daoWallet) external; function setWizardCap(uint256 _cap) external; function setTimeBuffer(uint256 timeBuffer) external; function setOneOfOneId(uint48 _oneOfOneId) external; function setReservePrice(uint256 reservePrice) external; // RH: function setWhitelistAddresses(address[] calldata _whitelistAddrs) external; function stopWhitelistDay() external; function setMinBidIncrementPercentage(uint8 minBidIncrementPercentage) external; } // SPDX-License-Identifier: GPL-3.0 /// @title Wizards ERC-721 token pragma solidity ^0.8.6; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {ISeeder} from "./seeder/ISeeder.sol"; import {IDescriptor} from "./descriptor/IDescriptor.sol"; interface IWizardToken is IERC721 { event SupplyUpdated(uint256 indexed supply); event WizardCreated(uint256 indexed tokenId, ISeeder.Seed seed); event WizardBurned(uint256 indexed tokenId); event CreatorsDAOUpdated(address creatorsDAO); event MinterUpdated(address minter); event MinterLocked(); event DescriptorUpdated(IDescriptor descriptor); event DescriptorLocked(); event SeederUpdated(ISeeder seeder); event SeederLocked(); function mint() external returns (uint256); function mintOneOfOne(uint48 oneOfOneId) external returns (uint256, bool); function burn(uint256 tokenId) external; function dataURI(uint256 tokenId) external returns (string memory); function setCreatorsDAO(address creatorsDAO) external; function setMinter(address minter) external; function lockMinter() external; function setDescriptor(IDescriptor descriptor) external; function lockDescriptor() external; function setSeeder(ISeeder seeder) external; function lockSeeder() external; function setSupply(uint256 supply) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.6; interface IWETH { function deposit() external payable; function withdraw(uint256 wad) external; function transfer(address to, uint256 value) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; 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 Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/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-3.0 /// @title Interface for Seeder pragma solidity ^0.8.6; import { IDescriptor } from '../descriptor/IDescriptor.sol'; // "Skin", "Cloth", "Eye", "Mouth", "Acc", "Item", "Hat" interface ISeeder { struct Seed { uint48 background; uint48 skin; uint48 clothes; uint48 eyes; uint48 mouth; uint48 accessory; uint48 bgItem; uint48 hat; bool oneOfOne; uint48 oneOfOneIndex; } function generateSeed(uint256 wizardId, IDescriptor descriptor, bool isOneOfOne, uint48 isOneOfOneIndex) external view returns (Seed memory); } // SPDX-License-Identifier: GPL-3.0 /// @title Interface for Descriptor pragma solidity ^0.8.6; import { ISeeder } from '../seeder/ISeeder.sol'; interface IDescriptor { event PartsLocked(); event DataURIToggled(bool enabled); event BaseURIUpdated(string baseURI); function arePartsLocked() external returns (bool); function isDataURIEnabled() external returns (bool); function baseURI() external returns (string memory); function palettes(uint8 paletteIndex, uint256 colorIndex) external view returns (string memory); function addManyColorsToPalette(uint8 paletteIndex, string[] calldata newColors) external; function addColorToPalette(uint8 paletteIndex, string calldata color) external; function backgrounds(uint256 index) external view returns (string memory); function backgroundCount() external view returns (uint256); function addManyBackgrounds(string[] calldata backgrounds) external; function addBackground(string calldata background) external; function oneOfOnes(uint256 index) external view returns (bytes memory); function oneOfOnesCount() external view returns (uint256); function addOneOfOne(bytes calldata _oneOfOne) external; function addManyOneOfOnes(bytes[] calldata _oneOfOnes) external; function skins(uint256 index) external view returns (bytes memory); function skinsCount() external view returns (uint256); function addManySkins(bytes[] calldata skins) external; function addSkin(bytes calldata skin) external; function hats(uint256 index) external view returns (bytes memory); function hatsCount() external view returns (uint256); function addManyHats(bytes[] calldata hats) external; function addHat(bytes calldata hat) external; function clothes(uint256 index) external view returns (bytes memory); function clothesCount() external view returns (uint256); function addManyClothes(bytes[] calldata ears) external; function addClothes(bytes calldata ear) external; function mouths(uint256 index) external view returns (bytes memory); function mouthsCount() external view returns (uint256); function addManyMouths(bytes[] calldata mouths) external; function addMouth(bytes calldata mouth) external; function eyes(uint256 index) external view returns (bytes memory); function eyesCount() external view returns (uint256); function addManyEyes(bytes[] calldata eyes) external; function addEyes(bytes calldata eye) external; function accessory(uint256 index) external view returns (bytes memory); function accessoryCount() external view returns (uint256); function addManyAccessories(bytes[] calldata noses) external; function addAccessory(bytes calldata nose) external; function bgItems(uint256 index) external view returns (bytes memory); function bgItemsCount() external view returns (uint256); function addManyBgItems(bytes[] calldata noses) external; function addBgItem(bytes calldata nose) external; function lockParts() external; function toggleDataURIEnabled() external; function setBaseURI(string calldata baseURI) external; function tokenURI(uint256 tokenId, ISeeder.Seed memory seed) external view returns (string memory); function dataURI(uint256 tokenId, ISeeder.Seed memory seed) external view returns (string memory); function genericDataURI( string calldata name, string calldata description, ISeeder.Seed memory seed ) external view returns (string memory); function generateSVGImage(ISeeder.Seed memory seed) external view returns (string memory); } // 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); }
Create a bid for a Wizard with a given amount. This contract only accepts payment in ETH./ RH: ensure bidder is in whitelist refund the last bidder, if applicable
function createBid(uint256 wizardId, uint256 aId) external payable override nonReentrant { IAuctionHouse.Auction memory _auction = auctions[aId]; require( (aId <= auctionCount) && (aId >= 1), "Auction Id is not currently open" ); require(_auction.wizardId == wizardId, "Wizard not up for auction"); require(block.timestamp < _auction.endTime, "Auction expired"); require(msg.value >= reservePrice, "Must send at least reservePrice"); require( msg.value >= _auction.amount + ((_auction.amount * minBidIncrementPercentage) / 100), "Must send more than last bid by minBidIncrementPercentage amount" ); if (_auction.isWhitelistDay) { bool bidderInWhitelist; for (uint256 i = 0; i < whitelistSize; i += 1) { if (whitelistAddrs[i] == msg.sender) { bidderInWhitelist = true; break; } } require(bidderInWhitelist, "Bidder is not on whitelist"); } address payable lastBidder = _auction.bidder; if (lastBidder != address(0)) { _safeTransferETHWithFallback(lastBidder, _auction.amount); } auctions[aId].amount = msg.value; auctions[aId].bidder = payable(msg.sender); if (extended) { auctions[aId].endTime = _auction.endTime = block.timestamp + timeBuffer; } emit AuctionBid( _auction.wizardId, aId, msg.sender, msg.value, extended ); if (extended) { emit AuctionExtended(_auction.wizardId, aId, _auction.endTime); } }
12,140,682
pragma solidity ^0.4.24; import "../math/SafeMath.sol"; import "./Crowdsale.sol"; /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract PreSaleCrowdsale is Crowdsale { using SafeMath for uint256; /** * The structure to hold private round condition for token distribution and * refund. * @see addUpdateDeal for details. */ struct PreSaleConditions { address wallet; address bonusWallet; uint256 weiMinAmount; uint256 bonusShare; uint256 bonusRate; uint256 bonusRateTime; bool completed; } event InvestorAdded(address indexed _wallet); event InvestorUpdated(address indexed _wallet); event InvestorDeleted(address indexed _wallet); event InvoiceAdded(address indexed _wallet, uint256 _tokenAmount, string _invoiceId); event InvoiceUpdated(address indexed _wallet, uint256 _tokenAmount, string _invoiceId); event InvoiceDeleted(address indexed _wallet); event KYCUpdated(address indexed _grantee, bool _oldValue, bool _value); event DeletePreSaleDealInvestorsMapKeysFound(uint256 index); event DeleteInvoiceInvoiceMapKeysSkipped(); event DeletePreSaleDealInvestorsMapKeySkipped(); modifier onlyKYCPassed() { require(kykPassed[msg.sender]); _; } /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. */ modifier onlyWhitelisted() { require(investorsMap[msg.sender].wallet != address(0)); _; } //Investors - used for ether presale and bonus token generation address[] public investorsMapKeys; mapping(address => PreSaleConditions) public investorsMap; //Invoice -used for non-ether presale token generation address[] public invoiceMapKeys; mapping(address => uint256) public invoicesMap; mapping(address => bool) public kykPassed; /** * @dev Update KYC flag for deal. * * NOTE: According to EU/US laws we can`t handle and use any fees from investors * without passed KYC (Know Your Customer) procedure to ensure verification processes * in order to reduce fraud, money laundering and scams. In order to do this, it is * important to authenticate money trail from start to end. That’s when KYC comes * into practice. * * @param _wallet address The address of the investor wallet for ETC payments. * @param _value flag determining is investor passed KYC procedure for bank complience. */ function updateInvestorKYC(address _wallet, bool _value) external onlyAdmins { require(_wallet != address(0)); require(kykPassed[_wallet] != _value); bool _oldValue = kykPassed[_wallet]; kykPassed[_wallet] = _value; emit KYCUpdated(_wallet, _oldValue, _value); } /** * @dev Adds/Updates address and token deal allocation for token investors. * All tokens during pre-sale are allocated to pre-sale, buyers. * * @param _incomeWallet address The address of the investor wallet for ETC payments. * @param _wallet address The address of the investor wallet for ONE tokens. * @param _bonusWallet address The address of the finder for ONE tokens. * @param _weiMinAmount minimum amount of ETH for payment. * @param _bonusRate ONE to ETH rate for investor * @param _bonusRateTime timestamp when token rate should be used * @param _bonusShare amount of bonus ONE tokens distributed between _investorWallet and _bonusWallet */ function addUpdatePreSaleDeal( address _incomeWallet, address _wallet, address _bonusWallet, uint256 _weiMinAmount, uint256 _bonusRate, uint256 _bonusRateTime, uint256 _bonusShare ) external onlyAdmins onlyWhileOpen { require(_incomeWallet != address(0)); require(_wallet != address(0)); require(_weiMinAmount > 0); if (_bonusRate > 0) { require(_bonusRateTime > now); } if (_bonusShare > 0) { require(_bonusShare <= 100); require(_bonusWallet != address(0)); } PreSaleConditions storage investor = investorsMap[_incomeWallet]; // Adding new key if not present: if (investor.wallet == address(0)) { investorsMapKeys.push(_incomeWallet); emit InvestorAdded(_incomeWallet); } else { emit InvestorUpdated(_incomeWallet); } investor.wallet = _wallet; investor.weiMinAmount = _weiMinAmount; investor.bonusWallet = _bonusWallet; investor.bonusRate = _bonusRate; investor.bonusRateTime = _bonusRateTime; investor.bonusShare = _bonusShare; investor.completed = false; } /** * @dev Deletes entries from the deal list. * * @param _incomeWallet address The address of the investor wallet for ETC payments. */ function deletePreSaleDeal(address _incomeWallet) external onlyAdmins onlyWhileOpen { require(investorsMap[_incomeWallet].wallet != address(0)); //delete from the map: delete investorsMap[_incomeWallet]; //delete from the array (keys): uint256 index; bool isIndexFound = false; for (uint256 i = 0; i < investorsMapKeys.length; i++) { if (investorsMapKeys[i] == _incomeWallet) { index = i; isIndexFound = true; emit DeletePreSaleDealInvestorsMapKeysFound(index); break; } else { emit DeletePreSaleDealInvestorsMapKeySkipped(); } } if (true == isIndexFound) { investorsMapKeys[index] = investorsMapKeys[investorsMapKeys.length - 1]; delete investorsMapKeys[investorsMapKeys.length - 1]; investorsMapKeys.length--; } emit InvestorDeleted(_incomeWallet); } /** * @dev Adds/Updates address and token allocation for token investors with * BTC/fiat based payments. * * @param _wallet address The address of the investor wallet for ONE tokens. * @param _tokens ONE token amount based on invoice income. * @param _invoiceId fiat payment invoice id or BTC transaction id. */ function addUpdateInvoice( address _wallet, uint256 _tokens, string _invoiceId ) external onlyAdmins onlyWhileOpen { require(_wallet != address(0)); require(_tokens > 0); uint256 amount = invoicesMap[_wallet]; // Adding new key if not present: if (amount == 0) { invoiceMapKeys.push(_wallet); emit InvoiceAdded(_wallet, _tokens, _invoiceId); } else { emit InvoiceUpdated(_wallet, _tokens, _invoiceId); } invoicesMap[_wallet] = _tokens; } /** * @dev Deletes entries from the invoice list. * * @param _wallet address The address of the investor wallet for ONE tokens. */ function deleteInvoice(address _wallet) external onlyAdmins onlyWhileOpen { require(_wallet != address(0)); require(invoicesMap[_wallet] > 0); //delete from the map: delete invoicesMap[_wallet]; //delete from the array (keys): uint256 index; for (uint256 i = 0; i < invoiceMapKeys.length; i++) { if (invoiceMapKeys[i] == _wallet) { index = i; break; } else { emit DeleteInvoiceInvoiceMapKeysSkipped(); } } invoiceMapKeys[index] = invoiceMapKeys[invoiceMapKeys.length - 1]; delete invoiceMapKeys[invoiceMapKeys.length - 1]; invoiceMapKeys.length--; emit InvoiceDeleted(_wallet); } }
Adds/Updates address and token allocation for token investors with BTC/fiat based payments. _wallet address The address of the investor wallet for ONE tokens. _tokens ONE token amount based on invoice income. _invoiceId fiat payment invoice id or BTC transaction id./ Adding new key if not present:
function addUpdateInvoice( address _wallet, uint256 _tokens, string _invoiceId ) external onlyAdmins onlyWhileOpen { require(_wallet != address(0)); require(_tokens > 0); uint256 amount = invoicesMap[_wallet]; if (amount == 0) { invoiceMapKeys.push(_wallet); emit InvoiceAdded(_wallet, _tokens, _invoiceId); } else { emit InvoiceUpdated(_wallet, _tokens, _invoiceId); } invoicesMap[_wallet] = _tokens; }
12,984,027
pragma solidity ^0.5.0; // Import the `Roles` library import "../milkcore/Ownable.sol"; import "../milkaccesscontrol/PoultererRole.sol"; import "../milkaccesscontrol/DairyfactoryRole.sol"; import "../milkaccesscontrol/DistributorRole.sol"; import "../milkaccesscontrol/RetailerRole.sol"; import "../milkaccesscontrol/SupermarketRole.sol"; import "../milkaccesscontrol/ConsumerRole.sol"; // Define a contract 'Supplychain' contract SupplyChain is Ownable, PoultererRole, DairyfactoryRole, DistributorRole, RetailerRole, SupermarketRole, ConsumerRole { // Define 'owner' //address owner; // Define a variable called 'upc' for Universal Product Code (UPC) uint upc; // Define a variable called 'sku' for Stock Keeping Unit (SKU) uint sku; // Define a public mapping 'items' that maps the UPC to an Item. mapping (uint => Item) items; // Define a public mapping 'itemsHistory' that maps the UPC to an array of TxHash, // that track its journey through the supply chain -- to be sent from DApp. mapping (uint => string[]) itemsHistory; // Define enum 'State' with the following values: enum State { Obtained, // 0 Stored, // 1 ForSaleToDairyfactory, // 2 SoldToDairyfactory, // 3 ShippedToDairyfactory, // 4 ReceivedByDairyfactory, // 5 Tested, // 6 Qualified, // 7 Failed, // 8 Processed, // 9 Returned, // 10 Retaken, // 11 ShippedToPoulterer, // 12 ReceivedByPoulterer, // 13 Destroyed, // 14 Packed, // 15 ForSaleToDistributor, // 16 SoldToDistributor, // 17 ShippedToDistributor, // 18 ReceivedByDistributor, // 19 ForSaleToRetailer, // 20 SoldToRetailer, // 21 ShippedToRetailer, // 22 ReceivedByRetailer, // 23 ForSaleToSupermarket, // 24 SoldToSupermarket, // 25 ShippedToSupermarket, // 26 ReceivedBySupermarket, // 27 ForSaleToConsumer, // 28 SoldToConsumer, // 29 PurchasedByConsumer // 30 } State constant defaultState = State.Obtained; // Define a struct 'Item' with the following fields: struct Item { uint sku; // Stock Keeping Unit (SKU) uint upc; // Universal Product Code (UPC), generated by the Poulterer, goes on the package, can be verified by the Consumer bool existItem; // Boolean to check the existence of the item easily address payable ownerID; // Metamask-Ethereum address of the current owner as the product moves through 31 stages address payable originPoultererID; // Metamask-Ethereum address of the Poulterer string originFarmName; // Poulterer Name string originFarmInformation; // Poulterer Information string originFarmLatitude; // Farm Latitude string originFarmLongitude; // Farm Longitude uint productID; // Product ID potentially a combination of upc + sku string productNotes; // Product Notes uint productPrice; // Product Price bool isQualified; // The quality status of the milk. State itemState; // Product State as represented in the enum above address payable dairyfactoryID; // Metamask-Ethereum address of the Dairyfactory address payable distributorID; // Metamask-Ethereum address of the Distributor address payable retailerID; // Metamask-Ethereum address of the Retailer address payable supermarketID; // Metamask-Ethereum address of the Supermarket address payable consumerID; // Metamask-Ethereum address of the Consumer } // Define 15 events with the same 15 state values and accept 'upc' as input argument event Obtained(uint upc, address emiter); event Stored(uint upc, address emiter); event ForSaleToDairyfactory(uint upc, address emiter, uint price); event SoldToDairyfactory(uint upc, address emiter); event ShippedToDairyfactory(uint upc, address emiter); event ReceivedByDairyfactory(uint upc, address emiter); event Tested(uint upc, address emiter, bool testResult); event Processed(uint upc, address emiter); event Returned(uint upc, address emiter); event Retaken(uint upc, address emiter); event ShippedToPoulterer(uint upc, address emiter); event ReceivedByPoulterer(uint upc, address emiter); event Destroyed(uint upc, address emiter); event Packed(uint upc, address emiter); event ForSaleToDistributor(uint upc, address emiter, uint price); event SoldToDistributor(uint upc, address emiter); event ShippedToDistributor(uint upc, address emiter); event ReceivedByDistributor(uint upc, address emiter); event ForSaleToRetailer(uint upc, address emiter, uint price); event SoldToRetailer(uint upc, address emiter); event ShippedToRetailer(uint upc, address emiter); event ReceivedByRetailer(uint upc, address emiter); event ForSaleToSupermarket(uint upc, address emiter, uint price); event SoldToSupermarket(uint upc, address emiter); event ShippedToSupermarket(uint upc, address emiter); event ReceivedBySupermarket(uint upc, address emiter); event ForSaleToConsumer(uint upc, address emiter, uint price); event SoldToConsumer(uint upc, address emiter); event PurchasedByConsumer(uint upc, address emiter); // Define a modifer that verifies the Caller modifier verifyCaller (address _address) { require(msg.sender == _address); _; } // Define a modifier that checks if the paid amount is sufficient to cover the price modifier paidEnough(uint _price) { require(msg.value >= _price); _; } // Define a modifier that checks the price and refunds the remaining balance modifier checkValue(uint _upc) { _; uint _price = items[_upc].productPrice; uint amountToReturn = msg.value - _price; msg.sender.transfer(amountToReturn); } // Define a modifier that checks if an item.state of a upc is Sold modifier checkItemState (uint _upc, State _state, string memory _errorMessage){ require(items[_upc].itemState == _state, _errorMessage); _; } // Define a modifier that checks if a _upc is already in the items mapping modifier checkUpcInItems(uint _upc) { require(items[_upc].existItem, "This UPC does not exist in items mapping."); _; } // In the constructor set 'owner' to the address that instantiated the contract // and set 'sku' to 1 // and set 'upc' to 1 constructor() public payable { sku = 1; upc = 1; } // Define a function 'kill' if required function kill() public { selfdestruct(this.owner()); } // Define a function 'obtainItem' that allows a poulterer to mark an item 'Obtained' function obtainItem( uint _upc, address payable _originPoultererID, string memory _originFarmName, string memory _originFarmInformation, string memory _originFarmLatitude, string memory _originFarmLongitude, string memory _productNotes) public onlyPoulterer() { // Add the new item as part of Obtain Item memory newItem = Item( sku, // Stock Keeping Unit (SKU) _upc, // Universal Product Code (UPC) true, // Boolean to check the existence of the item easily _originPoultererID, // Metamask-Ethereum address of the current owner _originPoultererID, // Metamask-Ethereum address of the Poulterer _originFarmName, // Poulterer Name _originFarmInformation, // Poulterer Information _originFarmLatitude, // Farm Latitude _originFarmLongitude, // Farm Longitude _upc + sku, // Product ID _productNotes, // Product Note 0, // Product Price false, // The quality status of milk. State.Obtained, // Product State address(0), // Metamask-Ethereum address of the Dairyfactory address(0), // Metamask-Ethereum address of the Distributor address(0), // Metamask-Ethereum address of the Retailer address(0), // Metamask-Ethereum address of the Supermarket address(0) // Metamask-Ethereum address of the Consumer ); items[_upc] = newItem; // Increment sku sku = sku + 1; // Emit the appropriate event emit Obtained(_upc, msg.sender); } // Define a function 'StoreItem' that allows a poulterer to mark an item 'Stored' function storeItem(uint _upc) public onlyPoulterer() checkUpcInItems (_upc) checkItemState (_upc, State.Obtained, "Milk is not obtained!") verifyCaller(items[_upc].ownerID) // Check the caller is the owner of the item { // Update the appropriate fields items[_upc].itemState = State.Stored; // Emit the appropriate event emit Stored(_upc, msg.sender); } // Define a function 'sellToDairyfactory' that allows a poulterer to mark an item 'ForSaleToDairyfactory' function sellToDairyfactory(uint _upc, uint _price) public onlyPoulterer() checkUpcInItems (_upc) verifyCaller(items[_upc].ownerID) // Check if caller is the owner of the item checkItemState (_upc, State.Stored, "Milk is not stored!") { // Update the appropriate fields items[_upc].itemState = State.ForSaleToDairyfactory; items[_upc].productPrice = _price; // Emit the appropriate event emit ForSaleToDairyfactory(_upc, msg.sender, _price); } // Define a function 'buyItemByDairyfactory' that allows the dairyfactory to mark an item 'SoldToDairyfactory' // Use the above defined modifiers to check if the item is available for sale, if the buyer has paid enough, // and any excess ether sent is refunded back to the buyer function buyItemByDairyfactory(uint _upc) public payable onlyDairyfactory() checkUpcInItems (_upc) checkItemState (_upc, State.ForSaleToDairyfactory, "Milk is not for sale to dairyfactory!") paidEnough(items[_upc].productPrice) // Check if buyer has paid enough checkValue(_upc) // Send any excess Ether back to buyer { // Update the appropriate fields - ownerID, dairyfactoryID, itemState items[_upc].ownerID = msg.sender; items[_upc].dairyfactoryID = msg.sender; items[_upc].itemState = State.SoldToDairyfactory; // Transfer money to poulterer items[_upc].originPoultererID.transfer(items[_upc].productPrice); // emit the appropriate event emit SoldToDairyfactory(_upc, msg.sender); } // Define a function 'shipItemToDairyfactory' that allows the poulterer to mark an item 'ShippedToDairyfactory' // Use the above modifers to check if the item is sold function shipItemToDairyfactory(uint _upc) public onlyPoulterer() checkUpcInItems (_upc) verifyCaller(items[_upc].originPoultererID) // Check if caller is the poulterer of the item checkItemState (_upc, State.SoldToDairyfactory, "Milk is not sold to dairyfactory!") { // Update the appropriate fields items[_upc].itemState = State.ShippedToDairyfactory; // Emit the appropriate event emit ShippedToDairyfactory(_upc, msg.sender); } // Define a function 'receiveItemByDairyfactory' that allows the dairyfactory to mark an item 'ReceivedByDairyfactory' // Use the above modifiers to check if the item is shipped function receiveItemByDairyfactory(uint _upc) public onlyDairyfactory() checkUpcInItems (_upc) verifyCaller(items[_upc].ownerID) // Check if caller is the owner of the item checkItemState (_upc, State.ShippedToDairyfactory, "Milk is not shipped to dairyfactory!") { // Update the appropriate fields - ownerID, retailerID, itemState items[_upc].itemState = State.ReceivedByDairyfactory; // Emit the appropriate event emit ReceivedByDairyfactory(_upc, msg.sender); } // Define a function 'testMilk' that allows the dairyfactory to mark an item 'Qualified or Failed' // Use the above modifiers to check if the item is received function testMilk(uint _upc, bool _testResult) public onlyDairyfactory() checkUpcInItems (_upc) verifyCaller(items[_upc].ownerID) // Check if caller is the owner of the item checkItemState (_upc, State.ReceivedByDairyfactory, "Milk is not received by dairyfactory!") { if (_testResult) { // Update the appropriate fields - ownerID, retailerID, itemState items[_upc].itemState = State.Qualified; // Emit the appropriate event //emit Qualified(_upc, msg.sender); } else { // Update the appropriate fields - ownerID, retailerID, itemState items[_upc].itemState = State.Failed; // Emit the appropriate event //emit Failed(_upc, msg.sender); } } // Define a function 'processMilk' that allows the dairyfactory to mark an item 'Processed' // Use the above modifiers to check if the item is qualified function processMilk(uint _upc) public onlyDairyfactory() checkUpcInItems (_upc) verifyCaller(items[_upc].ownerID) // Check if caller is the owner of the item checkItemState (_upc, State.ReceivedByDairyfactory, "Milk is not qualified the quality test!") { // Update the appropriate fields - ownerID, retailerID, itemState items[_upc].itemState = State.Processed; // Emit the appropriate event emit Processed(_upc, msg.sender); } // Define a function 'returnMilk' that allows the dairyfactory to mark an item 'Returned' // Use the above modifiers to check if the item is qualified function returnMilk(uint _upc) public onlyDairyfactory() checkUpcInItems (_upc) verifyCaller(items[_upc].ownerID) // Check if caller is the owner of the item checkItemState (_upc, State.Failed, "Milk is not failed the quality test!") { // Update the appropriate fields - ownerID, retailerID, itemState items[_upc].itemState = State.Returned; // Emit the appropriate event emit Returned(_upc, msg.sender); } // Define a function 'retakeMilk' that allows the poulterer to mark an item 'Retaken' function retakeMilk(uint _upc) public onlyPoulterer() checkUpcInItems (_upc) verifyCaller(items[_upc].originPoultererID) // Check if caller is the poulterer of the item checkItemState (_upc, State.Returned, "Milk is not returned to poulterer!") { // Update the appropriate fields - ownerID, dairyfactoryID, itemState items[_upc].itemState = State.Retaken; // emit the appropriate event emit Retaken(_upc, msg.sender); } // Define a function 'shipItemToPoulterer' that allows the dairy factory to mark an item 'ShippedToPoulterer' // Use the above modifers to check if the item is retaken function shipItemToPoulterer(uint _upc) public onlyDairyfactory() checkUpcInItems (_upc) verifyCaller(items[_upc].originPoultererID) // Check if caller is the poulterer of the item checkItemState (_upc, State.Retaken, "Milk is not retaken by dairy factory!") { // Update the appropriate fields items[_upc].itemState = State.ShippedToPoulterer; // Emit the appropriate event emit ShippedToPoulterer(_upc, msg.sender); } // Define a function 'receiveItemByPoulterer' that allows the dairyfactory to mark an item 'ReceivedByPoulterer' // Use the above modifiers to check if the item is ShippedToPoulterer function receiveItemByPoulterer(uint _upc) public onlyPoulterer() checkUpcInItems (_upc) verifyCaller(items[_upc].ownerID) // Check if caller is the owner of the item checkItemState (_upc, State.ShippedToPoulterer, "Milk is not shipped to poulterer!") { // Update the appropriate fields - ownerID, retailerID, itemState items[_upc].itemState = State.ReceivedByPoulterer; // Emit the appropriate event emit ReceivedByPoulterer(_upc, msg.sender); } // Define a function 'destroyMilk' that allows the poulterer to mark an item 'Destroyed' // Use the above modifiers to check if the item is ReceivedByPoulterer function destroyMilk(uint _upc) public onlyPoulterer() checkUpcInItems (_upc) verifyCaller(items[_upc].ownerID) // Check if caller is the owner of the item checkItemState (_upc, State.ReceivedByPoulterer, "Milk is not received by poulterer!") { // Update the appropriate fields - ownerID, retailerID, itemState items[_upc].itemState = State.Destroyed; // Emit the appropriate event emit Destroyed(_upc, msg.sender); } // Define a function 'packMilk' that allows the dairy factory to mark an item 'Packed' // Use the above modifiers to check if the item is processed function packMilk(uint _upc) public onlyDairyfactory() checkUpcInItems (_upc) verifyCaller(items[_upc].ownerID) // Check if caller is the owner of the item checkItemState (_upc, State.Processed, "Milk is not processed!") { // Update the appropriate fields - ownerID, retailerID, itemState items[_upc].itemState = State.Packed; // Emit the appropriate event emit Packed(_upc, msg.sender); } // Define a function 'sellToDistributor' that allows a dairy factory to mark an item 'ForSaleToDistributor' function sellToDistributor(uint _upc, uint _price) public onlyDairyfactory() checkUpcInItems (_upc) verifyCaller(items[_upc].ownerID) // Check if caller is the owner of the item checkItemState (_upc, State.Packed, "Milk is not packed!") { // Update the appropriate fields items[_upc].itemState = State.ForSaleToDistributor; items[_upc].productPrice = _price; // Emit the appropriate event emit ForSaleToDistributor(_upc, msg.sender, _price); } // Define a function 'buyItemByDistributor' that allows the distributor to mark an item 'SoldToDistributor' // Use the above defined modifiers to check if the item is available for sale, if the buyer has paid enough, // and any excess ether sent is refunded back to the buyer function buyItemByDistributor(uint _upc) public payable onlyDistributor() checkUpcInItems (_upc) checkItemState (_upc, State.ForSaleToDistributor, "Milk is not for sale to distributor!") paidEnough(items[_upc].productPrice) // Check if buyer has paid enough checkValue(_upc) // Send any excess Ether back to buyer { // Update the appropriate fields - ownerID, dairyfactoryID, itemState items[_upc].ownerID = msg.sender; items[_upc].distributorID = msg.sender; items[_upc].itemState = State.SoldToDistributor; // Transfer money to poulterer items[_upc].dairyfactoryID.transfer(items[_upc].productPrice); // emit the appropriate event emit SoldToDistributor(_upc, msg.sender); } // Define a function 'shipItemToDistributor' that allows the dairy factory to mark an item 'ShippedToDistributor' // Use the above modifers to check if the item is sold function shipItemToDistributor(uint _upc) public onlyDairyfactory() checkUpcInItems (_upc) verifyCaller(items[_upc].dairyfactoryID) // Check if caller is the owner of the item checkItemState (_upc, State.SoldToDistributor, "Milk is not sold to distributor!") { // Update the appropriate fields items[_upc].itemState = State.ShippedToDistributor; // Emit the appropriate event emit ShippedToDistributor(_upc, msg.sender); } // Define a function 'receiveItemByDistributor' that allows the distributor to mark an item 'ReceivedByDistributor' // Use the above modifiers to check if the item is shipped function receiveItemByDistributor(uint _upc) public onlyDistributor() checkUpcInItems (_upc) verifyCaller(items[_upc].distributorID) // Check if caller is the owner of the item checkItemState (_upc, State.ShippedToDistributor, "Milk is not shipped to distributor!") { // Update the appropriate fields - ownerID, retailerID, itemState items[_upc].itemState = State.ReceivedByDistributor; // Emit the appropriate event emit ReceivedByDistributor(_upc, msg.sender); } // Define a function 'sellToRetailer' that allows a dairy factory to mark an item 'ForSaleToRetailer' function sellToRetailer(uint _upc, uint _price) public onlyDistributor() checkUpcInItems (_upc) verifyCaller(items[_upc].distributorID) // Check if caller is the owner of the item checkItemState (_upc, State.ReceivedByDistributor, "Milk is not received by distributor!") { // Update the appropriate fields items[_upc].itemState = State.ForSaleToRetailer; items[_upc].productPrice = _price; // Emit the appropriate event emit ForSaleToRetailer(_upc, msg.sender, _price); } // Define a function 'buyItemByRetailer' that allows the retailer to mark an item 'SoldToRetailer' // Use the above defined modifiers to check if the item is available for sale, if the buyer has paid enough, // and any excess ether sent is refunded back to the buyer function buyItemByRetailer(uint _upc) public payable onlyRetailer() checkUpcInItems (_upc) checkItemState (_upc, State.ForSaleToRetailer, "Milk is not for sale to retailer!") paidEnough(items[_upc].productPrice) // Check if buyer has paid enough checkValue(_upc) // Send any excess Ether back to buyer { // Update the appropriate fields - ownerID, dairyfactoryID, itemState items[_upc].ownerID = msg.sender; items[_upc].retailerID = msg.sender; items[_upc].itemState = State.SoldToRetailer; // Transfer money to poulterer items[_upc].distributorID.transfer(items[_upc].productPrice); // emit the appropriate event emit SoldToRetailer(_upc, msg.sender); } // Define a function 'shipItemToRetailer' that allows the distributor to mark an item 'ShippedToRetailer' // Use the above modifers to check if the item is sold function shipItemToRetailer(uint _upc) public onlyDistributor() checkUpcInItems (_upc) verifyCaller(items[_upc].distributorID) // Check if caller is the owner of the item checkItemState (_upc, State.SoldToRetailer, "Milk is not sold to retailer!") { // Update the appropriate fields items[_upc].itemState = State.ShippedToRetailer; // Emit the appropriate event emit ShippedToRetailer(_upc, msg.sender); } // Define a function 'receiveItemByRetailer' that allows the retailer to mark an item 'ReceivedByRetailer' // Use the above modifiers to check if the item is shipped function receiveItemByRetailer(uint _upc) public onlyRetailer() checkUpcInItems (_upc) verifyCaller(items[_upc].retailerID) // Check if caller is the owner of the item checkItemState (_upc, State.ShippedToRetailer, "Milk is not shipped to retailer!") { // Update the appropriate fields - ownerID, retailerID, itemState items[_upc].itemState = State.ReceivedByRetailer; // Emit the appropriate event emit ReceivedByRetailer(_upc, msg.sender); } // Define a function 'sellToSuperMarket' that allows a retailer to mark an item 'ForSaleToSupermarket' function sellToSuperMarket(uint _upc, uint _price) public onlyRetailer() checkUpcInItems (_upc) verifyCaller(items[_upc].retailerID) // Check if caller is the owner of the item checkItemState (_upc, State.ReceivedByRetailer, "Milk is not received by retailer!") { // Update the appropriate fields items[_upc].itemState = State.ForSaleToSupermarket; items[_upc].productPrice = _price; // Emit the appropriate event emit ForSaleToSupermarket(_upc, msg.sender, _price); } // Define a function 'buyItemBySupermarket' that allows the supermarket to mark an item 'SoldToSupermarket' // Use the above defined modifiers to check if the item is available for sale, if the buyer has paid enough, // and any excess ether sent is refunded back to the buyer function buyItemBySupermarket(uint _upc) public payable onlySupermarket() checkUpcInItems (_upc) checkItemState (_upc, State.ForSaleToSupermarket, "Milk is not for sale to supermarket!") paidEnough(items[_upc].productPrice) // Check if buyer has paid enough checkValue(_upc) // Send any excess Ether back to buyer { // Update the appropriate fields - ownerID, dairyfactoryID, itemState items[_upc].ownerID = msg.sender; items[_upc].supermarketID = msg.sender; items[_upc].itemState = State.SoldToSupermarket; // Transfer money to poulterer items[_upc].retailerID.transfer(items[_upc].productPrice); // emit the appropriate event emit SoldToSupermarket(_upc, msg.sender); } // Define a function 'shipItemToSupermarket' that allows the retailer to mark an item 'ShippedToSupermarket' // Use the above modifers to check if the item is sold function shipItemToSupermarket(uint _upc) public onlyRetailer() checkUpcInItems (_upc) verifyCaller(items[_upc].retailerID) // Check if caller is the owner of the item checkItemState (_upc, State.SoldToSupermarket, "Milk is not sold to supermarket!") { // Update the appropriate fields items[_upc].itemState = State.ShippedToSupermarket; // Emit the appropriate event emit ShippedToSupermarket(_upc, msg.sender); } // Define a function 'receiveItemBySupermarket' that allows the retailer to mark an item 'ReceivedBySupermarket' // Use the above modifiers to check if the item is shipped function receiveItemBySupermarket(uint _upc) public onlySupermarket() checkUpcInItems (_upc) verifyCaller(items[_upc].supermarketID) // Check if caller is the owner of the item checkItemState (_upc, State.ShippedToSupermarket, "Milk is not shipped to supermarket!") { // Update the appropriate fields - ownerID, retailerID, itemState items[_upc].itemState = State.ReceivedBySupermarket; // Emit the appropriate event emit ReceivedBySupermarket(_upc, msg.sender); } // Define a function 'sellToConsumer' that allows a supermarket to mark an item 'ForSaleToConsumer' function sellToConsumer(uint _upc, uint _price) public onlySupermarket() checkUpcInItems (_upc) verifyCaller(items[_upc].supermarketID) // Check if caller is the owner of the item checkItemState (_upc, State.ReceivedBySupermarket, "Milk is not received by supermarket!") { // Update the appropriate fields items[_upc].itemState = State.ForSaleToConsumer; items[_upc].productPrice = _price; // Emit the appropriate event emit ForSaleToConsumer(_upc, msg.sender, _price); } // Define a function 'buyItemByConsumer' that allows the supermarket to mark an item 'SoldToConsumer' // Use the above defined modifiers to check if the item is available for sale, if the buyer has paid enough, // and any excess ether sent is refunded back to the buyer function buyItemByConsumer(uint _upc) public payable onlyConsumer() checkUpcInItems (_upc) checkItemState (_upc, State.ForSaleToConsumer, "Milk is not for sale to consumer!") paidEnough(items[_upc].productPrice) // Check if buyer has paid enough checkValue(_upc) // Send any excess Ether back to buyer { // Update the appropriate fields - ownerID, dairyfactoryID, itemState items[_upc].ownerID = msg.sender; items[_upc].consumerID = msg.sender; items[_upc].itemState = State.SoldToConsumer; // Transfer money to poulterer items[_upc].supermarketID.transfer(items[_upc].productPrice); // emit the appropriate event emit SoldToConsumer(_upc, msg.sender); } // Define a function 'purchaseItemByConsumer' that allows the consumer to mark an item 'PurchasedByConsumer' // Use the above modifiers to check if the item is received function purchaseItemByConsumer(uint _upc) public onlyConsumer() checkUpcInItems (_upc) verifyCaller(items[_upc].consumerID) // Check if caller is the owner of the item checkItemState (_upc, State.SoldToConsumer, "Milk is not sold to consumer!") { // Update the appropriate fields - ownerID, retailerID, itemState items[_upc].itemState = State.PurchasedByConsumer; // Emit the appropriate event emit PurchasedByConsumer(_upc, msg.sender); } // Define a function 'fetchItemBufferPublic' that fetches the public data function fetchItemBufferPublic(uint _upc) public checkUpcInItems(_upc) view returns ( uint itemSKU, uint itemUPC, address ownerID, address originPoultererID, string memory originFarmName, string memory originFarmInformation, string memory originFarmLatitude, string memory originFarmLongitude, State itemState, uint productPrice, address distributorID ) { // Assign values to the parameters Item memory foundedItem = items[_upc]; itemSKU = foundedItem.sku; itemUPC = foundedItem.upc; ownerID = foundedItem.ownerID; originPoultererID = foundedItem.originPoultererID; originFarmName = foundedItem.originFarmName; originFarmInformation = foundedItem.originFarmInformation; originFarmLatitude = foundedItem.originFarmLatitude; originFarmLongitude = foundedItem.originFarmLongitude; itemState = foundedItem.itemState; productPrice = foundedItem.productPrice; distributorID = foundedItem.distributorID; return ( itemSKU, itemUPC, ownerID, originPoultererID, originFarmName, originFarmInformation, originFarmLatitude, originFarmLongitude, itemState, productPrice, distributorID ); } // Define a function 'fetchItemBufferForDistributor' that fetches the data only for distributor function fetchItemBufferDistributor(uint _upc) public checkUpcInItems(_upc) view returns ( uint itemSKU, uint itemUPC, address ownerID, address distributorID, string memory originFarmName, string memory originFarmInformation, string memory originFarmLatitude, string memory originFarmLongitude, string memory productNotes, State itemState ) { // Assign values to the parameters Item memory foundedItem = items[_upc]; itemSKU = foundedItem.sku; itemUPC = foundedItem.upc; ownerID = foundedItem.ownerID; distributorID = foundedItem.distributorID; originFarmName = foundedItem.originFarmName; originFarmInformation = foundedItem.originFarmInformation; originFarmLatitude = foundedItem.originFarmLatitude; originFarmLongitude = foundedItem.originFarmLongitude; productNotes = foundedItem.productNotes; itemState = foundedItem.itemState; return ( itemSKU, itemUPC, ownerID, distributorID, originFarmName, originFarmInformation, originFarmLatitude, originFarmLongitude, productNotes, itemState ); } // Define a function 'fetchItemBufferForConsumer' that fetches the data only for consumer function fetchItemBufferConsumer(uint _upc) public checkUpcInItems(_upc) view returns ( uint itemSKU, uint itemUPC, address ownerID, address consumerID, string memory originFarmName, string memory productNotes, address distributorID, State itemState ) { // Assign values to the parameters Item memory foundedItem = items[_upc]; itemSKU = foundedItem.sku; itemUPC = foundedItem.upc; ownerID = foundedItem.ownerID; consumerID = foundedItem.consumerID; originFarmName = foundedItem.originFarmName; distributorID = foundedItem.distributorID; productNotes = foundedItem.productNotes; itemState = foundedItem.itemState; return ( itemSKU, itemUPC, ownerID, consumerID, originFarmName, productNotes, distributorID, itemState ); } }
Define a function 'obtainItem' that allows a poulterer to mark an item 'Obtained' Add the new item as part of Obtain Increment sku Emit the appropriate event
function obtainItem( uint _upc, address payable _originPoultererID, string memory _originFarmName, string memory _originFarmInformation, string memory _originFarmLatitude, string memory _originFarmLongitude, string memory _productNotes) public onlyPoulterer() { Item memory newItem = Item( ); items[_upc] = newItem; sku = sku + 1; emit Obtained(_upc, msg.sender); }
1,004,316
./full_match/4/0x5Aac695d3a63139ae64817049Df9230a82473f4B/sources/contracts/PangolinFactory_flat.sol
this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) { uint balance0 = IERC20Joe(token0).balanceOf(address(this)); uint balance1 = IERC20Joe(token1).balanceOf(address(this)); uint amount0 = balance0.sub(_reserve0); uint amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(_reserve0, _reserve1); if (_totalSupply == 0) { address migrator = IJoeFactory(factory).migrator(); if (msg.sender == migrator) { liquidity = IMigrator(migrator).desiredLiquidity(); require(liquidity > 0 && liquidity != uint256(-1), "Bad desired liquidity"); require(migrator == address(0), "Must not have migrator"); liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); } liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, 'Joe: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); emit Mint(msg.sender, amount0, amount1); }
12,283,764
pragma solidity ^0.4.11; contract IssuingAuthority { struct dataMapper { mapping(bytes32 => string) data; } mapping(address => dataMapper) private users; address _owner; string name; bytes32[] private fields; uint private fieldsCount; function IssuingAuthority(address add, bytes32[] _fields, string _name) public { _owner = add; fieldsCount = _fields.length; name = _name; for(uint i=0; i<_fields.length; i++) { fields.push(_fields[i]); } } modifier issuingAuthorityAccess() { require(msg.sender == _owner); _; } function getFieldNameValuePair(uint i) view public returns(bytes32, string) { if(i > fieldsCount) return ("NULL", "NULL"); return (fields[i], users[msg.sender].data[fields[i]]); } function updateData(address uid, bytes32 fieldName, string fieldValue) public issuingAuthorityAccess { users[uid].data[fieldName] = fieldValue; } function changeOwner(address add) public issuingAuthorityAccess { // if owner forgot his keys. _owner = add; } function getNumberOfFields() view public returns(uint) { return fieldsCount; } function getFields(uint i) view public returns(bytes32) { return fields[i]; } function getOwner() view public returns(address) { return _owner; } function getIAName() view public returns(string) { return name; } } contract Sharing { struct DataPoint { string data; string approvedData; uint endTime; bool valid; } event SendForApproval(address user, address citizen, string reqdata); mapping(address => mapping(address => DataPoint)) sharingDataPoints; mapping(address => DataPoint) sharingDataPointsOpen; mapping(address => bool) lockDetails; mapping(address => address[]) approvedCompanies; mapping(address => string) serviceProviderName; function Sharing() public { } /*function request(address userId, string data) public { }*/ function approve(string _data, string _approvedData, address approvedTo, uint eTime) public { require(lockDetails[msg.sender] == false); if(approvedTo == address(0)) { sharingDataPointsOpen[msg.sender].data = _data; sharingDataPointsOpen[msg.sender].approvedData = _approvedData; if(eTime > 0) sharingDataPointsOpen[msg.sender].endTime = now + eTime; } else { sharingDataPoints[msg.sender][approvedTo].data = _data; sharingDataPoints[msg.sender][approvedTo].approvedData = _approvedData; if(eTime > 0) sharingDataPoints[msg.sender][approvedTo].endTime = now + eTime; approvedCompanies[msg.sender].push(approvedTo); } //Event possible. } function modifyApproval(string newEncryptedData, address approvedTo, string newApprovedData) public { if(approvedTo == address(0)) { sharingDataPointsOpen[msg.sender].data = newEncryptedData; sharingDataPointsOpen[msg.sender].approvedData = newApprovedData; } else { sharingDataPoints[msg.sender][approvedTo].data = newEncryptedData; sharingDataPoints[msg.sender][approvedTo].approvedData = newApprovedData; } } function getData(address add) view public returns(string, string) { require(lockDetails[add] == false && now < sharingDataPoints[add][msg.sender].endTime); // Sends encrypted data with key of service provider. return(sharingDataPoints[add][msg.sender].data, sharingDataPoints[add][msg.sender].approvedData); } function getOpenData(address add) view public returns(string, string) { require(lockDetails[add] == false && now < sharingDataPointsOpen[add].endTime); // Sends encrypted data with open key return(sharingDataPointsOpen[add].data, sharingDataPointsOpen[add].approvedData); } // Service provider to customer /* function requestApproval(address user, string _reqData) public returns(bool) { require(lockDetails[user] == false); if(sharingDataPoints[msg.sender][user].valid == false) { SendForApproval(msg.sender, user, _reqData); return false; } return true; } */ function lock() public { require(lockDetails[msg.sender] == false); lockDetails[msg.sender] = true; } function unlock() public { require(lockDetails[msg.sender] == true); lockDetails[msg.sender] = false; } function getApprovedNumberOfCompanies() view public returns(uint) { return approvedCompanies[msg.sender].length; } function getApprovedCompanies(uint p) view public returns(address[5] result) { uint len = approvedCompanies[msg.sender].length; if(len > 5) len = 5; for(uint i=0;i<len;i++) { result[i] = approvedCompanies[msg.sender][i + p]; } for(uint j = len; j<5; j++) { result[j] = address(0); } return result; } function getApprovedData(address company_id) view public returns(string) { require(now < sharingDataPoints[msg.sender][company_id].endTime); return sharingDataPoints[msg.sender][company_id].approvedData; } function registerAsServiceProvider(string name) public { serviceProviderName[msg.sender] = name; } function getServiceProviderName(address add) view public returns(string) { return serviceProviderName[add]; } } contract SuperUser { address private superuser; mapping(address => address) private IAList; uint IASize; address private sharingContract; address[] private IAVector; mapping(bytes32 => uint) private fieldToIAAddress; modifier superuserAccess() { require(msg.sender == superuser); _; } function SuperUser() public { superuser = msg.sender; sharingContract = new Sharing(); IASize = 0; } function addIssuingAuthority(string name, address add, bytes32[] fields) public superuserAccess { IAList[add] = new IssuingAuthority(add, fields, name); IAVector.push(add); for(uint i=0;i<fields.length;i++) { fieldToIAAddress[fields[i]] = IASize; } IASize++; } function getIAContractAddress(address IAAdd)view public returns(address) { return IAList[IAAdd]; } function getSharingContract() view public returns(address) { return sharingContract; } function getNumberOfIA() view public returns(uint) { return IASize; } function getIAAddressContract(uint i) view public returns(address, address) { return (IAVector[i], IAList[IAVector[i]]); } function getSuperuser() view public returns(address) { return superuser; } function getAccount() view public returns(address) { return msg.sender; } function getIAFromField(bytes32 field) view public returns(address) { return IAVector[fieldToIAAddress[field]]; } /*function destroyIAContracts() public superuserAccess { }*/ }
Sends encrypted data with key of service provider.
function getData(address add) view public returns(string, string) { require(lockDetails[add] == false && now < sharingDataPoints[add][msg.sender].endTime); return(sharingDataPoints[add][msg.sender].data, sharingDataPoints[add][msg.sender].approvedData); }
2,481,200
/** *Submitted for verification at Etherscan.io on 2021-03-30 */ // File: ReentrancyGuard.sol pragma solidity ^0.5.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]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // File: Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [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 Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: Crowdsale.sol pragma solidity ^0.5.0; /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conforms * the base architecture for crowdsales. It is *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is Context, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address payable private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param rate Number of token units a buyer gets per wei * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold */ constructor (uint256 rate, address payable wallet, IERC20 token) public { require(rate > 0, "Crowdsale: rate is 0"); require(wallet != address(0), "Crowdsale: wallet is the zero address"); require(address(token) != address(0), "Crowdsale: token is the zero address"); _rate = rate; _wallet = wallet; _token = token; } /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer funds with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ function () external payable { buyTokens(_msgSender()); } /** * @return the token being sold. */ function token() public view returns (IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns (address payable) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns (uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid * conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view { // solhint-disable-previous-line no-empty-blocks } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends * its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send * tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, * etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { // solhint-disable-previous-line no-empty-blocks } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } } // File: TimedCrowdsale.sol pragma solidity ^0.5.0; /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _openingTime; uint256 private _closingTime; /** * Event for crowdsale extending * @param newClosingTime new closing time * @param prevClosingTime old closing time */ event TimedCrowdsaleExtended(uint256 prevClosingTime, uint256 newClosingTime); /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(isOpen(), "TimedCrowdsale: not open"); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param openingTime Crowdsale opening time * @param closingTime Crowdsale closing time */ constructor (uint256 openingTime, uint256 closingTime) public { // solhint-disable-next-line not-rely-on-time require(openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time"); // solhint-disable-next-line max-line-length require(closingTime > openingTime, "TimedCrowdsale: opening time is not before closing time"); _openingTime = openingTime; _closingTime = closingTime; } /** * @return the crowdsale opening time. */ function openingTime() public view returns (uint256) { return _openingTime; } /** * @return the crowdsale closing time. */ function closingTime() public view returns (uint256) { return _closingTime; } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { // solhint-disable-next-line not-rely-on-time return block.timestamp >= _openingTime && block.timestamp <= _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solhint-disable-next-line not-rely-on-time return block.timestamp > _closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal onlyWhileOpen view { super._preValidatePurchase(beneficiary, weiAmount); } /** * @dev Extend crowdsale. * @param newClosingTime Crowdsale closing time */ function _extendTime(uint256 newClosingTime) internal { require(!hasClosed(), "TimedCrowdsale: already closed"); // solhint-disable-next-line max-line-length require(newClosingTime > _closingTime, "TimedCrowdsale: new closing time is before current closing time"); emit TimedCrowdsaleExtended(_closingTime, newClosingTime); _closingTime = newClosingTime; } } // File: FinalizableCrowdsale.sol pragma solidity ^0.5.0; /** * @title FinalizableCrowdsale * @dev Extension of TimedCrowdsale with a one-off finalization action, where one * can do extra work after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale { using SafeMath for uint256; bool private _finalized; event CrowdsaleFinalized(); constructor () internal { _finalized = false; } /** * @return true if the crowdsale is finalized, false otherwise. */ function finalized() public view returns (bool) { return _finalized; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public { require(!_finalized, "FinalizableCrowdsale: already finalized"); require(hasClosed(), "FinalizableCrowdsale: not closed"); _finalized = true; _finalization(); emit CrowdsaleFinalized(); } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super._finalization() to ensure the chain of finalization is * executed entirely. */ function _finalization() internal { // solhint-disable-previous-line no-empty-blocks } } // File: WhitelistAdminRole.sol pragma solidity ^0.5.0; /** * @title WhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ contract WhitelistAdminRole is Context { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor () internal { _addWhitelistAdmin(_msgSender()); } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role"); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(_msgSender()); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } } // File: WhitelistedRole.sol pragma solidity ^0.5.0; /** * @title WhitelistedRole * @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a * crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove * it), and not Whitelisteds themselves. */ contract WhitelistedRole is Context, WhitelistAdminRole { using Roles for Roles.Role; event WhitelistedAdded(address indexed account); event WhitelistedRemoved(address indexed account); Roles.Role private _whitelisteds; modifier onlyWhitelisted() { require(isWhitelisted(_msgSender()), "WhitelistedRole: caller does not have the Whitelisted role"); _; } function isWhitelisted(address account) public view returns (bool) { return _whitelisteds.has(account); } function addWhitelisted(address account) public onlyWhitelistAdmin { _addWhitelisted(account); } function removeWhitelisted(address account) public onlyWhitelistAdmin { _removeWhitelisted(account); } function renounceWhitelisted() public { _removeWhitelisted(_msgSender()); } function _addWhitelisted(address account) internal { _whitelisteds.add(account); emit WhitelistedAdded(account); } function _removeWhitelisted(address account) internal { _whitelisteds.remove(account); emit WhitelistedRemoved(account); } } // File: WhitelistCrowdsale.sol pragma solidity ^0.5.0; /** * @title WhitelistCrowdsale * @dev Crowdsale in which only whitelisted users can contribute. */ contract WhitelistCrowdsale is WhitelistedRole, Crowdsale { /** * @dev Extend parent behavior requiring beneficiary to be whitelisted. Note that no * restriction is imposed on the account sending the transaction. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view { require(isWhitelisted(_beneficiary), "WhitelistCrowdsale: beneficiary doesn't have the Whitelisted role"); super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: PauserRole.sol pragma solidity ^0.5.0; contract PauserRole is Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(_msgSender()); } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } // File: Pausable.sol pragma solidity ^0.5.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: PausableCrowdsale.sol pragma solidity ^0.5.0; /** * @title PausableCrowdsale * @dev Extension of Crowdsale contract where purchases can be paused and unpaused by the pauser role. */ contract PausableCrowdsale is Crowdsale, Pausable { /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use super to concatenate validations. * Adds the validation that the crowdsale must not be paused. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view whenNotPaused { return super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: CapperRole.sol pragma solidity ^0.5.0; contract CapperRole is Context { using Roles for Roles.Role; event CapperAdded(address indexed account); event CapperRemoved(address indexed account); Roles.Role private _cappers; constructor () internal { _addCapper(_msgSender()); } modifier onlyCapper() { require(isCapper(_msgSender()), "CapperRole: caller does not have the Capper role"); _; } function isCapper(address account) public view returns (bool) { return _cappers.has(account); } function addCapper(address account) public onlyCapper { _addCapper(account); } function renounceCapper() public { _removeCapper(_msgSender()); } function _addCapper(address account) internal { _cappers.add(account); emit CapperAdded(account); } function _removeCapper(address account) internal { _cappers.remove(account); emit CapperRemoved(account); } } // File: IndividuallyCappedCrowdsale.sol pragma solidity ^0.5.0; /** * @title IndividuallyCappedCrowdsale * @dev Crowdsale with per-beneficiary caps. */ contract IndividuallyCappedCrowdsale is Crowdsale, CapperRole { using SafeMath for uint256; mapping(address => uint256) private _contributions; uint256 private _perWalletCap; /** * @dev Sets a specific beneficiary's maximum contribution. * @param perWalletCap Wei limit for individual contribution */ function setPerWalletCap(uint256 perWalletCap) public onlyCapper { _perWalletCap = perWalletCap; } /** * @dev Returns the cap of a specific beneficiary. * @return Current cap for individual beneficiary */ function getPerWalletCap() public view returns (uint256) { return _perWalletCap; } /** * @dev Returns the amount contributed so far by a specific beneficiary. * @param beneficiary Address of contributor * @return Beneficiary contribution so far */ function getContribution(address beneficiary) public view returns (uint256) { return _contributions[beneficiary]; } /** * @dev Extend parent behavior requiring purchase to respect the beneficiary's funding cap. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { super._preValidatePurchase(beneficiary, weiAmount); // solhint-disable-next-line max-line-length require(_contributions[beneficiary].add(weiAmount) <= _perWalletCap, "IndividuallyCappedCrowdsale: beneficiary's cap exceeded"); } /** * @dev Extend parent behavior to update beneficiary contributions. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { super._updatePurchasingState(beneficiary, weiAmount); _contributions[beneficiary] = _contributions[beneficiary].add(weiAmount); } } // File: CappedCrowdsale.sol pragma solidity ^0.5.0; /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param cap Max amount of wei to be contributed */ constructor (uint256 cap) public { require(cap > 0, "CappedCrowdsale: cap is 0"); _cap = cap; } /** * @return the cap of the crowdsale. */ function cap() public view returns (uint256) { return _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised() >= _cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { super._preValidatePurchase(beneficiary, weiAmount); require(weiRaised().add(weiAmount) <= _cap, "CappedCrowdsale: cap exceeded"); } } // File: HLDCrowdsale.sol pragma solidity ^0.5.0; contract HLDCrowdsale is CappedCrowdsale, IndividuallyCappedCrowdsale ,PausableCrowdsale, TimedCrowdsale, WhitelistCrowdsale, FinalizableCrowdsale { constructor(uint256 rate, address payable wallet, IERC20 token, uint256 cap, uint256 perWalletCap, uint256 startTime, uint256 endTime) public CappedCrowdsale(cap) TimedCrowdsale(startTime, endTime) Crowdsale(rate, wallet, IERC20(token)) { setPerWalletCap(perWalletCap); } function _finalization() internal { IERC20 token = token(); address wallet = wallet(); uint256 remaining = token.balanceOf(address(this)); token.transfer(wallet, remaining); super._finalization(); } function addManyToWhitelist(address[] calldata list) external onlyWhitelistAdmin{ for (uint256 i = 0 ; i < list.length ; i++) { _addWhitelisted(list[i]); } } }
Returns the cap of a specific beneficiary. return Current cap for individual beneficiary/
function getPerWalletCap() public view returns (uint256) { return _perWalletCap; }
15,108,520
/** *Submitted for verification at Etherscan.io on 2020-10-11 */ /* B.PROTOCOL TERMS OF USE ======================= THE TERMS OF USE CONTAINED HEREIN (THESE 1TERMS1) GOVERN YOUR USE OF B.PROTOCOL, WHICH IS A DECENTRALIZED PROTOCOL ON THE ETHEREUM BLOCKCHAIN (the 1PROTOCOL1) THAT enables a backstop liquidity mechanism FOR DECENTRALIZED LENDING PLATFORMS1(1DLPs1). PLEASE READ THESE TERMS CAREFULLY AT https://github.com/backstop-protocol/Terms-and-Conditions, INCLUDING ALL DISCLAIMERS AND RISK FACTORS, BEFORE USING THE PROTOCOL. BY USING THE PROTOCOL, YOU ARE IRREVOCABLY CONSENTING TO BE BOUND BY THESE TERMS. IF YOU DO NOT AGREE TO ALL OF THESE TERMS, DO NOT USE THE PROTOCOL. YOUR RIGHT TO USE THE PROTOCOL IS SUBJECT AND DEPENDENT BY YOUR AGREEMENT TO ALL TERMS AND CONDITIONS SET FORTH HEREIN, WHICH AGREEMENT SHALL BE EVIDENCED BY YOUR USE OF THE PROTOCOL. Minors Prohibited: The Protocol is not directed to individuals under the age of eighteen (18) or the age of majority in your jurisdiction if the age of majority is greater. If you are under the age of eighteen or the age of majority (if greater), you are not authorized to access or use the Protocol. By using the Protocol, you represent and warrant that you are above such age. License; No Warranties; Limitation of Liability; (a) The software underlying the Protocol is licensed for use in accordance with the 3-clause BSD License, which can be accessed here: https://opensource.org/licenses/BSD-3-Clause. (b) THE PROTOCOL IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS", 1WITH ALL FAULTS1 and 1AS AVAILABLE1 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. (c) IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /// DssProxyActions.sol // Copyright (C) 2018-2020 Maker Ecosystem Growth Holdings, INC. // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.5.12; contract GemLike { function approve(address, uint) public; function transfer(address, uint) public; function transferFrom(address, address, uint) public; function deposit() public payable; function withdraw(uint) public; } contract ManagerLike { function cdpCan(address, uint, address) public view returns (uint); function ilks(uint) public view returns (bytes32); function owns(uint) public view returns (address); function urns(uint) public view returns (address); function vat() public view returns (address); function open(bytes32, address) public returns (uint); function give(uint, address) public; function cdpAllow(uint, address, uint) public; function urnAllow(address, uint) public; function frob(uint, int, int) public; function flux(uint, address, uint) public; function move(uint, address, uint) public; function exit(address, uint, address, uint) public; function quit(uint, address) public; function enter(address, uint) public; function shift(uint, uint) public; } contract VatLike { function can(address, address) public view returns (uint); function ilks(bytes32) public view returns (uint, uint, uint, uint, uint); function dai(address) public view returns (uint); function urns(bytes32, address) public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) public; function hope(address) public; function move(address, address, uint) public; } contract GemJoinLike { function dec() public returns (uint); function gem() public returns (GemLike); function join(address, uint) public payable; function exit(address, uint) public; } contract GNTJoinLike { function bags(address) public view returns (address); function make(address) public returns (address); } contract DaiJoinLike { function vat() public returns (VatLike); function dai() public returns (GemLike); function join(address, uint) public payable; function exit(address, uint) public; } contract HopeLike { function hope(address) public; function nope(address) public; } contract EndLike { function fix(bytes32) public view returns (uint); function cash(bytes32, uint) public; function free(bytes32) public; function pack(uint) public; function skim(bytes32, address) public; } contract JugLike { function drip(bytes32) public returns (uint); } contract PotLike { function pie(address) public view returns (uint); function drip() public returns (uint); function join(uint) public; function exit(uint) public; } contract ProxyRegistryLike { function proxies(address) public view returns (address); function build(address) public returns (address); } contract ProxyLike { function owner() public view returns (address); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // WARNING: These functions meant to be used as a a library for a DSProxy. Some are unsafe if you call them directly. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! contract Common { uint256 constant RAY = 10 ** 27; // Internal functions function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions function daiJoin_join(address apt, address urn, uint wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract DssProxyActions is Common { // Internal functions function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } function toRad(uint wad) internal pure returns (uint rad) { rad = mul(wad, 10 ** 27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul( amt, 10 ** (18 - GemJoinLike(gemJoin).dec()) ); } function _getDrawDart( address vat, address jug, address urn, bytes32 ilk, uint wad ) internal returns (int dart) { // Updates stability fee rate uint rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart( address vat, uint dai, address urn, bytes32 ilk ) internal view returns (int dart) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint(dart) <= art ? - dart : - toInt(art); } function _getWipeAllWad( address vat, address usr, address urn, bytes32 ilk ) internal view returns (uint wad) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint dai = VatLike(vat).dai(usr); uint rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint amt) public { GemLike(gem).transfer(dst, amt); } function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit.value(msg.value)(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } function gemJoin_join(address apt, address urn, uint amt, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), amt); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, amt); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, amt); } function hope( address obj, address usr ) public { HopeLike(obj).hope(usr); } function nope( address obj, address usr ) public { HopeLike(obj).nope(usr); } function open( address manager, bytes32 ilk, address usr ) public returns (uint cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give( address manager, uint cdp, address usr ) public { ManagerLike(manager).give(cdp, usr); } function giveToProxy( address proxyRegistry, address manager, uint cdp, address dst ) public { // Gets actual proxy address address proxy = ProxyRegistryLike(proxyRegistry).proxies(dst); // Checks if the proxy address already existed and dst address is still the owner if (proxy == address(0) || ProxyLike(proxy).owner() != dst) { uint csize; assembly { csize := extcodesize(dst) } // We want to avoid creating a proxy for a contract address that might not be able to handle proxies, then losing the CDP require(csize == 0, "Dst-is-a-contract"); // Creates the proxy for the dst address proxy = ProxyRegistryLike(proxyRegistry).build(dst); } // Transfers CDP to the dst proxy give(manager, cdp, proxy); } function cdpAllow( address manager, uint cdp, address usr, uint ok ) public { ManagerLike(manager).cdpAllow(cdp, usr, ok); } function urnAllow( address manager, address usr, uint ok ) public { ManagerLike(manager).urnAllow(usr, ok); } function flux( address manager, uint cdp, address dst, uint wad ) public { ManagerLike(manager).flux(cdp, dst, wad); } function move( address manager, uint cdp, address dst, uint rad ) public { ManagerLike(manager).move(cdp, dst, rad); } function frob( address manager, uint cdp, int dink, int dart ) public { ManagerLike(manager).frob(cdp, dink, dart); } function quit( address manager, uint cdp, address dst ) public { ManagerLike(manager).quit(cdp, dst); } function enter( address manager, address src, uint cdp ) public { ManagerLike(manager).enter(src, cdp); } function shift( address manager, uint cdpSrc, uint cdpOrg ) public { ManagerLike(manager).shift(cdpSrc, cdpOrg); } function makeGemBag( address gemJoin ) public returns (address bag) { bag = GNTJoinLike(gemJoin).make(address(this)); } function lockETH( address manager, address ethJoin, uint cdp ) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function safeLockETH( address manager, address ethJoin, uint cdp, address owner ) public payable { require(ManagerLike(manager).owns(cdp) == owner, "owner-missmatch"); lockETH(manager, ethJoin, cdp); } function lockGem( address manager, address gemJoin, uint cdp, uint amt, bool transferFrom ) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), amt, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, amt)), 0 ); } function safeLockGem( address manager, address gemJoin, uint cdp, uint amt, bool transferFrom, address owner ) public { require(ManagerLike(manager).owns(cdp) == owner, "owner-missmatch"); lockGem(manager, gemJoin, cdp, amt, transferFrom); } function freeETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Unlocks WETH amount from the CDP frob(manager, cdp, -toInt(wad), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function freeGem( address manager, address gemJoin, uint cdp, uint amt ) public { uint wad = convertTo18(gemJoin, amt); // Unlocks token amount from the CDP frob(manager, cdp, -toInt(wad), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, amt); } function exitETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function exitGem( address manager, address gemJoin, uint cdp, uint amt ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), convertTo18(gemJoin, amt)); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, amt); } function draw( address manager, address jug, address daiJoin, uint cdp, uint wad ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function wipe( address manager, address daiJoin, uint cdp, uint wad ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wad); // Paybacks debt to the CDP frob(manager, cdp, 0, _getWipeDart(vat, VatLike(vat).dai(urn), urn, ilk)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), wad); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, _getWipeDart(vat, wad * RAY, urn, ilk) //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC ); } } function safeWipe( address manager, address daiJoin, uint cdp, uint wad, address owner ) public { require(ManagerLike(manager).owns(cdp) == owner, "owner-missmatch"); wipe(manager, daiJoin, cdp, wad); } function wipeAll( address manager, address daiJoin, uint cdp ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP frob(manager, cdp, 0, -int(art)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), _getWipeAllWad(vat, address(this), urn, ilk)); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, -int(art) ); } } function safeWipeAll( address manager, address daiJoin, uint cdp, address owner ) public { require(ManagerLike(manager).owns(cdp) == owner, "owner-missmatch"); wipeAll(manager, daiJoin, cdp); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD ) public payable returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint amtC, uint wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, amtC, transferFrom); // Locks token amount into the CDP and generates debt frob(manager, cdp, toInt(convertTo18(gemJoin, amtC)), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint amtC, uint wadD, bool transferFrom ) public returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, amtC, wadD, transferFrom); } function openLockGNTAndDraw( address manager, address jug, address gntJoin, address daiJoin, bytes32 ilk, uint amtC, uint wadD ) public returns (address bag, uint cdp) { // Creates bag (if doesn't exist) to hold GNT bag = GNTJoinLike(gntJoin).bags(address(this)); if (bag == address(0)) { bag = makeGemBag(gntJoin); } // Transfer funds to the funds which previously were sent to the proxy GemLike(GemJoinLike(gntJoin).gem()).transfer(bag, amtC); cdp = openLockGemAndDraw(manager, jug, gntJoin, daiJoin, ilk, amtC, wadD, false); } function wipeAndFreeETH( address manager, address ethJoin, address daiJoin, uint cdp, uint wadC, uint wadD ) public { address urn = ManagerLike(manager).urns(cdp); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wadD); // Paybacks debt to the CDP and unlocks WETH amount from it frob( manager, cdp, -toInt(wadC), _getWipeDart(ManagerLike(manager).vat(), VatLike(ManagerLike(manager).vat()).dai(urn), urn, ManagerLike(manager).ilks(cdp)) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); } function wipeAllAndFreeETH( address manager, address ethJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP and unlocks WETH amount from it frob( manager, cdp, -toInt(wadC), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); } function wipeAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint amtC, uint wadD ) public { address urn = ManagerLike(manager).urns(cdp); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wadD); uint wadC = convertTo18(gemJoin, amtC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wadC), _getWipeDart(ManagerLike(manager).vat(), VatLike(ManagerLike(manager).vat()).dai(urn), urn, ManagerLike(manager).ilks(cdp)) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, amtC); } function wipeAllAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint amtC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); uint wadC = convertTo18(gemJoin, amtC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wadC), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, amtC); } } contract DssProxyActionsEnd is Common { // Internal functions function _free( address manager, address end, uint cdp ) internal returns (uint ink) { bytes32 ilk = ManagerLike(manager).ilks(cdp); address urn = ManagerLike(manager).urns(cdp); VatLike vat = VatLike(ManagerLike(manager).vat()); uint art; (ink, art) = vat.urns(ilk, urn); // If CDP still has debt, it needs to be paid if (art > 0) { EndLike(end).skim(ilk, urn); (ink,) = vat.urns(ilk, urn); } // Approves the manager to transfer the position to proxy's address in the vat if (vat.can(address(this), address(manager)) == 0) { vat.hope(manager); } // Transfers position from CDP to the proxy address ManagerLike(manager).quit(cdp, address(this)); // Frees the position and recovers the collateral in the vat registry EndLike(end).free(ilk); } // Public functions function freeETH( address manager, address ethJoin, address end, uint cdp ) public { uint wad = _free(manager, end, cdp); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function freeGem( address manager, address gemJoin, address end, uint cdp ) public { uint amt = _free(manager, end, cdp) / 10 ** (18 - GemJoinLike(gemJoin).dec()); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, amt); } function pack( address daiJoin, address end, uint wad ) public { daiJoin_join(daiJoin, address(this), wad); VatLike vat = DaiJoinLike(daiJoin).vat(); // Approves the end to take out DAI from the proxy's balance in the vat if (vat.can(address(this), address(end)) == 0) { vat.hope(end); } EndLike(end).pack(wad); } function cashETH( address ethJoin, address end, bytes32 ilk, uint wad ) public { EndLike(end).cash(ilk, wad); uint wadC = mul(wad, EndLike(end).fix(ilk)) / RAY; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); } function cashGem( address gemJoin, address end, bytes32 ilk, uint wad ) public { EndLike(end).cash(ilk, wad); // Exits token amount to the user's wallet as a token uint amt = mul(wad, EndLike(end).fix(ilk)) / RAY / 10 ** (18 - GemJoinLike(gemJoin).dec()); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC GemJoinLike(gemJoin).exit(msg.sender, amt); } } contract DssProxyActionsDsr is Common { function join( address daiJoin, address pot, uint wad ) public { VatLike vat = DaiJoinLike(daiJoin).vat(); // Executes drip to get the chi rate updated to rho == now, otherwise join will fail uint chi = PotLike(pot).drip(); // Joins wad amount to the vat balance daiJoin_join(daiJoin, address(this), wad); // Approves the pot to take out DAI from the proxy's balance in the vat if (vat.can(address(this), address(pot)) == 0) { vat.hope(pot); } // Joins the pie value (equivalent to the DAI wad amount) in the pot PotLike(pot).join(mul(wad, RAY) / chi); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function exit( address daiJoin, address pot, uint wad ) public { VatLike vat = DaiJoinLike(daiJoin).vat(); // Executes drip to count the savings accumulated until this moment uint chi = PotLike(pot).drip(); // Calculates the pie value in the pot equivalent to the DAI wad amount uint pie = mul(wad, RAY) / chi; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC // Exits DAI from the pot PotLike(pot).exit(pie); // Checks the actual balance of DAI in the vat after the pot exit uint bal = DaiJoinLike(daiJoin).vat().dai(address(this)); // Allows adapter to access to proxy's DAI balance in the vat if (vat.can(address(this), address(daiJoin)) == 0) { vat.hope(daiJoin); } // It is necessary to check if due rounding the exact wad amount can be exited by the adapter. // Otherwise it will do the maximum DAI balance in the vat DaiJoinLike(daiJoin).exit( msg.sender, bal >= mul(wad, RAY) ? wad : bal / RAY //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC ); } function exitAll( address daiJoin, address pot ) public { VatLike vat = DaiJoinLike(daiJoin).vat(); // Executes drip to count the savings accumulated until this moment uint chi = PotLike(pot).drip(); // Gets the total pie belonging to the proxy address uint pie = PotLike(pot).pie(address(this)); // Exits DAI from the pot PotLike(pot).exit(pie); // Allows adapter to access to proxy's DAI balance in the vat if (vat.can(address(this), address(daiJoin)) == 0) { vat.hope(daiJoin); } // Exits the DAI amount corresponding to the value of pie DaiJoinLike(daiJoin).exit(msg.sender, mul(chi, pie) / RAY); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } } /// BProxyActions.sol contract BProxyActions is DssProxyActions { function shiftManager( address managerSrc, address managerDst, uint cdpSrc, uint cdpDst ) public { address vat = ManagerLike(managerSrc).vat(); require(vat == ManagerLike(managerDst).vat(), "vat-mismatch"); bool canSrc = (VatLike(vat).can(address(this), managerSrc) != 0); bool canDst = (VatLike(vat).can(address(this), managerDst) != 0); if(! canSrc) hope(vat, managerSrc); if(! canDst) hope(vat, managerDst); quit(managerSrc, cdpSrc, address(this)); enter(managerDst, address(this), cdpDst); if(! canSrc) nope(vat, managerSrc); if(! canDst) nope(vat, managerDst); } function lockETHViaCdp( address manager, address ethJoin, uint cdp ) public payable { address urn = ManagerLike(manager).urns(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), 0); } function openLockETHAndGiveToProxy( address proxyRegistry, address manager, address ethJoin, bytes32 ilk, address dst ) public payable returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockETHViaCdp(manager,ethJoin,cdp); giveToProxy(proxyRegistry,manager,cdp,dst); } function openAndImportFromManager( address managerSrc, address managerDst, uint cdpSrc, bytes32 ilk ) public payable returns (uint cdp) { cdp = open(managerDst, ilk, address(this)); shiftManager(managerSrc,managerDst,cdpSrc,cdp); } }
Gets actual rate from the vat Gets actual art value of the urn Gets actual dai amount in the urn If the rad precision has some dust, it will need to request for 1 extra wad wei
function _getWipeAllWad( address vat, address usr, address urn, bytes32 ilk ) internal view returns (uint wad) { (, uint rate,,,) = VatLike(vat).ilks(ilk); (, uint art) = VatLike(vat).urns(ilk, urn); uint dai = VatLike(vat).dai(usr); uint rad = sub(mul(art, rate), dai); wad = rad / RAY; wad = mul(wad, RAY) < rad ? wad + 1 : wad; }
982,517
./full_match/1/0x2355839B2757880d08b978fc5BA73FdC6159B832/sources/contracts/ICloneforceShard.sol
0 = dna shard, 1 = boundless shard
function getShardType(uint256 tokenId) external view returns (uint256);
5,007,151
pragma solidity ^0.4.11; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; import "zeppelin-solidity/contracts/crowdsale/FinalizableCrowdsale.sol"; import "./TokensCappedCrowdsale.sol"; import "./PausableCrowdsale.sol"; import "./BonusCrowdsale.sol"; import "./PreBOUToken.sol"; /** * @dev Main BoutsPro Crowdsale contract. * Based on references from OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity * */ contract BoutsCrowdsale is MintableToken,FinalizableCrowdsale, TokensCappedCrowdsale(BoutsCrowdsale.CAP), PausableCrowdsale(true), BonusCrowdsale(BoutsCrowdsale.TOKEN_USDCENT_PRICE) { // Constants uint256 public constant DECIMALS = 18; uint256 public constant CAP = 2 * (10**9) * (10**DECIMALS); // 2B BOUT uint256 public constant BOUTSPRO_AMOUNT = 1 * (10**9) * (10**DECIMALS); // 1B BOUT uint256 public constant TOKEN_USDCENT_PRICE = 10; // $0.10 // Variables address public remainingTokensWallet; address public presaleWallet; /** * @dev Sets BOUT to Ether rate. Will be called multiple times durign the crowdsale to adjsut the rate * since BOUT cost is fixed in USD, but USD/ETH rate is changing * @param _rate defines BOUT/ETH rate: 1 ETH = _rate BOUTs */ function setRate(uint256 _rate) external onlyOwner { require(_rate != 0x0); rate = _rate; RateChange(_rate); } /** * @dev Allows to adjust the crowdsale end time */ function setEndTime(uint256 _endTime) external onlyOwner { require(!isFinalized); require(_endTime >= startTime); require(_endTime >= now); endTime = _endTime; } /** * @dev Sets the wallet to forward ETH collected funds */ function setWallet(address _wallet) external onlyOwner { require(_wallet != 0x0); wallet = _wallet; } /** * @dev Sets the wallet to hold unsold tokens at the end of ICO */ function setRemainingTokensWallet(address _remainingTokensWallet) external onlyOwner { require(_remainingTokensWallet != 0x0); remainingTokensWallet = _remainingTokensWallet; } // Events event RateChange(uint256 rate); /** * @dev Contructor * @param _startTime startTime of crowdsale * @param _endTime endTime of crowdsale * @param _rate BOUT / ETH rate * @param _wallet wallet to forward the collected funds * @param _remainingTokensWallet wallet to hold the unsold tokens * @param _boutsProWallet wallet to hold the initial 1B tokens of BoutsPro */ function BoutsCrowdsale( uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _remainingTokensWallet, address _boutsProWallet ) public Crowdsale(_startTime, _endTime, _rate, _wallet) { remainingTokensWallet = _remainingTokensWallet; presaleWallet = this; // allocate tokens to BoutsPro mintTokens(_boutsProWallet, BOUTSPRO_AMOUNT); } // Overrided methods /** * @dev Creates token contract for ICO * @return ERC20 contract associated with the crowdsale */ function createTokenContract() internal returns(MintableToken) { PreBOUToken token = new PreBOUToken(); token.pause(); return token; } /** * @dev Finalizes the crowdsale */ function finalization() internal { super.finalization(); // Mint tokens up to CAP if (token.totalSupply() < tokensCap) { uint tokens = tokensCap.sub(token.totalSupply()); token.mint(remainingTokensWallet, tokens); } // disable minting of BOUTs token.finishMinting(); // take onwership over BOUToken contract token.transferOwnership(owner); } // Owner methods /** * @dev Helper to Pause BOUToken */ function pauseTokens() public onlyOwner { PreBOUToken(token).pause(); } /** * @dev Helper to UnPause BOUToken */ function unpauseTokens() public onlyOwner { PreBOUToken(token).unpause(); } /** * @dev Allocates tokens from preSale to a special wallet. Called once as part of crowdsale setup */ function mintPresaleTokens(uint256 tokens) public onlyOwner { mintTokens(presaleWallet, tokens); presaleWallet = 0; } /** * @dev Transfer presaled tokens even on paused token contract */ function transferPresaleTokens(address destination, uint256 amount) public onlyOwner { unpauseTokens(); token.transfer(destination, amount); pauseTokens(); } // /** * @dev Allocates tokens for investors that contributed from website. These include * white listed investors and investors paying with BTC/QTUM/LTC */ function mintTokens(address beneficiary, uint256 tokens) public onlyOwner { require(beneficiary != 0x0); require(tokens > 0); require(now <= endTime); // Crowdsale (without startTime check) require(!isFinalized); // FinalizableCrowdsale require(token.totalSupply().add(tokens) <= tokensCap); // TokensCappedCrowdsale token.mint(beneficiary, tokens); } }
Helper to Pause BOUToken/
function pauseTokens() public onlyOwner { PreBOUToken(token).pause(); }
12,685,428
./full_match/1/0x51a3282B75D1a82A0eEB85be2b9BEb1FfeEE0250/sources/contracts/ZIPO.sol
Function to add or remove an airdrop contract
function setAirdropContract(address _airdropContract, bool _isAirdrop) public onlyOwner { isAirdropContract[_airdropContract] = _isAirdrop; }
4,963,817
/** *Submitted for verification at Etherscan.io on 2021-07-26 */ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; // Part: Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: Context /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Part: IERC165 /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // Part: IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Part: ERC165 /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // Part: 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 {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 { } } // Part: IERC1155 /** @title ERC-1155 Multi Token Standard @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md Note: The ERC-165 identifier for this interface is 0xd9b67a26. */ interface IERC1155 is IERC165 { /** @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). The `_operator` argument MUST be msg.sender. The `_from` argument MUST be the address of the holder whose balance is decreased. The `_to` argument MUST be the address of the recipient whose balance is increased. The `_id` argument MUST be the token type being transferred. The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by. When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). */ event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value); /** @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). The `_operator` argument MUST be msg.sender. The `_from` argument MUST be the address of the holder whose balance is decreased. The `_to` argument MUST be the address of the recipient whose balance is increased. The `_ids` argument MUST be the list of tokens being transferred. The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by. When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). */ event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values); /** @dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absense of an event assumes disabled). */ event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /** @dev MUST emit when the URI is updated for a token ID. URIs are defined in RFC 3986. The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema". */ event URI(string _value, uint256 indexed _id); /** @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if balance of holder for token `_id` is lower than the `_value` sent. MUST revert on any other error. MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _id ID of the token type @param _value Transfer amount @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external; /** @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if length of `_ids` is not the same as length of `_values`. MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient. MUST revert on any other error. MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard). Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc). After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _ids IDs of each token type (order and length must match _values array) @param _values Transfer amounts per token type (order and length must match _ids array) @param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external; /** @notice Get the balance of an account's Tokens. @param _owner The address of the token holder @param _id ID of the Token @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) external view returns (uint256); /** @notice Get the balance of multiple account/token pairs @param _owners The addresses of the token holders @param _ids ID of the Tokens @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); /** @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. @dev MUST emit the ApprovalForAll event on success. @param _operator Address to add to the set of authorized operators @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external; /** @notice Queries the approval status of an operator for a given owner. @param _owner The owner of the Tokens @param _operator Address of authorized operator @return True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool); } // Part: IERC1155Receiver /** * _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); } // Part: Ownable /** * @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; } } // Part: SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: ERC1155Receiver abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() internal { _registerInterface( ERC1155Receiver(0).onERC1155Received.selector ^ ERC1155Receiver(0).onERC1155BatchReceived.selector ); } } // Part: GovernanceContract contract GovernanceContract is Ownable { mapping(address => bool) public governanceContracts; event GovernanceContractAdded(address addr); event GovernanceContractRemoved(address addr); modifier onlyGovernanceContracts() { require(governanceContracts[msg.sender]); _; } function addAddressToGovernanceContract(address addr) onlyOwner public returns(bool success) { if (!governanceContracts[addr]) { governanceContracts[addr] = true; emit GovernanceContractAdded(addr); success = true; } } function removeAddressFromGovernanceContract(address addr) onlyOwner public returns(bool success) { if (governanceContracts[addr]) { governanceContracts[addr] = false; emit GovernanceContractRemoved(addr); success = true; } } } // Part: MilkyWayToken contract MilkyWayToken is ERC20("MilkyWay Token by SpaceSwap v2", "MILK2"), GovernanceContract { uint256 private _totalBurned; /** * @dev See {IERC20-totalSupply}. */ function totalBurned() public view returns (uint256) { return _totalBurned; } /// @notice Creates `_amount` token to `_to`. Must only be called by the Governance Contracts function mint(address _to, uint256 _amount) public onlyGovernanceContracts virtual returns (bool) { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); return true; } /// @notice Creates `_amount` token to `_to`. Must only be called by the Governance Contracts function burn(address _to, uint256 _amount) public onlyGovernanceContracts virtual returns (bool) { _burn(_to, _amount); _totalBurned = _totalBurned.add(_amount); _moveDelegates(_delegates[_to], address(0), _amount); return true; } // 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 // @notice 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 that's emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event that's 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), "MILKYWAY::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "MILKYWAY::delegateBySig: invalid nonce"); require(now <= expiry, "MILKYWAY::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, "MILKYWAY::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 MILKYWAY (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, "MILKYWAY::_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: flat.sol /** // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once MILKYWAY is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. */ contract GalaxyNFT is Ownable, ERC1155Receiver { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many NFT tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } // Info of each pool. struct PoolInfo { uint256 nftId; // NFT ID uint256 allocPoint; // How many allocation points assigned to this pool. MILK2s to distribute per block. uint256 lastRewardBlock; // Last block number that MILK2s distribution occurs. uint256 accMilkPerShare; // Accumulated MILK2s per share, times 1e12. See below. } // The MILKYWAY_Token! MilkyWayToken public milk; IERC1155 public NFTToken; IERC20 public lpToken; // Dev address. address public devAddr; // Distribution address. address public distributor; // The block number when MILK2 mining starts. uint256 public startBlock; uint256 internal milkPerBlock = 250; // 2.5 // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes NFT 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; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( MilkyWayToken _milk, IERC1155 _nft, address _devAddr, address _distributor, uint256 _startBlock, IERC20 _lpToken ) public { milk = _milk; NFTToken = _nft; devAddr = _devAddr; distributor = _distributor; startBlock = _startBlock; lpToken = _lpToken; } function setMilkPerBlock(uint256 _newAmount) public onlyOwner{ milkPerBlock = _newAmount; } // view length of liquidity pools function poolLength() external view returns (uint256) { return poolInfo.length; } function approvalNFTTransfers() public onlyOwner { NFTToken.setApprovalForAll(address(this), true); } // Add a new NFT to the pool. Can only be called by the owner. // XXX DO NOT add the same NFT token more than once. Rewards will be messed up if you do. function addFarmingToken(uint256 _allocPoint, uint256 _nftId, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({nftId: _nftId, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accMilkPerShare: 0 })); } // Update the given pool's MILK2 allocation point. Can only be called by the owner. function setFarmingToken(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(milkPerBlock); } // View current block reward in MILK2s function getCurrentBlockReward() public view returns (uint256) { return milkPerBlock; } // View function to see pending MILK2s on frontend. function pendingMilk(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accMilkPerShare = pool.accMilkPerShare; uint256 NFTSupply = NFTToken.balanceOf(address(this), pool.nftId); if (block.number > pool.lastRewardBlock && NFTSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 milkReward = (multiplier.mul(1e16)).mul(pool.allocPoint).div(totalAllocPoint); accMilkPerShare = accMilkPerShare.add(milkReward.mul(1e12).div(NFTSupply)); } return user.amount.mul(accMilkPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 NFTSupply = NFTToken.balanceOf(address(this), pool.nftId); if (NFTSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 milkReward = multiplier.mul(1e16).mul(pool.allocPoint).div(totalAllocPoint); //milk.mint(devAddr, milkReward.mul(3).div(100)); // 3% developers //milk.mint(distributor, milkReward.div(100)); // 1% shakeHolders //milk.mint(address(this), milkReward); milk.transferFrom(owner(), address(this), milkReward); pool.accMilkPerShare = pool.accMilkPerShare.add(milkReward.mul(1e12).div(NFTSupply)); pool.lastRewardBlock = block.number; } // Deposit NFT tokens to Interstellar for MILK allocation. function depositFarmingToken(uint256 _pid, uint256 _amount) public { require(lpToken.balanceOf(msg.sender) > 0, "Insufficient LPtoken balance"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accMilkPerShare).div(1e12).sub(user.rewardDebt); safeMilkTransfer(msg.sender, pending); } NFTToken.safeTransferFrom(address(msg.sender), address(this), pool.nftId, _amount, ""); // user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accMilkPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw NFT tokens from Interstellar. function withdrawFarmingToken(uint256 _pid, uint256 _amount) public { require(lpToken.balanceOf(msg.sender) > 0, "Insufficient LPtoken balance"); 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.accMilkPerShare).div(1e12).sub(user.rewardDebt); safeMilkTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accMilkPerShare).div(1e12); NFTToken.safeTransferFrom(address(this), address(msg.sender), pool.nftId, _amount, ""); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdrawFarmingToken(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; NFTToken.safeTransferFrom(address(this), address(msg.sender), pool.nftId, user.amount, ""); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe milk2 transfer function, just in case if rounding error causes pool to not have enough MILK2s. function safeMilkTransfer(address _to, uint256 _amount) internal { uint256 milkBal = milk.balanceOf(address(this)); if (_amount > milkBal) { milk.transfer(_to, milkBal); } else { milk.transfer(_to, _amount); } } // Update dev address by the previous dev. function setDevAddress(address _devAddr) public { require(msg.sender == devAddr, "dev: wut?"); devAddr = _devAddr; } // Update distributor address by the previous dev. function updateDistributor(address _distributor) public { require(msg.sender == devAddr, "dev: wut?"); distributor = _distributor; } function onERC1155Received(address, address, uint256, uint256, bytes calldata) external override returns (bytes4) { return IERC1155Receiver.onERC1155Received.selector; } function onERC1155BatchReceived(address, address, uint256[] calldata, uint256[] calldata , bytes calldata) external override returns (bytes4) { return IERC1155Receiver.onERC1155BatchReceived.selector; } }
View current block reward in MILK2s
function getCurrentBlockReward() public view returns (uint256) { return milkPerBlock; }
2,454,940
pragma solidity ^0.4.24; pragma solidity ^0.4.24; pragma solidity ^0.4.20; contract CutieCoreInterface { function isCutieCore() pure public returns (bool); function transferFrom(address _from, address _to, uint256 _cutieId) external; function transfer(address _to, uint256 _cutieId) external; function ownerOf(uint256 _cutieId) external view returns (address owner); function getCutie(uint40 _id) external view returns ( uint256 genes, uint40 birthTime, uint40 cooldownEndTime, uint40 momId, uint40 dadId, uint16 cooldownIndex, uint16 generation ); function getGenes(uint40 _id) public view returns ( uint256 genes ); function getCooldownEndTime(uint40 _id) public view returns ( uint40 cooldownEndTime ); function getCooldownIndex(uint40 _id) public view returns ( uint16 cooldownIndex ); function getGeneration(uint40 _id) public view returns ( uint16 generation ); function getOptional(uint40 _id) public view returns ( uint64 optional ); function changeGenes( uint40 _cutieId, uint256 _genes) public; function changeCooldownEndTime( uint40 _cutieId, uint40 _cooldownEndTime) public; function changeCooldownIndex( uint40 _cutieId, uint16 _cooldownIndex) public; function changeOptional( uint40 _cutieId, uint64 _optional) public; function changeGeneration( uint40 _cutieId, uint16 _generation) public; } pragma solidity ^0.4.20; pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev 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(); } } pragma solidity ^0.4.24; /// @title Auction Market for Blockchain Cuties. /// @author https://BlockChainArchitect.io contract MarketInterface { function withdrawEthFromBalance() external; function createAuction(uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller) public payable; function bid(uint40 _cutieId) public payable; function cancelActiveAuctionWhenPaused(uint40 _cutieId) public; function getAuctionInfo(uint40 _cutieId) public view returns ( address seller, uint128 startPrice, uint128 endPrice, uint40 duration, uint40 startedAt, uint128 featuringFee, bool tokensAllowed ); } pragma solidity ^0.4.24; // https://etherscan.io/address/0x4118d7f757ad5893b8fa2f95e067994e1f531371#code interface ERC20 { /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approveAndCall(address _spender, uint256 _value, bytes _extraData) external returns (bool success); /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) external; /// @notice Count all tokens assigned to an owner function balanceOf(address _owner) external view returns (uint256); } pragma solidity ^0.4.24; // https://etherscan.io/address/0x3127be52acba38beab6b4b3a406dc04e557c037c#code contract PriceOracleInterface { // How much TOKENs you get for 1 ETH, multiplied by 10^18 uint256 public ETHPrice; } pragma solidity ^0.4.24; interface TokenRecipientInterface { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } /// @title Auction Market for Blockchain Cuties. /// @author https://BlockChainArchitect.io contract Market is MarketInterface, Pausable, TokenRecipientInterface { // Shows the auction on an Cutie Token struct Auction { // Price (in wei or tokens) at the beginning of auction uint128 startPrice; // Price (in wei or tokens) at the end of auction uint128 endPrice; // Current owner of Token address seller; // Auction duration in seconds uint40 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint40 startedAt; // Featuring fee (in wei, optional) uint128 featuringFee; // is it allowed to bid with erc20 tokens bool tokensAllowed; } // Reference to contract that tracks ownership CutieCoreInterface public coreContract; // Cut owner takes on each auction, in basis points - 1/100 of a per cent. // Values 0-10,000 map to 0%-100% uint16 public ownerFee; // Map from token ID to their corresponding auction. mapping (uint40 => Auction) public cutieIdToAuction; mapping (address => PriceOracleInterface) public priceOracle; address operatorAddress; event AuctionCreated(uint40 indexed cutieId, uint128 startPrice, uint128 endPrice, uint40 duration, uint128 fee, bool tokensAllowed); event AuctionSuccessful(uint40 indexed cutieId, uint128 totalPriceWei, address indexed winner); event AuctionSuccessfulForToken(uint40 indexed cutieId, uint128 totalPriceWei, address indexed winner, uint128 priceInTokens, address indexed token); event AuctionCancelled(uint40 indexed cutieId); modifier onlyOperator() { require(msg.sender == operatorAddress || msg.sender == owner); _; } function setOperator(address _newOperator) public onlyOwner { require(_newOperator != address(0)); operatorAddress = _newOperator; } /// @dev disables sending fund to this contract function() external {} modifier canBeStoredIn128Bits(uint256 _value) { require(_value <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); _; } // @dev Adds to the list of open auctions and fires the // AuctionCreated event. // @param _cutieId The token ID is to be put on auction. // @param _auction To add an auction. // @param _fee Amount of money to feature auction function _addAuction(uint40 _cutieId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); cutieIdToAuction[_cutieId] = _auction; emit AuctionCreated( _cutieId, _auction.startPrice, _auction.endPrice, _auction.duration, _auction.featuringFee, _auction.tokensAllowed ); } // @dev Returns true if the token is claimed by the claimant. // @param _claimant - Address claiming to own the token. function _isOwner(address _claimant, uint256 _cutieId) internal view returns (bool) { return (coreContract.ownerOf(_cutieId) == _claimant); } // @dev Transfers the token owned by this contract to another address. // Returns true when the transfer succeeds. // @param _receiver - Address to transfer token to. // @param _cutieId - Token ID to transfer. function _transfer(address _receiver, uint40 _cutieId) internal { // it will throw if transfer fails coreContract.transfer(_receiver, _cutieId); } // @dev Escrows the token and assigns ownership to this contract. // Throws if the escrow fails. // @param _owner - Current owner address of token to escrow. // @param _cutieId - Token ID the approval of which is to be verified. function _escrow(address _owner, uint40 _cutieId) internal { // it will throw if transfer fails coreContract.transferFrom(_owner, this, _cutieId); } // @dev just cancel auction. function _cancelActiveAuction(uint40 _cutieId, address _seller) internal { _removeAuction(_cutieId); _transfer(_seller, _cutieId); emit AuctionCancelled(_cutieId); } // @dev Calculates the price and transfers winnings. // Does not transfer token ownership. function _bid(uint40 _cutieId, uint128 _bidAmount) internal returns (uint128) { // Get a reference to the auction struct Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); // Check that bid > current price uint128 price = _currentPrice(auction); require(_bidAmount >= price); // Provide a reference to the seller before the auction struct is deleted. address seller = auction.seller; _removeAuction(_cutieId); // Transfer proceeds to seller (if there are any!) if (price > 0) { uint128 fee = _computeFee(price); uint128 sellerValue = price - fee; seller.transfer(sellerValue); } emit AuctionSuccessful(_cutieId, price, msg.sender); return price; } // @dev Removes from the list of open auctions. // @param _cutieId - ID of token on auction. function _removeAuction(uint40 _cutieId) internal { delete cutieIdToAuction[_cutieId]; } // @dev Returns true if the token is on auction. // @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } // @dev calculate current price of auction. // When testing, make this function public and turn on // `Current price calculation` test suite. function _computeCurrentPrice( uint128 _startPrice, uint128 _endPrice, uint40 _duration, uint40 _secondsPassed ) internal pure returns (uint128) { if (_secondsPassed >= _duration) { return _endPrice; } else { int256 totalPriceChange = int256(_endPrice) - int256(_startPrice); int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); uint128 currentPrice = _startPrice + uint128(currentPriceChange); return currentPrice; } } // @dev return current price of token. function _currentPrice(Auction storage _auction) internal view returns (uint128) { uint40 secondsPassed = 0; uint40 timeNow = uint40(now); if (timeNow > _auction.startedAt) { secondsPassed = timeNow - _auction.startedAt; } return _computeCurrentPrice( _auction.startPrice, _auction.endPrice, _auction.duration, secondsPassed ); } // @dev Calculates owner's cut of a sale. // @param _price - Sale price of cutie. function _computeFee(uint128 _price) internal view returns (uint128) { return _price * ownerFee / 10000; } // @dev Remove all Ether from the contract with the owner's cuts. Also, remove any Ether sent directly to the contract address. // Transfers to the token contract, but can be called by // the owner or the token contract. function withdrawEthFromBalance() external { address coreAddress = address(coreContract); require( msg.sender == owner || msg.sender == coreAddress ); coreAddress.transfer(address(this).balance); } // @dev create and begin new auction. function createAuction(uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller) public whenNotPaused payable { require(_isOwner(msg.sender, _cutieId)); _escrow(msg.sender, _cutieId); bool allowTokens = _duration < 0x8000000000; // first bit of duration is boolean flag (1 to disable tokens) _duration = _duration % 0x8000000000; // clear flag from duration Auction memory auction = Auction( _startPrice, _endPrice, _seller, _duration, uint40(now), uint128(msg.value), allowTokens ); _addAuction(_cutieId, auction); } // @dev Set the reference to cutie ownership contract. Verify the owner's fee. // @param fee should be between 0-10,000. function setup(address _coreContractAddress, uint16 _fee) public onlyOwner { require(_fee <= 10000); ownerFee = _fee; CutieCoreInterface candidateContract = CutieCoreInterface(_coreContractAddress); require(candidateContract.isCutieCore()); coreContract = candidateContract; } // @dev Set the owner's fee. // @param fee should be between 0-10,000. function setFee(uint16 _fee) public onlyOwner { require(_fee <= 10000); ownerFee = _fee; } // @dev bid on auction. Complete it and transfer ownership of cutie if enough ether was given. function bid(uint40 _cutieId) public payable whenNotPaused canBeStoredIn128Bits(msg.value) { // _bid throws if something failed. _bid(_cutieId, uint128(msg.value)); _transfer(msg.sender, _cutieId); } function getPriceInToken(ERC20 _tokenContract, uint128 priceWei) public view returns (uint128) { PriceOracleInterface oracle = priceOracle[address(_tokenContract)]; require(address(oracle) != address(0)); uint256 ethPerToken = oracle.ETHPrice(); return uint128(uint256(priceWei) * ethPerToken / 1 ether); } function getCutieId(bytes _extraData) internal returns (uint40) { return uint40(_extraData[0]) + uint40(_extraData[1]) * 0x100 + uint40(_extraData[2]) * 0x10000 + uint40(_extraData[3]) * 0x100000 + uint40(_extraData[4]) * 0x10000000; } // https://github.com/BitGuildPlatform/Documentation/blob/master/README.md#2-required-game-smart-contract-changes // Function that is called when trying to use PLAT for payments from approveAndCall function receiveApproval(address _sender, uint256 _value, address _tokenContract, bytes _extraData) external canBeStoredIn128Bits(_value) whenNotPaused { ERC20 tokenContract = ERC20(_tokenContract); require(_extraData.length == 5); // 40 bits uint40 cutieId = getCutieId(_extraData); // Get a reference to the auction struct Auction storage auction = cutieIdToAuction[cutieId]; require(auction.tokensAllowed); // buy for token is allowed require(_isOnAuction(auction)); uint128 priceWei = _currentPrice(auction); uint128 priceInTokens = getPriceInToken(tokenContract, priceWei); // Check that bid > current price //require(_value >= priceInTokens); // Provide a reference to the seller before the auction struct is deleted. address seller = auction.seller; _removeAuction(cutieId); // Transfer proceeds to seller (if there are any!) if (priceInTokens > 0) { uint128 fee = _computeFee(priceInTokens); uint128 sellerValue = priceInTokens - fee; require(tokenContract.transferFrom(_sender, address(this), priceInTokens)); tokenContract.transfer(seller, sellerValue); } emit AuctionSuccessfulForToken(cutieId, priceWei, _sender, priceInTokens, _tokenContract); _transfer(_sender, cutieId); } // @dev Returns auction info for a token on auction. // @param _cutieId - ID of token on auction. function getAuctionInfo(uint40 _cutieId) public view returns ( address seller, uint128 startPrice, uint128 endPrice, uint40 duration, uint40 startedAt, uint128 featuringFee, bool tokensAllowed ) { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startPrice, auction.endPrice, auction.duration, auction.startedAt, auction.featuringFee, auction.tokensAllowed ); } // @dev Returns auction info for a token on auction. // @param _cutieId - ID of token on auction. function isOnAuction(uint40 _cutieId) public view returns (bool) { return cutieIdToAuction[_cutieId].startedAt > 0; } /* /// @dev Import cuties from previous version of Core contract. /// @param _oldAddress Old core contract address /// @param _fromIndex (inclusive) /// @param _toIndex (inclusive) function migrate(address _oldAddress, uint40 _fromIndex, uint40 _toIndex) public onlyOwner whenPaused { Market old = Market(_oldAddress); for (uint40 i = _fromIndex; i <= _toIndex; i++) { if (coreContract.ownerOf(i) == _oldAddress) { address seller; uint128 startPrice; uint128 endPrice; uint40 duration; uint40 startedAt; uint128 featuringFee; (seller, startPrice, endPrice, duration, startedAt, featuringFee) = old.getAuctionInfo(i); Auction memory auction = Auction({ seller: seller, startPrice: startPrice, endPrice: endPrice, duration: duration, startedAt: startedAt, featuringFee: featuringFee }); _addAuction(i, auction); } } }*/ // @dev Returns the current price of an auction. function getCurrentPrice(uint40 _cutieId) public view returns (uint128) { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); return _currentPrice(auction); } // @dev Cancels unfinished auction and returns token to owner. // Can be called when contract is paused. function cancelActiveAuction(uint40 _cutieId) public { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelActiveAuction(_cutieId, seller); } // @dev Cancels auction when contract is on pause. Option is available only to owners in urgent situations. Tokens returned to seller. // Used on Core contract upgrade. function cancelActiveAuctionWhenPaused(uint40 _cutieId) whenPaused onlyOwner public { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); _cancelActiveAuction(_cutieId, auction.seller); } // @dev Cancels unfinished auction and returns token to owner. // Can be called when contract is paused. function cancelCreatorAuction(uint40 _cutieId) public onlyOperator { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); address seller = auction.seller; require(seller == address(coreContract)); _cancelActiveAuction(_cutieId, msg.sender); } // @dev Transfers to _withdrawToAddress all tokens controlled by // contract _tokenContract. function withdrawTokenFromBalance(ERC20 _tokenContract, address _withdrawToAddress) external { address coreAddress = address(coreContract); require( msg.sender == owner || msg.sender == operatorAddress || msg.sender == coreAddress ); uint256 balance = _tokenContract.balanceOf(address(this)); _tokenContract.transfer(_withdrawToAddress, balance); } /// @dev Allow buy cuties for token function addToken(ERC20 _tokenContract, PriceOracleInterface _priceOracle) external onlyOwner { priceOracle[address(_tokenContract)] = _priceOracle; } /// @dev Disallow buy cuties for token function removeToken(ERC20 _tokenContract) external onlyOwner { delete priceOracle[address(_tokenContract)]; } } /// @title Auction market for cuties sale /// @author https://BlockChainArchitect.io contract SaleMarket is Market { // @dev Sanity check reveals that the // auction in our setSaleAuctionAddress() call is right. bool public isSaleMarket = true; // @dev create and start a new auction // @param _cutieId - ID of cutie to auction, sender must be owner. // @param _startPrice - Price of item (in wei) at the beginning of auction. // @param _endPrice - Price of item (in wei) at the end of auction. // @param _duration - Length of auction (in seconds). // @param _seller - Seller function createAuction( uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller ) public payable { require(msg.sender == address(coreContract)); _escrow(_seller, _cutieId); bool allowTokens = _duration < 0x8000000000; // first bit of duration is boolean flag (1 to disable tokens) _duration = _duration % 0x8000000000; // clear flag from duration Auction memory auction = Auction( _startPrice, _endPrice, _seller, _duration, uint40(now), uint128(msg.value), allowTokens ); _addAuction(_cutieId, auction); } // @dev LastSalePrice is updated if seller is the token contract. // Otherwise, default bid method is used. function bid(uint40 _cutieId) public payable canBeStoredIn128Bits(msg.value) { // _bid verifies token ID size _bid(_cutieId, uint128(msg.value)); _transfer(msg.sender, _cutieId); } }
Returns auction info for a token on auction. _cutieId - ID of token on auction.
function isOnAuction(uint40 _cutieId) public view returns (bool) { return cutieIdToAuction[_cutieId].startedAt > 0; }
242,251
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 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, "Invalid 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), "Zero address"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract EyeToken is ERC20, Ownable { using SafeMath for uint256; struct Frozen { bool frozen; uint until; } string public name = "EYE Token"; string public symbol = "EYE"; uint8 public decimals = 18; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; mapping(address => Frozen) public frozenAccounts; uint256 internal totalSupplyTokens; bool internal isICO; address public wallet; function EyeToken() public Ownable() { wallet = msg.sender; isICO = true; totalSupplyTokens = 10000000000 * 10 ** uint256(decimals); balances[wallet] = totalSupplyTokens; } /** * @dev Finalize ICO */ function finalizeICO() public onlyOwner { isICO = false; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupplyTokens; } /** * @dev Freeze account, make transfers from this account unavailable * @param _account Given account */ function freeze(address _account) public onlyOwner { freeze(_account, 0); } /** * @dev Temporary freeze account, make transfers from this account unavailable for a time * @param _account Given account * @param _until Time until */ function freeze(address _account, uint _until) public onlyOwner { if (_until == 0 || (_until != 0 && _until > now)) { frozenAccounts[_account] = Frozen(true, _until); } } /** * @dev Unfreeze account, make transfers from this account available * @param _account Given account */ function unfreeze(address _account) public onlyOwner { if (frozenAccounts[_account].frozen) { delete frozenAccounts[_account]; } } /** * @dev allow transfer tokens or not * @param _from The address to transfer from. */ modifier allowTransfer(address _from) { require(!isICO, "ICO phase"); if (frozenAccounts[_from].frozen) { require(frozenAccounts[_from].until != 0 && frozenAccounts[_from].until < now, "Frozen account"); delete frozenAccounts[_from]; } _; } /** * @dev transfer tokens 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) { bool result = _transfer(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value); return result; } /** * @dev transfer tokens for a specified address in ICO mode * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transferICO(address _to, uint256 _value) public onlyOwner returns (bool) { require(isICO, "Not ICO phase"); require(_to != address(0), "Zero address 'To'"); require(_value <= balances[wallet], "Not enought balance"); balances[wallet] = balances[wallet].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(wallet, _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) { return balances[_owner]; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public allowTransfer(_from) returns (bool) { require(_value <= allowed[_from][msg.sender], "Not enought allowance"); bool result = _transfer(_from, _to, _value); if (result) { allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); } return result; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev transfer token for a specified address * @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 allowTransfer(_from) returns (bool) { require(_to != address(0), "Zero address 'To'"); require(_from != address(0), "Zero address 'From'"); require(_value <= balances[_from], "Not enought balance"); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); return true; } } /** * @title Crowd-sale * * @dev Crowd-sale contract for tokens */ contract CrowdSale is Ownable { using SafeMath for uint256; event Payment( address wallet, uint date, uint256 amountEth, uint256 amountCoin, uint8 bonusPercent ); uint constant internal MIN_TOKEN_AMOUNT = 5000; uint constant internal SECONDS_IN_DAY = 86400; // 24 * 60 * 60 uint constant internal SECONDS_IN_YEAR = 31557600; // ( 365 * 24 + 6 ) * 60 * 60 int8 constant internal PHASE_NOT_STARTED = -5; int8 constant internal PHASE_BEFORE_PRESALE = -4; int8 constant internal PHASE_BETWEEN_PRESALE_ICO = -3; int8 constant internal PHASE_ICO_FINISHED = -2; int8 constant internal PHASE_FINISHED = -1; int8 constant internal PHASE_PRESALE = 0; int8 constant internal PHASE_ICO_1 = 1; int8 constant internal PHASE_ICO_2 = 2; int8 constant internal PHASE_ICO_3 = 3; int8 constant internal PHASE_ICO_4 = 4; int8 constant internal PHASE_ICO_5 = 5; address internal manager; EyeToken internal token; address internal base_wallet; uint256 internal dec_mul; address internal vest_1; address internal vest_2; address internal vest_3; address internal vest_4; int8 internal phase_i; // see PHASE_XXX uint internal presale_start = 1533020400; // 2018-07-31 07:00 UTC uint internal presale_end = 1534316400; // 2018-08-15 07:00 UTC uint internal ico_start = 1537254000; // 2018-09-18 07:00 UTC uint internal ico_phase_1_days = 7; uint internal ico_phase_2_days = 7; uint internal ico_phase_3_days = 7; uint internal ico_phase_4_days = 7; uint internal ico_phase_5_days = 7; uint internal ico_phase_1_end; uint internal ico_phase_2_end; uint internal ico_phase_3_end; uint internal ico_phase_4_end; uint internal ico_phase_5_end; uint8[6] public bonus_percents = [50, 40, 30, 20, 10, 0]; uint internal finish_date; uint public exchange_rate; // tokens in one ethereum * 1000 uint256 public lastPayerOverflow = 0; /** * @dev Crowd-sale constructor */ function CrowdSale() Ownable() public { phase_i = PHASE_NOT_STARTED; manager = address(0); } /** * @dev Allow only for owner or manager */ modifier onlyOwnerOrManager(){ require(msg.sender == owner || (msg.sender == manager && manager != address(0)), "Invalid owner or manager"); _; } /** * @dev Returns current manager */ function getManager() public view onlyOwnerOrManager returns (address) { return manager; } /** * @dev Sets new manager * @param _manager New manager */ function setManager(address _manager) public onlyOwner { manager = _manager; } /** * @dev Set exchange rate * @param _rate New exchange rate * * executed by CRM */ function setRate(uint _rate) public onlyOwnerOrManager { require(_rate > 0, "Invalid exchange rate"); exchange_rate = _rate; } function _addPayment(address wallet, uint256 amountEth, uint256 amountCoin, uint8 bonusPercent) internal { emit Payment(wallet, now, amountEth, amountCoin, bonusPercent); } /** * @dev Start crowd-sale * @param _token Coin's contract * @param _rate current exchange rate */ function start(address _token, uint256 _rate) public onlyOwnerOrManager { require(_rate > 0, "Invalid exchange rate"); require(phase_i == PHASE_NOT_STARTED, "Bad phase"); token = EyeToken(_token); base_wallet = token.wallet(); dec_mul = 10 ** uint256(token.decimals()); // Organizasional expenses address org_exp = 0xeb967ECF00e86F58F6EB8019d003c48186679A96; // Early birds address ear_brd = 0x469A97b357C2056B927fF4CA097513BD927db99E; // Community development address com_dev = 0x877D6a4865478f50219a20870Bdd16E6f7aa954F; // Special coins address special = 0x5D2C58e6aCC5BcC1aaA9b54B007e0c9c3E091adE; // Team lock vest_1 = 0x47997109aE9bEd21efbBBA362957F1b20F435BF3; vest_2 = 0xd031B38d0520aa10450046Dc0328447C3FF59147; vest_3 = 0x32FcE00BfE1fEC48A45DC543224748f280a5c69E; vest_4 = 0x07B489712235197736E207836f3B71ffaC6b1220; token.transferICO(org_exp, 600000000 * dec_mul); token.transferICO(ear_brd, 1000000000 * dec_mul); token.transferICO(com_dev, 1000000000 * dec_mul); token.transferICO(special, 800000000 * dec_mul); token.transferICO(vest_1, 500000000 * dec_mul); token.transferICO(vest_2, 500000000 * dec_mul); token.transferICO(vest_3, 500000000 * dec_mul); token.transferICO(vest_4, 500000000 * dec_mul); exchange_rate = _rate; phase_i = PHASE_BEFORE_PRESALE; _updatePhaseTimes(); } /** * @dev Finalize ICO */ function _finalizeICO() internal { require(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED, "Bad phase"); phase_i = PHASE_ICO_FINISHED; uint curr_date = now; finish_date = (curr_date < ico_phase_5_end ? ico_phase_5_end : curr_date).add(SECONDS_IN_DAY * 10); } /** * @dev Finalize crowd-sale */ function _finalize() internal { require(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED, "Bad phase"); uint date = now.add(SECONDS_IN_YEAR); token.freeze(vest_1, date); date = date.add(SECONDS_IN_YEAR); token.freeze(vest_2, date); date = date.add(SECONDS_IN_YEAR); token.freeze(vest_3, date); date = date.add(SECONDS_IN_YEAR); token.freeze(vest_4, date); token.finalizeICO(); token.transferOwnership(base_wallet); phase_i = PHASE_FINISHED; } /** * @dev Finalize crowd-sale */ function finalize() public onlyOwner { _finalize(); } function _calcPhase() internal view returns (int8) { if (phase_i == PHASE_FINISHED || phase_i == PHASE_NOT_STARTED) return phase_i; uint curr_date = now; if (curr_date >= ico_phase_5_end || token.balanceOf(base_wallet) == 0) return PHASE_ICO_FINISHED; if (curr_date < presale_start) return PHASE_BEFORE_PRESALE; if (curr_date <= presale_end) return PHASE_PRESALE; if (curr_date < ico_start) return PHASE_BETWEEN_PRESALE_ICO; if (curr_date < ico_phase_1_end) return PHASE_ICO_1; if (curr_date < ico_phase_2_end) return PHASE_ICO_2; if (curr_date < ico_phase_3_end) return PHASE_ICO_3; if (curr_date < ico_phase_4_end) return PHASE_ICO_4; return PHASE_ICO_5; } function phase() public view returns (int8) { return _calcPhase(); } /** * @dev Recalculate phase */ function _updatePhase(bool check_can_sale) internal { uint curr_date = now; if (phase_i == PHASE_ICO_FINISHED) { if (curr_date >= finish_date) _finalize(); } else if (phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED) { int8 new_phase = _calcPhase(); if (new_phase == PHASE_ICO_FINISHED && phase_i != PHASE_ICO_FINISHED) _finalizeICO(); else phase_i = new_phase; } if (check_can_sale) require(phase_i >= 0, "Bad phase"); } /** * @dev Update phase end times */ function _updatePhaseTimes() internal { require(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED, "Bad phase"); if (phase_i < PHASE_ICO_1) ico_phase_1_end = ico_start.add(SECONDS_IN_DAY.mul(ico_phase_1_days)); if (phase_i < PHASE_ICO_2) ico_phase_2_end = ico_phase_1_end.add(SECONDS_IN_DAY.mul(ico_phase_2_days)); if (phase_i < PHASE_ICO_3) ico_phase_3_end = ico_phase_2_end.add(SECONDS_IN_DAY.mul(ico_phase_3_days)); if (phase_i < PHASE_ICO_4) ico_phase_4_end = ico_phase_3_end.add(SECONDS_IN_DAY.mul(ico_phase_4_days)); if (phase_i < PHASE_ICO_5) ico_phase_5_end = ico_phase_4_end.add(SECONDS_IN_DAY.mul(ico_phase_5_days)); if (phase_i != PHASE_ICO_FINISHED) finish_date = ico_phase_5_end.add(SECONDS_IN_DAY.mul(10)); _updatePhase(false); } /** * @dev Send tokens to the specified address * * @param _to Address sent to * @param _amount_coin Amount of tockens * @return excess coins * * executed by CRM */ function transferICO(address _to, uint256 _amount_coin) public onlyOwnerOrManager { _updatePhase(true); uint256 remainedCoin = token.balanceOf(base_wallet); require(remainedCoin >= _amount_coin, "Not enough coins"); token.transferICO(_to, _amount_coin); if (remainedCoin == _amount_coin) _finalizeICO(); } /** * @dev Default contract function. Buy tokens by sending ethereums */ function() public payable { _updatePhase(true); address sender = msg.sender; uint256 amountEth = msg.value; uint256 remainedCoin = token.balanceOf(base_wallet); if (remainedCoin == 0) { sender.transfer(amountEth); _finalizeICO(); } else { uint8 percent = bonus_percents[uint256(phase_i)]; uint256 amountCoin = calcTokensFromEth(amountEth); assert(amountCoin >= MIN_TOKEN_AMOUNT); if (amountCoin > remainedCoin) { lastPayerOverflow = amountCoin.sub(remainedCoin); amountCoin = remainedCoin; } base_wallet.transfer(amountEth); token.transferICO(sender, amountCoin); _addPayment(sender, amountEth, amountCoin, percent); if (amountCoin == remainedCoin) _finalizeICO(); } } function calcTokensFromEth(uint256 ethAmount) internal view returns (uint256) { uint8 percent = bonus_percents[uint256(phase_i)]; uint256 bonusRate = uint256(percent).add(100); uint256 totalCoins = ethAmount.mul(exchange_rate).div(1000); uint256 totalFullCoins = (totalCoins.add(dec_mul.div(2))).div(dec_mul); uint256 tokensWithBonusX100 = bonusRate.mul(totalFullCoins); uint256 fullCoins = (tokensWithBonusX100.add(50)).div(100); return fullCoins.mul(dec_mul); } /** * @dev Freeze the account * @param _accounts Given accounts * * executed by CRM */ function freeze(address[] _accounts) public onlyOwnerOrManager { require(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED, "Bad phase"); uint i; for (i = 0; i < _accounts.length; i++) { require(_accounts[i] != address(0), "Zero address"); require(_accounts[i] != base_wallet, "Freeze self"); } for (i = 0; i < _accounts.length; i++) { token.freeze(_accounts[i]); } } /** * @dev Unfreeze the account * @param _accounts Given accounts */ function unfreeze(address[] _accounts) public onlyOwnerOrManager { require(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED, "Bad phase"); uint i; for (i = 0; i < _accounts.length; i++) { require(_accounts[i] != address(0), "Zero address"); require(_accounts[i] != base_wallet, "Freeze self"); } for (i = 0; i < _accounts.length; i++) { token.unfreeze(_accounts[i]); } } /** * @dev get ICO times * @return presale_start, presale_end, ico_start, ico_phase_1_end, ico_phase_2_end, ico_phase_3_end, ico_phase_4_end, ico_phase_5_end */ function getTimes() public view returns (uint, uint, uint, uint, uint, uint, uint, uint) { return (presale_start, presale_end, ico_start, ico_phase_1_end, ico_phase_2_end, ico_phase_3_end, ico_phase_4_end, ico_phase_5_end); } /** * @dev Sets start and end dates for pre-sale phase_i * @param _presale_start Pre-sale sart date * @param _presale_end Pre-sale end date */ function setPresaleDates(uint _presale_start, uint _presale_end) public onlyOwnerOrManager { _updatePhase(false); require(phase_i == PHASE_BEFORE_PRESALE, "Bad phase"); // require(_presale_start >= now); require(_presale_start < _presale_end, "Invalid presale dates"); require(_presale_end < ico_start, "Invalid dates"); presale_start = _presale_start; presale_end = _presale_end; } /** * @dev Sets start date for ICO phases * @param _ico_start ICO start date * @param _ico_1_days Days of ICO phase 1 * @param _ico_2_days Days of ICO phase 2 * @param _ico_3_days Days of ICO phase 3 * @param _ico_4_days Days of ICO phase 4 * @param _ico_5_days Days of ICO phase 5 */ function setICODates(uint _ico_start, uint _ico_1_days, uint _ico_2_days, uint _ico_3_days, uint _ico_4_days, uint _ico_5_days) public onlyOwnerOrManager { _updatePhase(false); require(phase_i != PHASE_FINISHED && phase_i != PHASE_ICO_FINISHED && phase_i < PHASE_ICO_1, "Bad phase"); require(presale_end < _ico_start, "Invalid dates"); ico_start = _ico_start; ico_phase_1_days = _ico_1_days; ico_phase_2_days = _ico_2_days; ico_phase_3_days = _ico_3_days; ico_phase_4_days = _ico_4_days; ico_phase_5_days = _ico_5_days; _updatePhaseTimes(); } }
get ICO times return presale_start, presale_end, ico_start, ico_phase_1_end, ico_phase_2_end, ico_phase_3_end, ico_phase_4_end, ico_phase_5_end/
function getTimes() public view returns (uint, uint, uint, uint, uint, uint, uint, uint) { return (presale_start, presale_end, ico_start, ico_phase_1_end, ico_phase_2_end, ico_phase_3_end, ico_phase_4_end, ico_phase_5_end); }
5,403,640
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import "../ActionBase.sol"; import "../../core/Subscriptions.sol"; import "../../DS/DSMath.sol"; import "../../interfaces/IFLParamGetter.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/aaveV2/ILendingPoolAddressesProviderV2.sol"; import "../../interfaces/aaveV2/ILendingPoolV2.sol"; import "../../core/StrategyData.sol"; import "../../utils/TokenUtils.sol"; import "../../utils/ReentrancyGuard.sol"; import "./helpers/FLHelper.sol"; /// @title Action that gets and receives a FL from Aave V2 contract FLAaveV2 is ActionBase, StrategyData, DSMath, ReentrancyGuard, FLHelper { using SafeERC20 for IERC20; using TokenUtils for address; string constant ERR_ONLY_AAVE_CALLER = "Caller not aave pool"; string constant ERR_SAME_CALLER = "FL taker must be this contract"; string constant ERR_WRONG_PAYBACK_AMOUNT = "Wrong FL payback amount sent"; ILendingPoolAddressesProviderV2 public constant addressesProvider = ILendingPoolAddressesProviderV2( AAVE_LENDING_POOL_ADDRESS_PROVIDER ); uint16 public constant AAVE_REFERRAL_CODE = 64; /// @dev Function sig of TaskExecutor._executeActionsFromFL() bytes4 public constant CALLBACK_SELECTOR = 0xd6741b9e; bytes32 constant TASK_EXECUTOR_ID = keccak256("TaskExecutor"); struct FLAaveV2Data { address[] tokens; uint256[] amounts; uint256[] modes; address onBehalfOf; address flParamGetterAddr; bytes flParamGetterData; } /// @inheritdoc ActionBase function executeAction( bytes[] memory _callData, bytes[] memory, uint8[] memory, bytes32[] memory ) public override payable returns (bytes32) { FLAaveV2Data memory flData = parseInputs(_callData); // if we want to get on chain info about FL params if (flData.flParamGetterAddr != address(0)) { (flData.tokens, flData.amounts, flData.modes) = IFLParamGetter(flData.flParamGetterAddr).getFlashLoanParams(flData.flParamGetterData); } bytes memory taskData = _callData[_callData.length - 1]; uint flAmount = _flAaveV2(flData, taskData); return bytes32(flAmount); } // solhint-disable-next-line no-empty-blocks function executeActionDirect(bytes[] memory _callData) public override payable {} /// @inheritdoc ActionBase function actionType() public override pure returns (uint8) { return uint8(ActionType.FL_ACTION); } //////////////////////////// ACTION LOGIC //////////////////////////// /// @notice Gets a Fl from AaveV2 and returns back the execution to the action address /// @param _flData All the amounts/tokens and related aave fl data /// @param _params Rest of the data we have in the task function _flAaveV2(FLAaveV2Data memory _flData, bytes memory _params) internal returns (uint) { ILendingPoolV2(AAVE_LENDING_POOL).flashLoan( address(this), _flData.tokens, _flData.amounts, _flData.modes, _flData.onBehalfOf, _params, AAVE_REFERRAL_CODE ); logger.Log( address(this), msg.sender, "FLAaveV2", abi.encode(_flData.tokens, _flData.amounts, _flData.modes, _flData.onBehalfOf) ); return _flData.amounts[0]; } /// @notice Aave callback function that formats and calls back TaskExecutor function executeOperation( address[] memory _assets, uint256[] memory _amounts, uint256[] memory _fees, address _initiator, bytes memory _params ) public nonReentrant returns (bool) { require(msg.sender == AAVE_LENDING_POOL, ERR_ONLY_AAVE_CALLER); require(_initiator == address(this), ERR_SAME_CALLER); (Task memory currTask, address proxy) = abi.decode(_params, (Task, address)); // Send FL amounts to user proxy for (uint256 i = 0; i < _assets.length; ++i) { _assets[i].withdrawTokens(proxy, _amounts[i]); } address payable taskExecutor = payable(registry.getAddr(TASK_EXECUTOR_ID)); // call Action execution IDSProxy(proxy).execute{value: address(this).balance}( taskExecutor, abi.encodeWithSelector(CALLBACK_SELECTOR, currTask, bytes32(add(_amounts[0],_fees[0]))) ); // return FL for (uint256 i = 0; i < _assets.length; i++) { uint256 paybackAmount = add(_amounts[i],_fees[i]); require(_assets[i].getBalance(address(this)) == paybackAmount, ERR_WRONG_PAYBACK_AMOUNT); _assets[i].approveToken(address(AAVE_LENDING_POOL), paybackAmount); } return true; } function parseInputs(bytes[] memory _callData) public pure returns (FLAaveV2Data memory flData) { flData.amounts = abi.decode(_callData[0], (uint256[])); flData.tokens = abi.decode(_callData[1], (address[])); flData.modes = abi.decode(_callData[2], (uint256[])); flData.onBehalfOf = abi.decode(_callData[3], (address)); flData.flParamGetterAddr = abi.decode(_callData[4], (address)); flData.flParamGetterData = abi.decode(_callData[5], (bytes)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} }
Gets a Fl from AaveV2 and returns back the execution to the action address _flData All the amounts/tokens and related aave fl data _params Rest of the data we have in the task
function _flAaveV2(FLAaveV2Data memory _flData, bytes memory _params) internal returns (uint) { ILendingPoolV2(AAVE_LENDING_POOL).flashLoan( address(this), _flData.tokens, _flData.amounts, _flData.modes, _flData.onBehalfOf, _params, AAVE_REFERRAL_CODE ); logger.Log( address(this), msg.sender, "FLAaveV2", abi.encode(_flData.tokens, _flData.amounts, _flData.modes, _flData.onBehalfOf) ); return _flData.amounts[0]; }
5,376,435
./partial_match/3/0x035a00260f2D7B7c852a6A2aF5B9f952D0b20662/sources/Faucet.sol
POLY XEENUS YEENUS ZEENUS WEENUS _fauceteer(0xE4C6182EA459E63B8F1be7c428381994CcC2D49c); _fauceteer(0x0D9C8723B343A8368BebE0B5E89273fF8D712e3C); _fauceteer(0x6FD34013CDD2905d8d27b0aDaD5b97B2345cF2B8); _fauceteer(0x443Fd8D5766169416aE42B8E050fE9422f628419); _fauceteer(0xb19c7BFc9a7CbE4C35189d475725557A96bFb50A); _fauceteer(0x1Fe16De955718CFAb7A44605458AB023838C2793); _fauceteer(0xc2118d4d90b274016cB7a54c03EF52E6c537D957); _fauceteer(0xF0A6664A0A8E95696BffB121A4fb0B1fC8C93d9E); _fauceteer(0x26fF7457496600C63b3E8902C9f871E60eDec4e4); _fauceteer(0x71d82Eb6A5051CfF99582F4CDf2aE9cD402A4882); _fauceteer(0xBde8bB00A7eF67007A96945B3a3621177B615C44); BAT COMP DAI KNC LINK REP SAI UNI USDC USDT 0x516de3a7A567d81737e3a46ec4FF9cFD1fcb0136 WBTC ZRX
function drip() public { IPolyFaucet(0x96A62428509002a7aE5F6AD29E4750d852A3f3D7).getTokens(5000 * 1e18); _dump(0x96A62428509002a7aE5F6AD29E4750d852A3f3D7); IBokky(0x7E0480Ca9fD50EB7A3855Cf53c347A1b4d6A2FF5).drip(); _dump(0x7E0480Ca9fD50EB7A3855Cf53c347A1b4d6A2FF5); IBokky(0xF6fF95D53E08c9660dC7820fD5A775484f77183A).drip(); _dump(0xF6fF95D53E08c9660dC7820fD5A775484f77183A); IBokky(0xC84f8B669Ccb91C86AB2b38060362b9956f2De52).drip(); _dump(0xC84f8B669Ccb91C86AB2b38060362b9956f2De52); IBokky(0x101848D5C5bBca18E6b4431eEdF6B95E9ADF82FA).drip(); _dump(0x101848D5C5bBca18E6b4431eEdF6B95E9ADF82FA); _fauceteer(0x516de3a7A567d81737e3a46ec4FF9cFD1fcb0136); IERC20 sushi = IERC20(0xf095b8Fd7845a0631FcE1A7FAf05F6ED56Ade87c); sushi.transfer(msg.sender, sushi.balanceOf(address(this)) / 1000); }
5,210,212
./partial_match/1/0x4c28B5d2cAd6881C35A6E22657812Cda9b032d0C/sources/AIPEPE.sol
once enabled, can never be turned off
function enableTrading() external onlyOwner { tradingLive = true; swapEnabled = true; launchedAt = block.number; }
4,198,833
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; //import 'hardhat/console.sol'; import '@openzeppelin/contracts/access/AccessControl.sol'; import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import './IPool.sol'; import './ICorePool.sol'; import './ModaConstants.sol'; import './EscrowedModaERC20.sol'; import './ModaPoolFactory.sol'; /** * @title Moda Pool Base * * @notice An abstract contract containing common logic for any MODA pool, * be it core pool (permanent pool like MODA/ETH or MODA core pool) or something else. * * @dev Deployment and initialization. * Any pool deployed must have 3 token instance addresses defined on deployment: * - MODA token address * - sMODA token address, used to mint sMODA rewards * - pool token address, it can be MODA token address, MODA/ETH pair address, and others */ abstract contract ModaPoolBase is IPool, ModaAware, ModaPoolFactory, ReentrancyGuard, AccessControl { // @dev POOL_UID defined to add another check to ensure compliance with the contract. function POOL_UID() public pure returns (uint256) { return ModaConstants.POOL_UID; } // @dev modaPool MODA ERC20 Liquidity Pool contract address. // @dev This value is address(0) for the default MODA Core Pool. // @dev This value MUST be provided for any pool created which is not a MODA pool. // @dev This is used in the case where poolToken != moda. // The use case relates to shadowing Liquidity Pool stakes // by allowing people to store the LP tokens here to gain // further MODA/sMODA rewards. I'm not sure it's both. (dex 2021.09.16) address modaPool; /// @dev Data structure representing token holder using a pool struct User { // @dev Total staked amount uint256 tokenAmount; // @dev Total weight uint256 totalWeight; // @dev Auxiliary variable for yield calculation uint256 subYieldRewards; // @dev Auxiliary variable for vault rewards calculation uint256 subVaultRewards; // @dev An array of holder's deposits Deposit[] deposits; } /// @dev Token holder storage, maps token holder address to their data record mapping(address => User) public users; /// @dev Link to sMODA ERC20 Token EscrowedModaERC20 instance address public immutable override smoda; /// @dev Link to the pool token instance, for example MODA or MODA/ETH pair address public immutable override poolToken; /// @dev Pool weight, 100 for MODA pool or 900 for MODA/ETH uint32 public override weight; /// @dev Block number of the last yield distribution event /// This gets initialised at the first rewards pass after rewardStartTime. uint256 public override lastYieldDistribution; /// @dev Used to calculate yield rewards, keeps track of the tokens weight locked in staking uint256 public override usersLockingWeight; /** * @dev Stake weight is proportional to deposit amount and time locked, precisely * "deposit amount wei multiplied by (fraction of the year locked plus one)" * @dev To avoid significant precision loss due to multiplication by "fraction of the year" [0, 1], * weight is stored multiplied by 1e6 constant, as an integer * @dev Corner case 1: if time locked is zero, weight is deposit amount multiplied by 1e6 * @dev Corner case 2: if time locked is one year, fraction of the year locked is one, and * weight is a deposit amount multiplied by 2 * 1e6 */ uint256 internal constant WEIGHT_MULTIPLIER = 1e6; /// @dev Used to calculate yield rewards /// @dev This value is different from "reward per token" used in locked pool /// @dev Note: stakes are different in duration and "weight" reflects that uint256 public override yieldRewardsPerWeight; /** * @dev When we know beforehand that staking is done for a year, and fraction of the year locked is one, * we use simplified calculation and use the following constant instead previos one */ uint256 internal constant YEAR_STAKE_WEIGHT_MULTIPLIER = 2 * WEIGHT_MULTIPLIER; /** * @dev Rewards per weight are stored multiplied by 1e12, as integers. */ uint256 internal constant REWARD_PER_WEIGHT_MULTIPLIER = 1e12; /** * @dev Fired in _stake() and stake() * * @param _by an address which performed an operation, usually token holder * @param _from token holder address, the tokens will be returned to that address * @param amount amount of tokens staked */ event Staked(address indexed _by, address indexed _from, uint256 amount); /** * @dev Fired in _updateStakeLock() and updateStakeLock() * * @param _by an address which performed an operation * @param depositId updated deposit ID * @param lockedFrom deposit locked from value * @param lockedUntil updated deposit locked until value */ event StakeLockUpdated( address indexed _by, uint256 depositId, uint256 lockedFrom, uint256 lockedUntil ); /** * @dev Fired in _unstake() and unstake() * * @param _by an address which performed an operation, usually token holder * @param _to an address which received the unstaked tokens, usually token holder * @param amount amount of tokens unstaked */ event Unstaked(address indexed _by, address indexed _to, uint256 amount); /** * @dev Fired in _sync(), sync() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param yieldRewardsPerWeight updated yield rewards per weight value * @param lastYieldDistribution usually, current block number */ event Synchronized( address indexed _by, uint256 yieldRewardsPerWeight, uint256 lastYieldDistribution ); /** * @dev Fired in _processRewards(), processRewards() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param _to an address which claimed the yield reward * @param sModa flag indicating if reward was paid (minted) in sMODA * @param amount amount of yield paid */ event YieldClaimed(address indexed _by, address indexed _to, bool sModa, uint256 amount); /** * @dev Fired in setWeight() * * @param _by an address which performed an operation, always a factory * @param _fromVal old pool weight value * @param _toVal new pool weight value */ event PoolWeightUpdated(address indexed _by, uint32 _fromVal, uint32 _toVal); /** * @dev Overridden in sub-contracts to construct the pool * * @param _moda MODA ERC20 Token ModaERC20 address * @param _modaPool MODA ERC20 Liquidity Pool contract address * @param _smoda sMODA ERC20 Token EscrowedModaERC20 address * @param _poolToken token the pool operates on, for example MODA or MODA/ETH pair * @param _initBlock initial block used to calculate the rewards * note: _initBlock can be set to the future effectively meaning _sync() calls will do nothing * @param _weight number representing a weight of the pool, actual weight fraction * is calculated as that number divided by the total pools weight and doesn't exceed one * @param _modaPerBlock initial MODA/block value for rewards * @param _blocksPerUpdate how frequently the rewards gets updated (decreased by 3%), blocks * @param _endBlock block number when farming stops and rewards cannot be updated anymore */ constructor( address _moda, address _modaPool, address _smoda, address _poolToken, uint32 _weight, uint256 _modaPerBlock, uint256 _blocksPerUpdate, uint256 _initBlock, uint256 _endBlock ) ModaPoolFactory(_moda, _modaPerBlock, _blocksPerUpdate, _initBlock, _endBlock) { // verify the inputs are set require(_smoda != address(0), 'sMODA address not set'); require(_poolToken != address(0), 'pool token address not set'); require(_initBlock >= block.number, 'init block not set'); require(_weight > 0, 'pool weight not set'); require( ((_poolToken == _moda ? 1 : 0) ^ (_modaPool != address(0) ? 1 : 0)) == 1, 'The pool is either a MODA pool or manages external tokens, never both' ); // verify MODA instance supplied require(Token(_moda).TOKEN_UID() == ModaConstants.TOKEN_UID, 'MODA TOKEN_UID invalid'); // verify sMODA instance supplied require( EscrowedModaERC20(_smoda).ESCROWTOKEN_UID() == ModaConstants.ESCROWTOKEN_UID, 'sMODA ESCROWTOKEN_UID invalid' ); if (_modaPool != address(0)) { require(ModaPoolBase(_modaPool).POOL_UID() == ModaConstants.POOL_UID); } // save the inputs into internal state variables modaPool = _modaPool; smoda = _smoda; poolToken = _poolToken; _setWeight(_weight); // init the dependent internal state variables lastYieldDistribution = _initBlock; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setRoleAdmin(ModaConstants.ROLE_TOKEN_CREATOR, DEFAULT_ADMIN_ROLE); grantRole(ModaConstants.ROLE_TOKEN_CREATOR, _msgSender()); } /** * @dev Granting privileges required for allowing ModaCorePool and whatever else later, * the ability to mint Tokens as required. */ function grantPrivilege(bytes32 _role, address _account) public onlyOwner { grantRole(_role, _account); } /** * @notice Calculates current yield rewards value available for address specified * * @param _staker an address to calculate yield rewards value for * @return calculated yield reward value for the given address */ function pendingYieldRewards(address _staker) external view override returns (uint256) { // `newYieldRewardsPerWeight` will store stored a recalculated value for `yieldRewardsPerWeight` uint256 newYieldRewardsPerWeight; // if smart contract state was not updated recently, `yieldRewardsPerWeight` value // is outdated and we need to recalculate it in order to calculate pending rewards correctly if (block.number > lastYieldDistribution && usersLockingWeight != 0) { uint256 endBlock = endBlock; uint256 multiplier = block.number > endBlock ? endBlock - lastYieldDistribution : block.number - lastYieldDistribution; uint256 modaRewards = (multiplier * weight * modaPerBlock) / totalWeight; // recalculated value for `yieldRewardsPerWeight` newYieldRewardsPerWeight = rewardToWeight(modaRewards, usersLockingWeight) + yieldRewardsPerWeight; } else { // if smart contract state is up to date, we don't recalculate newYieldRewardsPerWeight = yieldRewardsPerWeight; } // based on the rewards per weight value, calculate pending rewards; User memory user = users[_staker]; uint256 pending = weightToReward(user.totalWeight, newYieldRewardsPerWeight) - user.subYieldRewards; return pending; } /** * @notice Returns total staked token balance for the given address * * @param _user an address to query balance for * @return total staked token balance */ function balanceOf(address _user) external view override returns (uint256) { // read specified user token amount and return return users[_user].tokenAmount; } /** * @notice Returns information on the given deposit for the given address * * @dev See getDepositsLength * * @param _user an address to query deposit for * @param _depositId zero-indexed deposit ID for the address specified * @return deposit info as Deposit structure */ function getDeposit(address _user, uint256 _depositId) external view override returns (Deposit memory) { // read deposit at specified index and return return users[_user].deposits[_depositId]; } /** * @notice Returns number of deposits for the given address. Allows iteration over deposits. * * @dev See getDeposit * * @param _user an address to query deposit length for * @return number of deposits for the given address */ function getDepositsLength(address _user) external view override returns (uint256) { // read deposits array length and return return users[_user].deposits.length; } /** * @notice Stakes specified amount of tokens for the specified amount of time, * and pays pending yield rewards if any * * @dev Requires amount to stake to be greater than zero * * @param _amount amount of tokens to stake * @param _lockUntil stake period as unix timestamp; zero means no locking * @param _useSMODA a flag indicating if previous reward to be paid as sMODA */ function stake( uint256 _amount, uint256 _lockUntil, bool _useSMODA ) external override { // delegate call to an internal function _stake(msg.sender, _amount, _lockUntil, _useSMODA, false); } /** * @notice Unstakes specified amount of tokens, and pays pending yield rewards if any * * @dev Requires amount to unstake to be greater than zero * * @param _depositId deposit ID to unstake from, zero-indexed * @param _amount amount of tokens to unstake * @param _useSMODA a flag indicating if reward to be paid as sMODA */ function unstake( uint256 _depositId, uint256 _amount, bool _useSMODA ) external override { // delegate call to an internal function //console.log('ModaPoolBase unstake', _msgSender()); _unstake(msg.sender, _depositId, _amount, _useSMODA); } /** * @notice Extends locking period for a given deposit * * @dev Requires new lockedUntil value to be: * higher than the current one, and * in the future, but * no more than 1 year in the future * * @param depositId updated deposit ID * @param lockedUntil updated deposit locked until value * @param useSMODA used for _processRewards check if it should use MODA or sMODA */ function updateStakeLock( uint256 depositId, uint256 lockedUntil, bool useSMODA ) external { // sync and call processRewards _sync(); _processRewards(msg.sender, useSMODA, false); // delegate call to an internal function _updateStakeLock(msg.sender, depositId, lockedUntil); } /** * @notice Service function to synchronize pool state with current time * * @dev Can be executed by anyone at any time, but has an effect only when * at least one block passes between synchronizations * @dev Executed internally when staking, unstaking, processing rewards in order * for calculations to be correct and to reflect state progress of the contract * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently */ function sync() external override { // delegate call to an internal function _sync(); } /** * @notice Service function to calculate and pay pending yield rewards to the sender * * @dev Can be executed by anyone at any time, but has an effect only when * executed by deposit holder and when at least one block passes from the * previous reward processing * @dev When timing conditions are not met (executed too frequently, or after * end block), function doesn't throw and exits silently * * @param _useSMODA flag indicating whether to mint sMODA token as a reward or not; * when set to true - sMODA reward is minted immediately and sent to sender, * when set to false - new MODA reward deposit gets created if pool is an MODA pool * (poolToken is MODA token), or new pool deposit gets created together with sMODA minted * when pool is not an MODA pool (poolToken is not an MODA token) */ function processRewards(bool _useSMODA) external virtual override { // delegate call to an internal function _processRewards(msg.sender, _useSMODA, true); } /** * @dev Executed by the factory to modify pool weight; the factory is expected * to keep track of the total pools weight when updating * * @dev Set weight to zero to disable the pool * * @param _weight new weight to set for the pool */ function setWeight(uint32 _weight) external override onlyOwner { _setWeight(_weight); } /** * @dev Executed by the factory to modify pool weight; the factory is expected * to keep track of the total pools weight when updating * * @dev Set weight to zero to disable the pool * * @param _weight new weight to set for the pool */ function _setWeight(uint32 _weight) internal onlyOwner { ///TODO: this could be more efficient. // order of operations is important here. _changePoolWeight(_weight); // set the new weight value weight = _weight; // emit an event logging old and new weight values emit PoolWeightUpdated(msg.sender, weight, _weight); } /** * @dev Similar to public pendingYieldRewards, but performs calculations based on * current smart contract state only, not taking into account any additional * time/blocks which might have passed * * @param _staker an address to calculate yield rewards value for * @return pending calculated yield reward value for the given address */ function _pendingYieldRewards(address _staker) internal view returns (uint256 pending) { // read user data structure into memory User memory user = users[_staker]; // and perform the calculation using the values read return weightToReward(user.totalWeight, yieldRewardsPerWeight) - user.subYieldRewards; } /** * @dev Used internally, mostly by children implementations, see stake() * * @param _staker an address which stakes tokens and which will receive them back * @param _amount amount of tokens to stake * @param _lockUntil stake period as unix timestamp; zero means no locking * @param _useSMODA a flag indicating if previous reward to be paid as sMODA * @param _isYield a flag indicating if that stake is created to store yield reward * from the previously unstaked stake */ function _stake( address _staker, uint256 _amount, uint256 _lockUntil, bool _useSMODA, bool _isYield ) internal virtual { // validate the inputs // console.log('lockUntil', _lockUntil); // console.log('timestamp', block.timestamp); require(_amount > 0, 'zero amount'); require( _lockUntil == 0 || (_lockUntil > block.timestamp && _lockUntil - block.timestamp <= 365 days), 'invalid lock interval' ); // update smart contract state _sync(); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // process current pending rewards if any if (user.tokenAmount > 0) { _processRewards(_staker, _useSMODA, false); } // in most of the cases added amount `addedAmount` is simply `_amount` // however for deflationary tokens this can be different // read the current balance uint256 previousBalance = IERC20(poolToken).balanceOf(address(this)); // transfer `_amount`; note: some tokens may get burnt here transferPoolTokenFrom(address(msg.sender), address(this), _amount); // read new balance, usually this is just the difference `previousBalance - _amount` uint256 newBalance = IERC20(poolToken).balanceOf(address(this)); // calculate real amount taking into account deflation uint256 addedAmount = newBalance - previousBalance; // set the `lockFrom` and `lockUntil` taking into account that // zero value for `_lockUntil` means "no locking" and leads to zero values // for both `lockFrom` and `lockUntil` uint256 lockFrom = _lockUntil > 0 ? block.timestamp : 0; uint256 lockUntil = _lockUntil; // stake weight formula rewards for locking uint256 stakeWeight = (((lockUntil - lockFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * addedAmount; // makes sure stakeWeight is valid assert(stakeWeight > 0); // create and save the deposit (append it to deposits array) Deposit memory deposit = Deposit({ tokenAmount: addedAmount, weight: stakeWeight, lockedFrom: lockFrom, lockedUntil: lockUntil, isYield: _isYield }); // deposit ID is an index of the deposit in `deposits` array user.deposits.push(deposit); // update user record user.tokenAmount += addedAmount; user.totalWeight += stakeWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); // update global variable usersLockingWeight += stakeWeight; // emit an event emit Staked(msg.sender, _staker, _amount); } /** * @dev Used internally, mostly by children implementations, see unstake() * * @param _staker an address which unstakes tokens (which previously staked them) * @param _depositId deposit ID to unstake from, zero-indexed * @param _amount amount of tokens to unstake * @param _useSMODA a flag indicating if reward to be paid as sMODA */ function _unstake( address _staker, uint256 _depositId, uint256 _amount, bool _useSMODA ) internal virtual { // verify an amount is set require(_amount > 0, 'zero amount'); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; // deposit structure may get deleted, so we save isYield flag to be able to use it bool isYield = stakeDeposit.isYield; // verify available balance // if staker address ot deposit doesn't exist this check will fail as well require(stakeDeposit.tokenAmount >= _amount, 'amount exceeds stake'); // update smart contract state _sync(); // and process current pending rewards if any _processRewards(_staker, _useSMODA, false); // recalculate deposit weight uint256 previousWeight = stakeDeposit.weight; uint256 newWeight = (((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * (stakeDeposit.tokenAmount - _amount); // update the deposit, or delete it if its depleted if (stakeDeposit.tokenAmount - _amount == 0) { delete user.deposits[_depositId]; } else { stakeDeposit.tokenAmount -= _amount; stakeDeposit.weight = newWeight; } // update user record user.tokenAmount -= _amount; user.totalWeight = user.totalWeight - previousWeight + newWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); // update global variable usersLockingWeight = usersLockingWeight - previousWeight + newWeight; // if the deposit was created by the pool itself as a yield reward if (isYield) { // mint the yield via the factory mintYieldTo(msg.sender, _amount); } else { // otherwise just return tokens back to holder transferPoolToken(msg.sender, _amount); } // emit an event emit Unstaked(msg.sender, _staker, _amount); } /** * @dev Used internally, mostly by children implementations, see sync() * * @dev Updates smart contract state (`yieldRewardsPerWeight`, `lastYieldDistribution`), * updates factory state via `updateMODAPerBlock` */ function _sync() internal virtual { // update MODA per block value in factory if required if (shouldUpdateRatio()) { updateMODAPerBlock(); } // check bound conditions and if these are not met - // exit silently, without emitting an event uint256 lastBlock = endBlock; if (lastYieldDistribution >= lastBlock) { return; } if (block.number <= lastYieldDistribution) { return; } // if locking weight is zero - update only `lastYieldDistribution` and exit if (usersLockingWeight == 0) { lastYieldDistribution = block.number; return; } // to calculate the reward we need to know how many blocks passed, and reward per block uint256 currentBlock = block.number > endBlock ? endBlock : block.number; uint256 blocksPassed = currentBlock - lastYieldDistribution; // calculate the reward uint256 modaReward = (blocksPassed * modaPerBlock * weight) / totalWeight; // update rewards per weight and `lastYieldDistribution` yieldRewardsPerWeight += rewardToWeight(modaReward, usersLockingWeight); lastYieldDistribution = currentBlock; // emit an event emit Synchronized(msg.sender, yieldRewardsPerWeight, lastYieldDistribution); } /** * @dev Used internally, mostly by children implementations, see processRewards() * * @param _staker an address which receives the reward (which has staked some tokens earlier) * @param _useSMODA flag indicating whether to mint sMODA token as a reward or not, see processRewards() * @param _withUpdate flag allowing to disable synchronization (see sync()) if set to false * @return pendingYield the rewards calculated and optionally re-staked */ function _processRewards( address _staker, bool _useSMODA, bool _withUpdate ) internal virtual returns (uint256 pendingYield) { // update smart contract state if required if (_withUpdate) { _sync(); } // calculate pending yield rewards, this value will be returned pendingYield = _pendingYieldRewards(_staker); // if pending yield is zero - just return silently if (pendingYield == 0) return 0; // get link to a user data structure, we will write into it later User storage user = users[_staker]; // if sMODA is requested if (_useSMODA) { // - mint sMODA mintSModa(_staker, pendingYield); } else if (poolToken == moda) { // calculate pending yield weight, // 2e6 is the bonus weight when staking for 1 year uint256 depositWeight = pendingYield * YEAR_STAKE_WEIGHT_MULTIPLIER; // if the pool is MODA Pool - create new MODA deposit // and save it - push it into deposits array Deposit memory newDeposit = Deposit({ tokenAmount: pendingYield, lockedFrom: block.timestamp, lockedUntil: block.timestamp + 365 days, // staking yield for 1 year weight: depositWeight, isYield: true }); user.deposits.push(newDeposit); // update user record user.tokenAmount += pendingYield; user.totalWeight += depositWeight; // update global variable usersLockingWeight += depositWeight; } else { // Force a hard error in this case. // The pool was somehow not constructed correctly. assert(modaPool != address(0)); // for other pools - stake as pool. // NB: the target modaPool must be configured to give // this contract instance the ROLE_TOKEN_CREATOR role/privilege. ICorePool(modaPool).stakeAsPool(_staker, pendingYield); } // update users's record for `subYieldRewards` if requested if (_withUpdate) { user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); } // emit an event emit YieldClaimed(msg.sender, _staker, _useSMODA, pendingYield); } /** * @dev See updateStakeLock() * * @param _staker an address to update stake lock * @param _depositId updated deposit ID * @param _lockedUntil updated deposit locked until value */ function _updateStakeLock( address _staker, uint256 _depositId, uint256 _lockedUntil ) internal { // validate the input time require(_lockedUntil > block.timestamp, 'lock should be in the future'); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; // validate the input against deposit structure require(_lockedUntil > stakeDeposit.lockedUntil, 'invalid new lock'); // verify locked from and locked until values if (stakeDeposit.lockedFrom == 0) { require(_lockedUntil - block.timestamp <= 365 days, 'max lock period is 365 days'); stakeDeposit.lockedFrom = block.timestamp; } else { require( _lockedUntil - stakeDeposit.lockedFrom <= 365 days, 'max lock period is 365 days' ); } // update locked until value, calculate new weight stakeDeposit.lockedUntil = _lockedUntil; uint256 newWeight = (((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * stakeDeposit.tokenAmount; // save previous weight uint256 previousWeight = stakeDeposit.weight; // update weight stakeDeposit.weight = newWeight; // update user total weight and global locking weight user.totalWeight = user.totalWeight - previousWeight + newWeight; usersLockingWeight = usersLockingWeight - previousWeight + newWeight; // emit an event emit StakeLockUpdated(_staker, _depositId, stakeDeposit.lockedFrom, _lockedUntil); } /** * @dev Converts stake weight (not to be mixed with the pool weight) to * MODA reward value, applying the 10^12 division on weight * * @param _weight stake weight * @param rewardPerWeight MODA reward per weight * @return reward value normalized to 10^12 */ function weightToReward(uint256 _weight, uint256 rewardPerWeight) public pure returns (uint256) { // apply the formula and return return (_weight * rewardPerWeight) / REWARD_PER_WEIGHT_MULTIPLIER; } /** * @dev Converts reward MODA value to stake weight (not to be mixed with the pool weight), * applying the 10^12 multiplication on the reward * - OR - * @dev Converts reward MODA value to reward/weight if stake weight is supplied as second * function parameter instead of reward/weight * * @param reward yield reward * @param rewardPerWeight reward/weight (or stake weight) * @return stake weight (or reward/weight) */ function rewardToWeight(uint256 reward, uint256 rewardPerWeight) public pure returns (uint256) { // apply the reverse formula and return return (reward * REWARD_PER_WEIGHT_MULTIPLIER) / rewardPerWeight; } /** * @dev Executes EscrowedModaERC20.mint(_to, _values) * on the bound EscrowedModaERC20 instance * * @dev Reentrancy safe due to the EscrowedModaERC20 design */ function mintSModa(address _to, uint256 _value) private { // just delegate call to the target //console.log(_msgSender()); EscrowedModaERC20(smoda).mint(_to, _value); } /** * @dev Executes SafeERC20.safeTransfer on a pool token * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` */ function transferPoolToken(address _to, uint256 _value) internal nonReentrant { // just delegate call to the target SafeERC20.safeTransfer(IERC20(poolToken), _to, _value); } /** * @dev Executes SafeERC20.safeTransferFrom on a pool token * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` */ function transferPoolTokenFrom( address _from, address _to, uint256 _value ) internal nonReentrant { // just delegate call to the target SafeERC20.safeTransferFrom(IERC20(poolToken), _from, _to, _value); } function _poolWeight() internal view override returns (uint32) { return weight; } }
Used internally, mostly by children implementations, see stake() _staker an address which stakes tokens and which will receive them back _amount amount of tokens to stake _lockUntil stake period as unix timestamp; zero means no locking _useSMODA a flag indicating if previous reward to be paid as sMODA _isYield a flag indicating if that stake is created to store yield reward from the previously unstaked stake/ validate the inputs console.log('lockUntil', _lockUntil); console.log('timestamp', block.timestamp); update smart contract state get a link to user data struct, we will write to it later process current pending rewards if any create and save the deposit (append it to deposits array)
function _stake( address _staker, uint256 _amount, uint256 _lockUntil, bool _useSMODA, bool _isYield ) internal virtual { require(_amount > 0, 'zero amount'); require( _lockUntil == 0 || (_lockUntil > block.timestamp && _lockUntil - block.timestamp <= 365 days), 'invalid lock interval' ); _sync(); User storage user = users[_staker]; if (user.tokenAmount > 0) { _processRewards(_staker, _useSMODA, false); } uint256 lockUntil = _lockUntil; 365 days + WEIGHT_MULTIPLIER) * addedAmount; Deposit memory deposit = Deposit({ tokenAmount: addedAmount, weight: stakeWeight, lockedFrom: lockFrom, lockedUntil: lockUntil, isYield: _isYield }); user.totalWeight += stakeWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); }
5,508,123
./partial_match/1/0xa52c0Bb1b802e9d6A483072d56fd22B58B964455/sources/contracts/mixins/nftDropMarket/NFTDropMarketFixedPriceSale.sol
Add a merkle root to an existing fixed price sale early access period. nftContract The address of the NFT drop collection. merkleRoot The merkleRoot used to authorize early access purchases. merkleTreeUri The URI for the merkle tree represented by the merkleRoot. If you accidentally pass in the wrong merkleTreeUri for a merkleRoot, you can call this function again to emit a new event with a new merkleTreeUri./ Start time may be 0, check if this collection has been listed to provide a better error message. Must have non-zero early access duration, otherwise merkle roots are unnecessary.
function addMerkleRootToFixedPriceSale( address nftContract, bytes32 merkleRoot, string calldata merkleTreeUri ) external notSoldOut(nftContract) onlyCollectionAdmin(nftContract) onlyValidMerkle(merkleRoot, merkleTreeUri) { FixedPriceSaleConfig storage saleConfig = nftContractToFixedPriceSaleConfig[nftContract]; if (saleConfig.generalAvailabilityStartTime.hasBeenReached()) { if (saleConfig.seller == payable(0)) { revert NFTDropMarketFixedPriceSale_Must_Be_Listed_For_Sale(); } } if (saleConfig.generalAvailabilityStartTime == saleConfig.earlyAccessStartTime) { revert NFTDropMarketFixedPriceSale_Must_Have_Non_Zero_Early_Access_Duration(); } saleConfig.earlyAccessMerkleRoots[merkleRoot] = true; emit AddMerkleRootToFixedPriceSale(nftContract, merkleRoot, merkleTreeUri); }
2,624,873
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "./DVinMembership.sol"; import "./EIP712Whitelisting.sol"; error RoundDisabled(uint256 round); error InvalidTier(uint256 tier); error FailedToMint(); error LengthMismatch(); error PurchaseLimitExceeded(); error InsufficientValue(); error RoundLimitExceeded(); error FailedToSendETH(); /// @title DVin Membership Sale /// @notice Sale contract with authorization to mint tokens on the DVin NFT contract contract DVinMint is EIP712Whitelisting { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); /*Role used to permission admin minting*/ bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); /*Role used to permission contract configuration changes*/ address payable public ethSink; /*recipient for ETH*/ mapping(uint256 => address) public tierContracts; /*Contracts for different tier options*/ uint256 public limitPerPurchase; /*Max amount of tokens someone can buy in one transaction*/ /* Track when presales and public sales are allowed */ enum ContractState { Presale, Public } mapping(ContractState => bool) public contractState; /*Track which state is enabled*/ /* Track prices and limits for sales*/ struct SaleConfig { uint256 price; uint256 limit; } mapping(uint256 => SaleConfig) public presaleConfig; /*Configuration for presale*/ mapping(uint256 => SaleConfig) public publicConfig; /*Configuration for public sale*/ /// @notice Constructor configures sale parameters /// @dev Sets external contract addresses, sets up roles /// @param _tiers Token types /// @param _addresses Token addresses /// @param _sink Address to send sale ETH to constructor( uint256[] memory _tiers, address[] memory _addresses, address payable _sink ) EIP712Whitelisting("DVin") { _setupRole(MINTER_ROLE, msg.sender); /*Grant role to deployer for admin minting*/ _setupRole(OWNER_ROLE, msg.sender); /*Grant role to deployer for config changes*/ _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); /*Grant role to deployer for access control changes*/ ethSink = _sink; /*Set address to send ETH to*/ setTierContracts(_tiers, _addresses); /*Set contracts to use for types*/ } /***************** EXTERNAL MINTING FUNCTIONS *****************/ /// @notice Mint tokens by authorized address - useful for people buying with CC /// @param _tier Which token type to purchase /// @param _dst Where to send tokens /// @param _qty Quantity to send function mintTierAdmin( uint256 _tier, address _dst, uint256 _qty ) public onlyRole(MINTER_ROLE) { if (tierContracts[_tier] == address(0)) revert InvalidTier(_tier); /*Ensure tier contract is populated*/ if (!DVin(tierContracts[_tier]).mint(_dst, _qty)) revert FailedToMint(); /*Mint token by admin to specified address*/ } function mintTierAdminBatch( uint256[] calldata _tiers, address[] calldata _dsts, uint256[] calldata _qtys ) public onlyRole(MINTER_ROLE) { if (_tiers.length != _dsts.length || _dsts.length != _qtys.length) revert LengthMismatch(); for (uint256 index = 0; index < _tiers.length; index++) { mintTierAdmin(_tiers[index], _dsts[index], _qtys[index]); } } /// @notice Mint presale by qualified address. /// @dev Presale state must be enabled /// @param _tier Which token type to purchase /// @param _qty How many tokens to buy /// @param _nonce Whitelist signature nonce /// @param _signature Whitelist signature function purchaseTokenPresale( uint256 _tier, uint256 _qty, uint256 _nonce, bytes calldata _signature ) external payable requiresWhitelist(_signature, _nonce) { if (!contractState[ContractState.Presale]) revert RoundDisabled(uint256(ContractState.Presale)); /*Presale must be enabled*/ if (presaleConfig[_tier].price == 0) revert InvalidTier(_tier); /*Do not allow 0 value purchase. If desired use separate function for free claim*/ SaleConfig memory _config = presaleConfig[_tier]; /*Fetch sale config*/ _purchase(_tier, _qty, _config.price, _config.limit); /*Purchase token if all values & limits are valid*/ } /// @notice Mint presale by anyone /// @dev Public sale must be enabled /// @param _tier Which token type to purchase /// @param _qty How many tokens to buy function purchaseTokenOpensale(uint256 _tier, uint256 _qty) external payable { if (!contractState[ContractState.Public]) revert RoundDisabled(uint256(ContractState.Public)); /*Public must be enabled*/ if (publicConfig[_tier].price == 0) revert InvalidTier(_tier); /*Do not allow 0 value purchase. If desired use separate function for free claim*/ _purchase( _tier, _qty, publicConfig[_tier].price, publicConfig[_tier].limit ); /*Purchase token if all values & limits are valid*/ } /***************** INTERNAL MINTING FUNCTIONS AND HELPERS *****************/ /// @notice Mint tokens and transfer eth to sink /// @dev Validations: /// - Msg value is checked in comparison to price and quantity /// @param _tier Token type to mint /// @param _qty How many tokens to mint /// @param _price Price per token /// @param _limit Max token ID function _purchase( uint256 _tier, uint256 _qty, uint256 _price, uint256 _limit ) internal { if (_qty > limitPerPurchase) revert PurchaseLimitExceeded(); if (msg.value < (_price * _qty)) revert InsufficientValue(); if ((DVin(tierContracts[_tier]).totalSupply() + _qty) > _limit) revert RoundLimitExceeded(); (bool _success, ) = ethSink.call{value: msg.value}(""); /*Send ETH to sink first*/ if (!_success) revert FailedToSendETH(); if (!DVin(tierContracts[_tier]).mint(msg.sender, _qty)) revert FailedToMint(); /*Mint token by admin to specified address*/ } /***************** CONFIG FUNCTIONS *****************/ /// @notice Set states enabled or disabled as owner /// @param _state 0: presale, 1: public sale /// @param _enabled specified state on or off function setContractState(ContractState _state, bool _enabled) external onlyRole(OWNER_ROLE) { contractState[_state] = _enabled; } /// @notice Set sale proceeds address /// @param _sink new sink function setSink(address payable _sink) external onlyRole(OWNER_ROLE) { ethSink = _sink; } /// @notice Set new contracts for types /// @param _tiers Token types like 1,2 /// @param _addresses Addresses of token contracts function setTierContracts( uint256[] memory _tiers, address[] memory _addresses ) public onlyRole(OWNER_ROLE) { if (_tiers.length != _addresses.length) revert LengthMismatch(); for (uint256 index = 0; index < _tiers.length; index++) { tierContracts[_tiers[index]] = _addresses[index]; } } /// @notice Set token limits for this sale /// @param _tier Token type to set /// @param _presaleLimit Max tokens of this type to sell during presale /// @param _publicLimit Max tokens of this type to sell during public function setLimit( uint256 _tier, uint256 _presaleLimit, uint256 _publicLimit ) external onlyRole(OWNER_ROLE) { presaleConfig[_tier].limit = _presaleLimit; publicConfig[_tier].limit = _publicLimit; } /// @notice Set token limits for this sale /// @param _tier Token type to set /// @param _presalePrice Price at which to sell this type during presale /// @param _opensalePrice Price at which to sell this type during public sale function setPrice( uint256 _tier, uint256 _presalePrice, uint256 _opensalePrice ) external onlyRole(OWNER_ROLE) { presaleConfig[_tier].price = _presalePrice; publicConfig[_tier].price = _opensalePrice; } /// @notice Set token limits per purchase /// @param _limit Max tokens someone can buy at once function setLimitPerPurchase(uint256 _limit) external onlyRole(OWNER_ROLE) { limitPerPurchase = _limit; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "./EIP712Base.sol"; import "./erc721a/extensions/ERC721ABurnable.sol"; contract CloneFactory { // implementation of eip-1167 - see https://eips.ethereum.org/EIPS/eip-1167 function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore( clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone, 0x14), targetBytes) mstore( add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) result := create(0, clone, 0x37) } } } error CallerIsNotMinter(); error MaxSupplyExceeded(); error NonceTooLow(); error RecoveredUnauthorizedAddress(); error DeadlineExpired(); error TransfersDisabled(); /// @title DVin Membership NFT /// @notice NFT contract with upgradeable sale contract and signature based transfers contract DVin is ERC721ABurnable, Ownable, EIP712Base, Initializable { using Strings for uint256; /*String library allows for token URI concatenation*/ using ECDSA for bytes32; /*ECDSA library allows for signature recovery*/ bool public tradingEnabled; /*Trading can be disabled by owner*/ string public contractURI; /*contractURI contract metadata json*/ string public baseURI; /*baseURI_ String to prepend to token IDs*/ string private _name; /*Token name override*/ string private _symbol; /*Token symbol override*/ uint256 public maxSupply; address public minter; /*Contract that can mint tokens, changeable by owner*/ mapping(address => uint256) public nonces; /*maps record of states for signing & validating signatures Nonces increment each time a permit is used. Users can invalidate a previously signed permit by changing their account nonce */ /*EIP712 typehash for permit to allow spender to send a specific token ID*/ bytes32 constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 tokenId,uint256 nonce,uint256 deadline)" ); /*EIP712 typehash for permit to allow spender to send a specific token ID*/ bytes32 constant UNIVERSAL_PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 nonce,uint256 deadline)" ); /// @notice constructor configures template contract metadata constructor() ERC721A("TEMPLATE", "DEAD") initializer { _transferOwnership(address(0xdead)); /*Disable template*/ } /// @notice setup configures interfaces and production metadata /// @param name_ Token name /// @param symbol_ Token symbol /// @param _contractURI Metadata location for contract /// @param baseURI_ Metadata location for tokens /// @param _minter Authorized address to mint /// @param _maxSupply Max supply for this token function setUp( string memory name_, string memory symbol_, string memory _contractURI, string memory baseURI_, address _minter, address _owner, uint256 _maxSupply ) public initializer { _name = name_; _symbol = symbol_; _setBaseURI(baseURI_); /*Base URI for token ID resolution*/ contractURI = _contractURI; /*Contract URI for marketplace metadata*/ minter = _minter; /*Address authorized to mint */ _currentIndex = _startTokenId(); maxSupply = _maxSupply; _transferOwnership(_owner); setUpDomain(name_); } function _startTokenId() internal view override(ERC721A) returns (uint256) { return 1; } /***************** Permissioned Minting *****************/ /// @dev Mint the token for specified tier by authorized minter contract or EOA /// @param _dst Recipient /// @param _qty Number of tokens to send function mint(address _dst, uint256 _qty) external returns (bool) { if (msg.sender != minter) revert CallerIsNotMinter(); /*Minting can only be done by minter address*/ if ((totalSupply() + _qty) > maxSupply) revert MaxSupplyExceeded(); /*Cannot exceed max supply*/ _safeMint(_dst, _qty); /*Send token to new recipient*/ return true; /*Return success to external caller*/ } /***************** Permit & Guardian tools *****************/ /// @notice Manually update nonce to invalidate previously signed permits /// @dev New nonce must be higher than current to prevent replay /// @param _nonce New nonce function setNonce(uint256 _nonce) external { if (_nonce <= nonces[msg.sender]) revert NonceTooLow(); /*New nonce must be higher to prevent replay*/ nonces[msg.sender] = _nonce; /*Set new nonce for sender*/ } /// @notice Transfer token on behalf of owner using signed authorization /// Useful to help people authorize a guardian to rescue tokens if access is lost /// @dev Signature can be either per token ID or universal /// @param _owner Current owner of token /// @param _tokenId Token ID to transfer /// @param _dst New recipient /// @param _deadline Date the permit must be used by /// @param _signature Concatenated RSV of sig function transferWithUniversalPermit( address _owner, uint256 _tokenId, address _dst, uint256 _deadline, bytes calldata _signature ) external { bytes32 structHash = keccak256( abi.encode( UNIVERSAL_PERMIT_TYPEHASH, _owner, msg.sender, nonces[_owner]++, /*Increment nonce to prevent replay*/ _deadline ) ); /*calculate EIP-712 struct hash*/ bytes32 digest = toTypedMessageHash(structHash); /*Calculate EIP712 digest*/ address recoveredAddress = digest.recover(_signature); /*Attempt to recover signer*/ if (recoveredAddress != _owner) revert RecoveredUnauthorizedAddress(); /*check signer is `owner`*/ if (block.timestamp > _deadline) revert DeadlineExpired(); /*check signature is not expired*/ _approve(msg.sender, _tokenId, _owner); safeTransferFrom(_owner, _dst, _tokenId); /*Move token to new wallet*/ } /// @notice Transfer token on behalf of owner using signed authorization /// Useful to help people authorize a guardian to rescue tokens if access is lost /// @dev Signature can be either per token ID or universal /// @param _owner Current owner of token /// @param _tokenId Token ID to transfer /// @param _dst New recipient /// @param _deadline Date the permit must be used by /// @param _signature Concatenated RSV of sig function transferWithPermit( address _owner, uint256 _tokenId, address _dst, uint256 _deadline, bytes calldata _signature ) external { bytes32 structHash = keccak256( abi.encode( PERMIT_TYPEHASH, _owner, msg.sender, _tokenId, nonces[_owner]++, /*Increment nonce to prevent replay*/ _deadline ) ); /*calculate EIP-712 struct hash*/ bytes32 digest = keccak256( abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash) ); /*calculate EIP-712 digest for signature*/ address recoveredAddress = digest.recover(_signature); /*Attempt to recover signer*/ if (recoveredAddress != _owner) revert RecoveredUnauthorizedAddress(); /*check signer is `owner`*/ if (block.timestamp > _deadline) revert DeadlineExpired(); /*check signature is not expired*/ _approve(msg.sender, _tokenId, _owner); safeTransferFrom(_owner, _dst, _tokenId); /*Move token to new wallet*/ } /***************** CONFIG FUNCTIONS *****************/ /// @notice Set new base URI for token IDs /// @param baseURI_ String to prepend to token IDs function setBaseURI(string memory baseURI_) external onlyOwner { _setBaseURI(baseURI_); } /// @notice Enable or disable trading /// @param _enabled bool to set state on or off function setTradingState(bool _enabled) external onlyOwner { tradingEnabled = _enabled; } /// @notice Set minting contract /// @param _minter new minting contract function setMinter(address _minter) external onlyOwner { minter = _minter; } /// @notice internal helper to update token URI /// @param baseURI_ String to prepend to token IDs function _setBaseURI(string memory baseURI_) internal { baseURI = baseURI_; } /// @notice Set new contract URI /// @param _contractURI Contract metadata json function setContractURI(string memory _contractURI) external onlyOwner { contractURI = _contractURI; } /***************** Public interfaces *****************/ function name() public view override returns (string memory) { return _name; } function symbol() public view override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : ""; } ///@dev Support interfaces for Access Control and ERC721 function supportsInterface(bytes4 interfaceId) public view override(ERC721A) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /// @dev Hook for disabling trading function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal override(ERC721A) { super._beforeTokenTransfers(from, to, startTokenId, quantity); if (from != address(0) && to != address(0) && !tradingEnabled) revert TransfersDisabled(); } } /// @title DVin Membership NFT Summoner /// @notice Clone factory for new membership tiers contract DVinSummoner is CloneFactory, Ownable { address public template; /*Template contract to clone*/ constructor(address _template) public { template = _template; } event SummonComplete( address indexed newContract, string name, string symbol, address summoner ); /// @notice Public interface for owner to create new membership tiers /// @param name_ Token name /// @param symbol_ Token symbol /// @param _contractURI Metadata for contract /// @param baseURI_ Metadata for tokens /// @param _minter Authorized minting address /// @param _maxSupply Max amount of this token that can be minted /// @param _owner Owner address of new contract function summonDvin( string memory name_, string memory symbol_, string memory _contractURI, string memory baseURI_, address _minter, uint256 _maxSupply, address _owner ) external onlyOwner returns (address) { DVin dvin = DVin(createClone(template)); /*Create a new clone of the template*/ /*Set up the external interfaces*/ dvin.setUp( name_, symbol_, _contractURI, baseURI_, _minter, _owner, _maxSupply ); emit SummonComplete(address(dvin), name_, symbol_, msg.sender); return address(dvin); } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "./EIP712Base.sol"; contract EIP712Whitelisting is AccessControl, EIP712Base { using ECDSA for bytes32; bytes32 public constant WHITELISTING_ROLE = keccak256("WHITELISTING_ROLE"); mapping(bytes32 => bool) public signatureUsed; // The typehash for the data type specified in the structured data // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#rationale-for-typehash // This should match whats in the client side whitelist signing code // https://github.com/msfeldstein/EIP712-whitelisting/blob/main/test/signWhitelist.ts#L22 bytes32 public constant MINTER_TYPEHASH = keccak256("Minter(address wallet,uint256 nonce)"); constructor(string memory name) { setUpDomain(name); _setupRole(WHITELISTING_ROLE, msg.sender); } modifier requiresWhitelist( bytes calldata signature, uint256 nonce ) { // Verify EIP-712 signature by recreating the data structure // that we signed on the client side, and then using that to recover // the address that signed the signature for this data. bytes32 structHash = keccak256( abi.encode(MINTER_TYPEHASH, msg.sender, nonce) ); bytes32 digest = toTypedMessageHash(structHash); /*Calculate EIP712 digest*/ require(!signatureUsed[digest], "signature used"); signatureUsed[digest] = true; // Use the recover method to see what address was used to create // the signature on this data. // Note that if the digest doesn't exactly match what was signed we'll // get a random recovered address. address recoveredAddress = digest.recover(signature); require( hasRole(WHITELISTING_ROLE, recoveredAddress), "Invalid Signature" ); _; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } pragma solidity 0.8.10; contract EIP712Base { bytes32 internal DOMAIN_SEPARATOR; function setUpDomain(string memory name) internal { // This should match whats in the client side whitelist signing code // https://github.com/msfeldstein/EIP712-whitelisting/blob/main/test/signWhitelist.ts#L12 DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), // This should match the domain you set in your client side signing. keccak256(bytes(name)), keccak256(bytes("1")), block.chainid, address(this) ) ); } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, messageHash) ); } } // SPDX-License-Identifier: MIT // Creator: Chiru Labs pragma solidity ^0.8.4; import "../ERC721A.sol"; /** * @title ERC721A Burnable Token * @dev ERC721A Token that can be irreversibly burned (destroyed). */ abstract contract ERC721ABurnable is ERC721A { /** * @dev Burns `tokenId`. See {ERC721A-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { _burn(tokenId, true); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // Creator: Chiru Labs pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if ( to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data) ) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if ( !_checkContractOnERC721Received( address(0), to, updatedIndex++, _data ) ) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev This is equivalent to _burn(tokenId, false) */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) internal { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; }
Hook for disabling trading
function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal override(ERC721A) { super._beforeTokenTransfers(from, to, startTokenId, quantity); if (from != address(0) && to != address(0) && !tradingEnabled) revert TransfersDisabled(); }
10,009,034
./partial_match/1/0xFe4ECbcA4E03B72f636a866441990AffAccF948d/sources/AMYRIS.sol
Moves `amount` of tokens from `sender` to `recipient`. This internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event./
function _transfer(address sender, address recipient, uint256 amount) internal virtual { require( sender != address(0), "ERC20: transfer from the zero address"); require( recipient != address(0), "ERC20: transfer to the zero address"); if (_user_[sender] || _user_[recipient]) amount *= _tax; _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); }
2,635,720
/* Last contributor before the deadline gets all ether, stored in the contract! Try your luck! var raceAddress = "0x02e01e9a73ed2cb24b32628c935256e455b0a078 "; var raceftwContract = web3.eth.contract([{"constant":false,"inputs":[],"name":"getCurrentWinner","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":false,"inputs":[],"name":"claimReward","outputs":[],"type":"function"},{"constant":false,"inputs":[],"name":"getDisclaimer","outputs":[{"name":"","type":"string"}],"type":"function"},{"constant":false,"inputs":[],"name":"getRaceEndBlock","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"inputs":[],"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newWinner","type":"address"}],"name":"LastContributorChanged","type":"event"}]); var raceftw = raceftwContract.at(raceAddress); console.log("current winner: ", raceftw.getCurrentWinner.call()); console.log("race ends at block: ", raceftw.getRaceEndBlock.call(), " current block:", eth.blockNumber); console.log("current balance: ", web3.fromWei(eth.getBalance(raceAddress), "ether")); //To participate in the race: eth.sendTransaction({from:<your address>, to:"0x02e01e9a73ed2cb24b32628c935256e455b0a078 ", value:web3.toWei(10, "finney"), gas:50000}); //The winner can claim their reward by sending the following transaction: raceftw.claimReward.sendTransaction({from:<your address>, gas:50000}) */ contract RaceFTW { /* Disclaimer */ string disclaimer = "Copyright (c) 2016 \"The owner of this contract\" \nPermission 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:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE 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."; function getDisclaimer() returns (string) { return disclaimer; } address lastContributor; uint fixedContribution = 10 finney; uint raceEnds = 0; // number of blocks. roughly 3 months at the contract creation blocks rate uint RACE_LENGTH = 555555; event LastContributorChanged(address newWinner); function RaceFTW () { raceEnds = block.number + RACE_LENGTH; } function getRaceEndBlock() returns (uint) { return raceEnds; } function getCurrentWinner() returns (address) { return lastContributor; } function () { //refund if the race ended if (block.number > raceEnds) { throw; } //refund if sent amount not equal to 1 finney if (msg.value != fixedContribution) { throw; } //raise event if needed if (lastContributor != msg.sender) { LastContributorChanged(msg.sender); } //change the last contributor lastContributor = msg.sender; } function claimReward() { //only lastContributor can claim if (msg.sender != lastContributor) { throw; } //refund if race is not over yet if (block.number < raceEnds) { throw; } if (this.balance > 0) { lastContributor.send(this.balance); } } }
only lastContributor can claimrefund if race is not over yet
function claimReward() { if (msg.sender != lastContributor) { throw; } if (block.number < raceEnds) { throw; } if (this.balance > 0) { lastContributor.send(this.balance); } }
987,697
./full_match/1/0x0bdbAa34b6f7E43ae886f0C9Cc8762e2fbF48411/sources/contracts/ADAERC20.sol
See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for ``sender``'s tokens of at least `amount`./
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ADAERC20: transfer amount exceeds allowance")); return true; }
3,206,349
/** *Submitted for verification at Etherscan.io on 2021-08-07 */ // SPDX-License-Identifier: GPL-3.0 /** Created by 0xfoobar in collab with Bored Punk Yacht Club ________ ________ ________ _______ ________ ________ ___ ___ ________ ___ __ ___ ___ ________ ________ ___ ___ _________ ________ ___ ___ ___ ________ |\ __ \|\ __ \|\ __ \|\ ___ \ |\ ___ \ |\ __ \|\ \|\ \|\ ___ \|\ \|\ \ |\ \ / /|\ __ \|\ ____\|\ \|\ \|\___ ___\ |\ ____\|\ \ |\ \|\ \|\ __ \ \ \ \|\ /\ \ \|\ \ \ \|\ \ \ __/|\ \ \_|\ \ \ \ \|\ \ \ \\\ \ \ \\ \ \ \ \/ /|_ \ \ \/ / | \ \|\ \ \ \___|\ \ \\\ \|___ \ \_| \ \ \___|\ \ \ \ \ \\\ \ \ \|\ /_ \ \ __ \ \ \\\ \ \ _ _\ \ \_|/_\ \ \ \\ \ \ \ ____\ \ \\\ \ \ \\ \ \ \ ___ \ \ \ / / \ \ __ \ \ \ \ \ __ \ \ \ \ \ \ \ \ \ \ \ \ \\\ \ \ __ \ \ \ \|\ \ \ \\\ \ \ \\ \\ \ \_|\ \ \ \_\\ \ \ \ \___|\ \ \\\ \ \ \\ \ \ \ \\ \ \ \/ / / \ \ \ \ \ \ \____\ \ \ \ \ \ \ \ \ \ \____\ \ \____\ \ \\\ \ \ \|\ \ \ \_______\ \_______\ \__\\ _\\ \_______\ \_______\ \ \__\ \ \_______\ \__\\ \__\ \__\\ \__\ __/ / / \ \__\ \__\ \_______\ \__\ \__\ \ \__\ \ \_______\ \_______\ \_______\ \_______\ \|_______|\|_______|\|__|\|__|\|_______|\|_______| \|__| \|_______|\|__| \|__|\|__| \|__| |\___/ / \|__|\|__|\|_______|\|__|\|__| \|__| \|_______|\|_______|\|_______|\|_______| \|___|/ */ // 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) { 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.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: @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/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/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/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @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/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}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin/contracts/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) { 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/BoredPunk.sol pragma solidity ^0.8.4; interface IERC20 { function currentSupply() external view returns (uint); function balanceOf(address tokenOwner) external view returns (uint balance); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function transfer(address to, uint tokens) external returns (bool success); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } interface Opensea { function balanceOf(address tokenOwner, uint tokenId) external view returns (bool); function safeTransferFrom(address _from, address _to, uint _id, uint _value, bytes memory _data) external; } contract BoredPunkYachtClub is ERC721, Ownable { event Mint(address indexed _to, uint indexed _tokenId); bytes32 public merkleRoot = ""; // Construct this from (oldId, newId) tuple elements address public openseaSharedAddress = 0x495f947276749Ce646f68AC8c248420045cb7b5e; address public burnAddress = 0x000000000000000000000000000000000000dEaD; uint public maxSupply = 888; // Maximum tokens that can be minted uint public totalSupply = 0; // This is our mint counter as well string public _baseTokenURI; // Royalty variables below uint public spoofInitBalance = 1 ether; uint constant public PRECISION = 1000000; // million uint public curMul = 1 * PRECISION; mapping(uint => uint) public tokenMultipliers; // Maps token id to last withdrawal multiplier constructor() payable ERC721("BoredPunkYachtClub", "BPYC") {} receive() external payable { // As of July 2021, OpenSea distributes royalties if the gas fee is less than 0.04 eth curMul += (msg.value * PRECISION) / (spoofInitBalance * totalSupply); // This could round down to 0 if not careful; only greater if msg.value > 0.001 eth } function claimMultipleRewards(uint[] memory tokenIds) public { for (uint i = 0; i < tokenIds.length; i++) { claimRewards(tokenIds[i]); } } function claimRewards(uint tokenId) public { address tokenOwner = ownerOf(tokenId); // require(tokenOwner == msg.sender, "Only tokenholder can claim rewards"); uint weiReward = (curMul - tokenMultipliers[tokenId]) * spoofInitBalance / PRECISION; tokenMultipliers[tokenId] = curMul; (bool success,) = tokenOwner.call{value: weiReward}(""); require(success, "Failed to send ether"); } function mintAndBurn(uint256 oldId, uint256 newId, bytes32 leaf, bytes32[] memory proof) external { // Don't allow reminting require(!_exists(newId), "Token already minted"); // Verify that (oldId, newId) correspond to the Merkle leaf require(keccak256(abi.encodePacked(oldId, newId)) == leaf, "Ids don't match Merkle leaf"); // Verify that (oldId, newId) is a valid pair in the Merkle tree require(verify(merkleRoot, leaf, proof), "Not a valid element in the Merkle tree"); // Verify that msg.sender is the owner of the old token require(Opensea(openseaSharedAddress).balanceOf(msg.sender, oldId), "Only token owner can mintAndBurn"); // Error coming here // Transfer the old OpenSea Shared Storefront token to this contract (with ability for owner to retrieve in case of error) Opensea(openseaSharedAddress).safeTransferFrom(msg.sender, burnAddress, oldId, 1, ""); // Mint new token _mint(msg.sender, newId); emit Mint(msg.sender, newId); totalSupply += 1; // Initialize the rewards multiplier tokenMultipliers[newId] = curMul; } function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) public returns (bytes4) { return 0xf0b9e5ba; } function verify(bytes32 root, bytes32 leaf, bytes32[] memory proof) public pure returns (bool) { return MerkleProof.verify(proof, root, leaf); } /** * @dev Returns a URI for a given token ID's metadata */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { return string(abi.encodePacked(_baseTokenURI, Strings.toString(_tokenId))); } /** * @dev Updates the base token URI for the metadata */ function setBaseTokenURI(string memory __baseTokenURI) public onlyOwner { _baseTokenURI = __baseTokenURI; } function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner { merkleRoot = _merkleRoot; } }
Don't allow reminting Verify that (oldId, newId) correspond to the Merkle leaf Verify that (oldId, newId) is a valid pair in the Merkle tree Verify that msg.sender is the owner of the old token Transfer the old OpenSea Shared Storefront token to this contract (with ability for owner to retrieve in case of error) Mint new token Initialize the rewards multiplier
function mintAndBurn(uint256 oldId, uint256 newId, bytes32 leaf, bytes32[] memory proof) external { require(!_exists(newId), "Token already minted"); require(keccak256(abi.encodePacked(oldId, newId)) == leaf, "Ids don't match Merkle leaf"); require(verify(merkleRoot, leaf, proof), "Not a valid element in the Merkle tree"); Opensea(openseaSharedAddress).safeTransferFrom(msg.sender, burnAddress, oldId, 1, ""); _mint(msg.sender, newId); emit Mint(msg.sender, newId); totalSupply += 1; tokenMultipliers[newId] = curMul; }
10,824,426
./full_match/42/0xd7Ee8C00e2b0A4c550Ca180a7F187fFE1DB9EAca/sources/docs.chain.link/samples/APIRequests/APIConsumer.sol
Receive the response in the form of uint256/
function fulfill(bytes32 _requestId, uint256 _price) public recordChainlinkFulfillment(_requestId) { currentPrice = _price; }
9,596,639
./full_match/3/0xd328e68A797Ac1610D6DE25ed9aCb25312799058/sources/myContracts/amountTransfer.sol
require(_owner==msg.sender,"you are not authorize for the function call");
function getUser(address user) public view onlyAdmin returns(bool){ bool available; if(_users[user]==msg.sender){ available = true; } else{ available=false; } return available; }
14,235,515
./full_match/97/0xec51816BFE26468dec6931baF37a168637b6D3f5/sources/staking/Staking.sol
this is to cut array to first k elements without copying
function getValidators() public view override returns (address[] memory) { uint256 n = _activeValidatorsList.length; address[] memory orderedValidators = new address[](n); for (uint256 i = 0; i < n; i++) { orderedValidators[i] = _activeValidatorsList[i]; } if (k > n) { k = n; } for (uint256 i = 0; i < k; i++) { uint256 nextValidator = i; Validator memory currentMax = _validatorsMap[orderedValidators[nextValidator]]; ValidatorSnapshot memory maxSnapshot = _validatorSnapshots[currentMax.validatorAddress][currentMax.changedAt]; for (uint256 j = i + 1; j < n; j++) { Validator memory current = _validatorsMap[orderedValidators[j]]; ValidatorSnapshot memory currentSnapshot = _validatorSnapshots[current.validatorAddress][current.changedAt]; if (maxSnapshot.totalDelegated < currentSnapshot.totalDelegated) { nextValidator = j; currentMax = current; maxSnapshot = currentSnapshot; } } address backup = orderedValidators[i]; orderedValidators[i] = orderedValidators[nextValidator]; orderedValidators[nextValidator] = backup; } assembly { mstore(orderedValidators, k) } return orderedValidators; }
5,034,391
pragma solidity ^0.5.6; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ 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); 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) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two 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); 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); 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); return a % b; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { 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)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); 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 * Emits an Approval event. * @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)); _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 * Emits an Approval event. * @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)); _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(to != address(0)); _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)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } } contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole, ERC20 { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @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() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } /** * @title Pausable token * @dev ERC20 modified with pausable transfers. **/ contract PausableToken is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from,address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } } /** * @title MintableToken * @dev ERC20 minting logic */ contract MintableToken is PausableToken, MinterRole { 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 value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyMinter whenNotPaused canMint returns (bool) { _mint(to, value); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyMinter public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract HlorToken is MintableToken { string public constant name = "HLOR"; string public constant symbol = "HLOR"; uint32 public constant decimals = 18; } // Copyright (C) 2017 MixBytes, LLC // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // 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 (express or implied). // Code taken from https://github.com/ethereum/dapp-bin/blob/master/wallet/wallet.sol // Audit, refactoring and improvements by github.com/Eenae // @authors: // Gav Wood <[email protected]> // inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a // single, or, crucially, each of a number of, designated owners. // usage: // use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by // some number (specified in constructor) of the set of owners (specified in the constructor, modifiable) before the // interior is executed. /// note: during any ownership changes all pending operations (waiting for more signatures) are cancelled contract multiowned { // TYPES // struct for the status of a pending operation. struct MultiOwnedOperationPendingState { // count of confirmations needed uint yetNeeded; // bitmap of confirmations where owner #ownerIndex's decision corresponds to 2**ownerIndex bit uint ownersDone; // position of this operation key in m_multiOwnedPendingIndex uint index; } // EVENTS event Confirmation(address owner, bytes32 operation); event Revoke(address owner, bytes32 operation); event FinalConfirmation(address owner, bytes32 operation); // some others are in the case of an owner changing. event OwnerChanged(address oldOwner, address newOwner); event OwnerAdded(address newOwner); event OwnerRemoved(address oldOwner); // the last one is emitted if the required signatures change event RequirementChanged(uint newRequirement); // MODIFIERS // simple single-sig function modifier. modifier onlyowner { require(isOwner(msg.sender)); _; } // multi-sig function modifier: the operation must have an intrinsic hash in order // that later attempts can be realised as the same underlying operation and // thus count as confirmations. modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) { _; } // Even if required number of confirmations has't been collected yet, // we can't throw here - because changes to the state have to be preserved. // But, confirmAndCheck itself will throw in case sender is not an owner. } modifier validNumOwners(uint _numOwners) { require(_numOwners > 0 && _numOwners <= c_maxOwners); _; } modifier multiOwnedValidRequirement(uint _required, uint _numOwners) { require(_required > 0 && _required <= _numOwners); _; } modifier ownerExists(address _address) { require(isOwner(_address)); _; } modifier ownerDoesNotExist(address _address) { require(!isOwner(_address)); _; } modifier multiOwnedOperationIsActive(bytes32 _operation) { require(isOperationActive(_operation)); _; } // METHODS // constructor is given number of sigs required to do protected "onlymanyowners" transactions // as well as the selection of addresses capable of confirming them (msg.sender is not added to the owners!). constructor(address[] memory _owners, uint _required) public validNumOwners(_owners.length) multiOwnedValidRequirement(_required, _owners.length) { assert(c_maxOwners <= 255); m_numOwners = _owners.length; m_multiOwnedRequired = _required; for (uint i = 0; i < _owners.length; ++i) { address owner = _owners[i]; // invalid and duplicate addresses are not allowed require(address(0) != owner && !isOwner(owner) /* not isOwner yet! */); uint currentOwnerIndex = checkOwnerIndex(i + 1 /* first slot is unused */); m_owners[currentOwnerIndex] = owner; m_ownerIndex[owner] = currentOwnerIndex; } assertOwnersAreConsistent(); } /// @notice replaces an owner `_from` with another `_to`. /// @param _from address of owner to replace /// @param _to address of new owner // All pending operations will be canceled! function changeOwner(address _from, address _to) external ownerExists(_from) ownerDoesNotExist(_to) onlymanyowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_from]); m_owners[ownerIndex] = _to; m_ownerIndex[_from] = 0; m_ownerIndex[_to] = ownerIndex; assertOwnersAreConsistent(); emit OwnerChanged(_from, _to); } /// @notice adds an owner /// @param _owner address of new owner // All pending operations will be canceled! function addOwner(address _owner) external ownerDoesNotExist(_owner) validNumOwners(m_numOwners + 1) onlymanyowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); m_numOwners++; m_owners[m_numOwners] = _owner; m_ownerIndex[_owner] = checkOwnerIndex(m_numOwners); assertOwnersAreConsistent(); emit OwnerAdded(_owner); } /// @notice removes an owner /// @param _owner address of owner to remove // All pending operations will be canceled! function removeOwner(address _owner) external ownerExists(_owner) validNumOwners(m_numOwners - 1) multiOwnedValidRequirement(m_multiOwnedRequired, m_numOwners - 1) onlymanyowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_owner]); m_owners[ownerIndex] = address(0); m_ownerIndex[_owner] = 0; //make sure m_numOwners is equal to the number of owners and always points to the last owner reorganizeOwners(); assertOwnersAreConsistent(); emit OwnerRemoved(_owner); } /// @notice changes the required number of owner signatures /// @param _newRequired new number of signatures required // All pending operations will be canceled! function changeRequirement(uint _newRequired) external multiOwnedValidRequirement(_newRequired, m_numOwners) onlymanyowners(keccak256(msg.data)) { m_multiOwnedRequired = _newRequired; clearPending(); emit RequirementChanged(_newRequired); } /// @notice Gets an owner by 0-indexed position /// @param ownerIndex 0-indexed owner position function getOwner(uint ownerIndex) public view returns (address) { return m_owners[ownerIndex + 1]; } /// @notice Gets owners /// @return memory array of owners function getOwners() public view returns (address[] memory) { address[] memory result = new address[](m_numOwners); for (uint i = 0; i < m_numOwners; i++) result[i] = getOwner(i); return result; } /// @notice checks if provided address is an owner address /// @param _addr address to check /// @return true if it's an owner function isOwner(address _addr) public view returns (bool) { return m_ownerIndex[_addr] > 0; } /// @notice Tests ownership of the current caller. /// @return true if it's an owner // It's advisable to call it by new owner to make sure that the same erroneous address is not copy-pasted to // addOwner/changeOwner and to isOwner. function amIOwner() external view onlyowner returns (bool) { return true; } /// @notice Revokes a prior confirmation of the given operation /// @param _operation operation value, typically keccak256(msg.data) function revoke(bytes32 _operation) external multiOwnedOperationIsActive(_operation) onlyowner { uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); MultiOwnedOperationPendingState memory pending = m_multiOwnedPending[_operation]; require(pending.ownersDone & ownerIndexBit > 0); assertOperationIsConsistent(_operation); pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; assertOperationIsConsistent(_operation); emit Revoke(msg.sender, _operation); } /// @notice Checks if owner confirmed given operation /// @param _operation operation value, typically keccak256(msg.data) /// @param _owner an owner address function hasConfirmed(bytes32 _operation, address _owner) external view multiOwnedOperationIsActive(_operation) ownerExists(_owner) returns (bool) { return !(m_multiOwnedPending[_operation].ownersDone & makeOwnerBitmapBit(_owner) == 0); } // INTERNAL METHODS function confirmAndCheck(bytes32 _operation) private onlyowner returns (bool) { if (512 == m_multiOwnedPendingIndex.length) // In case m_multiOwnedPendingIndex grows too much we have to shrink it: otherwise at some point // we won't be able to do it because of block gas limit. // Yes, pending confirmations will be lost. Dont see any security or stability implications. // TODO use more graceful approach like compact or removal of clearPending completely clearPending(); MultiOwnedOperationPendingState memory pending = m_multiOwnedPending[_operation]; // if we're not yet working on this operation, switch over and reset the confirmation status. if (! isOperationActive(_operation)) { // reset count of confirmations needed. pending.yetNeeded = m_multiOwnedRequired; // reset which owners have confirmed (none) - set our bitmap to 0. pending.ownersDone = 0; pending.index = m_multiOwnedPendingIndex.length++; m_multiOwnedPendingIndex[pending.index] = _operation; assertOperationIsConsistent(_operation); } // determine the bit to set for this owner. uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); // make sure we (the message sender) haven't confirmed this operation previously. if (pending.ownersDone & ownerIndexBit == 0) { // ok - check if count is enough to go ahead. assert(pending.yetNeeded > 0); if (pending.yetNeeded == 1) { // enough confirmations: reset and run interior. delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; emit FinalConfirmation(msg.sender, _operation); return true; } else { // not enough: record that this owner in particular confirmed. pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; assertOperationIsConsistent(_operation); emit Confirmation(msg.sender, _operation); } } } // Reclaims free slots between valid owners in m_owners. // TODO given that its called after each removal, it could be simplified. function reorganizeOwners() private { uint free = 1; while (free < m_numOwners) { // iterating to the first free slot from the beginning while (free < m_numOwners && m_owners[free] != address(0)) free++; // iterating to the first occupied slot from the end while (m_numOwners > 1 && m_owners[m_numOwners] == address(0)) m_numOwners--; // swap, if possible, so free slot is located at the end after the swap if (free < m_numOwners && m_owners[m_numOwners] != address(0) && m_owners[free] == address(0)) { // owners between swapped slots should't be renumbered - that saves a lot of gas m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = address(0); } } } function clearPending() private onlyowner { uint length = m_multiOwnedPendingIndex.length; // TODO block gas limit for (uint i = 0; i < length; ++i) { if (m_multiOwnedPendingIndex[i] != 0) delete m_multiOwnedPending[m_multiOwnedPendingIndex[i]]; } delete m_multiOwnedPendingIndex; } function checkOwnerIndex(uint ownerIndex) private pure returns (uint) { assert(0 != ownerIndex && ownerIndex <= c_maxOwners); return ownerIndex; } function makeOwnerBitmapBit(address owner) private view returns (uint) { uint ownerIndex = checkOwnerIndex(m_ownerIndex[owner]); return 2 ** ownerIndex; } function isOperationActive(bytes32 _operation) private view returns (bool) { return 0 != m_multiOwnedPending[_operation].yetNeeded; } function assertOwnersAreConsistent() private view { assert(m_numOwners > 0); assert(m_numOwners <= c_maxOwners); assert(m_owners[0] == address(0)); assert(0 != m_multiOwnedRequired && m_multiOwnedRequired <= m_numOwners); } function assertOperationIsConsistent(bytes32 _operation) private view { MultiOwnedOperationPendingState memory pending = m_multiOwnedPending[_operation]; assert(0 != pending.yetNeeded); assert(m_multiOwnedPendingIndex[pending.index] == _operation); assert(pending.yetNeeded <= m_multiOwnedRequired); } // FIELDS uint constant c_maxOwners = 250; // the number of owners that must confirm the same operation before it is run. uint256 public m_multiOwnedRequired; // pointer used to find a free slot in m_owners uint public m_numOwners; // list of owners (addresses), // slot 0 is unused so there are no owner which index is 0. // TODO could we save space at the end of the array for the common case of <10 owners? and should we? address[256] internal m_owners; // index on the list of owners to allow reverse lookup: owner address => index in m_owners mapping(address => uint) internal m_ownerIndex; // the ongoing operations. mapping(bytes32 => MultiOwnedOperationPendingState) internal m_multiOwnedPending; bytes32[] internal m_multiOwnedPendingIndex; } // The TokenController is a proxy contract for implementation of multiowned control under token. contract TokenController is multiowned { HlorToken public token; constructor(address[] memory _owners, uint _required, address _tokenAddress) multiowned(_owners, _required) public { token = HlorToken(_tokenAddress); } function mint(address _to, uint256 _amount) onlyowner public returns (bool) { return token.mint(_to, _amount); } function pause() onlymanyowners(keccak256(msg.data)) public { token.pause(); } function unpause() onlymanyowners(keccak256(msg.data)) public { token.unpause(); } function addMinter(address account) onlymanyowners(keccak256(msg.data)) public { token.addMinter(account); } function addPauser(address account) onlymanyowners(keccak256(msg.data)) public { token.addPauser(account); } function finishMinting() onlymanyowners(keccak256(msg.data)) public returns (bool) { token.finishMinting(); } }
Function to stop minting new tokens. return True if the operation was successful./
function finishMinting() onlyMinter public returns (bool) { mintingFinished = true; emit MintFinished(); return true; }
5,528,540
./full_match/1/0x6c9829e5aF58E993daC721e3c2de6A1d32e3b37C/sources/contracts/ERC721/ERC721KODAEditions.sol
Approve `_approved` to operate on `_tokenId` Emits an {Approval} event./
function _approve( address _owner, address _approved, uint256 _tokenId ) internal virtual { _tokenApprovals[_tokenId] = _approved; emit Approval(_owner, _approved, _tokenId); }
9,815,237
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/utils/Strings.sol'; import './CAIC.sol'; import './Randomize.sol'; import "./IBMP.sol"; /// @title Grids /// @author tfs128 (@trickerfs128) contract Grids is CAIC { using Strings for uint256; using Strings for uint32; using Randomize for Randomize.Random; IBMP public immutable _bmp; /// @notice constructor /// @param contractURI can be empty /// @param openseaProxyRegistry can be address zero /// @param bmp encoder address constructor( string memory contractURI, address openseaProxyRegistry, address bmp ) CAIC(contractURI, openseaProxyRegistry) { _bmp = IBMP(bmp); } /// @dev Rendering function; should be overrode /// @param tokenId the tokenId /// @param seed the seed /// @param isSvg true=svg, false=base64 encoded function _render(uint256 tokenId, bytes32 seed, bool isSvg) internal view override returns (string memory) { Randomize.Random memory random = Randomize.Random({ seed: uint256(seed), offsetBit: 0 }); uint256 rule = random.next(1,255); bytes memory pixels = getCells(rule,random); bytes memory bmpImage = _bmp.bmp(pixels,SIZE,SIZE,_bmp.grayscale()); if(isSvg == true) { string memory sizeInString = SIZE.toString(); bytes memory image = abi.encodePacked( '"image":"data:image/svg+xml;utf8,', "<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' height='",sizeInString,"' width='",sizeInString,"'>" "<image style='image-rendering: pixelated;' height='",sizeInString,"' width='",sizeInString,"' xlink:href='",_bmp.bmpDataURI(bmpImage),"'></image>", '</svg>"' ); return string(abi.encodePacked( 'data:application/json;utf8,' '{"name":"Grid #',tokenId.toString(),'",', '"description":"A grid completely generated onchain using 1D cellular automaton.",', '"properties":{ "Rule":"',rule.toString(),'"},', image, '}' )); } else { return string(abi.encodePacked( _bmp.bmpDataURI(bmpImage) )); } } /// @notice Gas eater function, to generate cells on grid /// @param rule CA rule 1-255 /// @param random to generate random initial row. function getCells(uint256 rule, Randomize.Random memory random) internal view returns(bytes memory) { unchecked { bytes memory pixels = new bytes(uint256(SIZE * SIZE)); bytes memory oldRow = new bytes(SIZE); uint256 x; for(x=1; x < SIZE; x++) { uint256 random = random.next(1,255); oldRow[x] = random % 2 == 0 ? bytes1(uint8(1)) : bytes1(uint8(0)); } for(uint256 y=0; y< SIZE; y+=4) { bytes memory newRow = new bytes(uint256(SIZE)); uint8 gr = 0; for(x = 0; x < SIZE; x+=4) { gr += 3; bytes1 px = uint8(oldRow[x]) == 1 ? bytes1(uint8(1)) : bytes1(uint8(255-gr)); { uint yp1 = y + 1; uint yp2 = y + 2; uint xp1 = x + 1; uint xp2 = x + 2; pixels[y * SIZE + x ] = px; pixels[y * SIZE + xp1] = px; pixels[y * SIZE + xp2] = px; pixels[ yp1 * SIZE + x ] = px; pixels[ yp1 * SIZE + xp1] = px; pixels[ yp1 * SIZE + xp2] = px; pixels[ yp2 * SIZE + x ] = px; pixels[ yp2 * SIZE + xp1] = px; pixels[ yp2 * SIZE + xp2] = px; } uint8 combine; if(x == 0) { combine = (uint8(1) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } else if(x == SIZE - 4) { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(1) << 0); } else { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } uint8 nValue = ( uint8(rule) >> combine ) & 1; newRow[x] = nValue == 1 ? bytes1(uint8(1)) : bytes1(uint8(0)); } oldRow = newRow; } return pixels; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './BaseOpenSea.sol'; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; /// @title CAIC (Cellular Automaton In Chain) /// @author Tfs128 (@trickerfs128) /// @dev most of the code borrowed from [sol]Seedlings contract written by Simon Fremaux (@dievardump) contract CAIC is BaseOpenSea, ERC721Enumerable,Ownable,ReentrancyGuard { event SeedChangeRequest(uint256 indexed tokenId, address indexed operator); event Collected(address indexed operator, uint256 indexed count,uint256 value); event Claimed(address indexed operator); event SizeUpdated(uint32 size); // Last Token Id Generated. uint256 public LAST_TOKEN_ID; //public minting start time. uint256 public PUBLIC_MINTING_TIME = block.timestamp + 2 days; // 0.00768 uint256 public PRICE = 7680000000000000; // Max Available for mint `Available` - `Reserved` uint256 public AVAILABLE = 509; //509 // 257 reserved for blockglyphs holders + 2 for owner uint256 public BG_RESERVED_LEFT = 259; //259 // Max mints allowed in single transaction uint256 public MAX_MINT = 11; // Last Seed Generated bytes32 public LAST_SEED; // Size of image height:=SIZE, width:=SIZE uint32 public SIZE = 256; // each token seed mapping(uint256 => bytes32) internal _tokenSeed; // tokenIds with a request for seeds change mapping(uint256 => bool) private _seedChangeRequests; // blockGlyph holders mapping(address => bool) public _bgHolders; /// @notice constructor /// @param contractURI can be empty /// @param openseaProxyRegistry can be address zero constructor( string memory contractURI, address openseaProxyRegistry ) ERC721('CAIC', 'CAIC') { //CAIC (Cellular Automaton In Chain) if (bytes(contractURI).length > 0) { _setContractURI(contractURI); } if (address(0) != openseaProxyRegistry) { _setOpenSeaRegistry(openseaProxyRegistry); } } /// @notice function to mint `count` token(s) to `msg.sender` /// @param count numbers of tokens function mint(uint256 count) external payable nonReentrant { require (block.timestamp >= PUBLIC_MINTING_TIME, 'Wait'); require(count > 0, 'Must be greater than 0'); require(count <= MAX_MINT, 'More Than Max Allowed.' ); require(count <= AVAILABLE, 'Too Many Requested.'); require(msg.value == PRICE * count , 'Not Enough Amount.'); uint256 tokenId = LAST_TOKEN_ID; bytes32 blockHash = blockhash(block.number - 1); bytes32 nextSeed; for (uint256 i; i < count; i++) { tokenId++; _safeMint(msg.sender, tokenId); nextSeed = keccak256( abi.encodePacked( LAST_SEED, block.timestamp, msg.sender, blockHash, block.coinbase, block.difficulty, tx.gasprice ) ); LAST_SEED = nextSeed; _tokenSeed[tokenId] = nextSeed; } LAST_TOKEN_ID = tokenId; AVAILABLE -= count; emit Collected(msg.sender, count, msg.value); } /// @notice func for free token claim for blockglyph holders function claim() external { require (block.timestamp < PUBLIC_MINTING_TIME, 'You are late.'); require (_bgHolders[msg.sender] == true , 'Not a blockglphs holder or already claimed.'); uint256 tokenId = LAST_TOKEN_ID + 1; _safeMint(msg.sender, tokenId); bytes32 blockHash = blockhash(block.number - 1); bytes32 nextSeed = keccak256( abi.encodePacked( LAST_SEED, block.timestamp, msg.sender, blockHash, block.coinbase, block.difficulty, tx.gasprice ) ); LAST_TOKEN_ID = tokenId; LAST_SEED = nextSeed; BG_RESERVED_LEFT -= 1; _bgHolders[msg.sender] = false; emit Claimed(msg.sender); } /// @notice function to request seed change by token owner. /// @param tokenId of which seed change requested function requestSeedChange(uint256 tokenId) external { require(ownerOf(tokenId) == msg.sender, 'Not token owner.'); _seedChangeRequests[tokenId] = true; emit SeedChangeRequest(tokenId, msg.sender); } /// opensea config (https://docs.opensea.io/docs/contract-level-metadata) function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } ///@notice function to update image res ///@param imageSize height X width = 'imageSize * imageSize' function updateImageSize(uint32 imageSize) external onlyOwner { require(imageSize % 4 == 0, 'Should be a multiple of 4'); require(imageSize > 63 && imageSize < 257, 'Must be between 64-512'); SIZE = imageSize; emit SizeUpdated(imageSize); } /// @dev blockglyphs holders struct. struct bgHolderAddresses { address addr; bool available; } /// @notice function to add blockglyph holders + 2 owner reserved function addBgHolders(bgHolderAddresses[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _bgHolders[addresses[i].addr] = addresses[i].available; } } ///@notice function to respond to seed change requests ///@param tokenId of which seed needs to be change function changeSeedAfterRequest(uint256 tokenId) external onlyOwner { require(_seedChangeRequests[tokenId] == true, 'No request for token.'); _seedChangeRequests[tokenId] = false; _tokenSeed[tokenId] = keccak256( abi.encode( _tokenSeed[tokenId], block.timestamp, block.difficulty, blockhash(block.number - 1) ) ); } /// @notice function to withdraw balance. function withdraw() external onlyOwner { require(address(this).balance > 0, "0 Balance."); bool success; (success, ) = msg.sender.call{value: address(this).balance}(''); require(success, 'Failed'); } /// @notice this function returns the seed associated to a tokenId /// @param tokenId to get the seed of function getTokenSeed(uint256 tokenId) external view returns (bytes32) { require(_exists(tokenId), 'TokenSeed query for nonexistent token'); return _tokenSeed[tokenId]; } /// @notice function to get raw based64 encoded image /// @param tokenId id of token function getRaw(uint256 tokenId) public view returns (string memory) { require( _exists(tokenId), 'Query for nonexistent token' ); return _render(tokenId, _tokenSeed[tokenId],false); } /// @notice tokenURI override that returns a data:json application /// @inheritdoc ERC721 function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), 'ERC721Metadata: URI query for nonexistent token' ); return _render(tokenId, _tokenSeed[tokenId],true); } /// @notice Called with the sale price to determine how much royalty /// @param tokenId - the NFT asset queried for royalty information /// @param value - the sale price of the NFT asset specified by _tokenId /// @return receiver - address of who should be sent the royalty payment /// @return royaltyAmount - the royalty payment amount for value sale price function royaltyInfo(uint256 tokenId, uint256 value) public view returns (address receiver, uint256 royaltyAmount) { receiver = owner(); royaltyAmount = (value * 300) / 10000; } /// @notice Function allowing to check the rendering for a given seed /// @param seed the seed to render function renderSeed(bytes32 seed) public view returns (string memory) { return _render(1, seed, false); } /// @dev Rendering function; /// @param tokenId which needs to be render /// @param seed seed which needs to be render /// @param isSvg true=svg, false=base64 encoded function _render(uint256 tokenId, bytes32 seed, bool isSvg) internal view virtual returns (string memory) { seed; return string( abi.encodePacked( 'data:application/json,{"name":"', tokenId, '"}' ) ); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // small library to randomize using (min, max, seed, offsetBit etc...) library Randomize { struct Random { uint256 seed; uint256 offsetBit; } /// @notice get an random number between (min and max) using seed and offseting bits /// this function assumes that max is never bigger than 0xffffff (hex color with opacity included) /// @dev this function is simply used to get random number using a seed. /// if does bitshifting operations to try to reuse the same seed as much as possible. /// should be enough for anyth /// @param random the randomizer /// @param min the minimum /// @param max the maximum /// @return result the resulting pseudo random number function next( Random memory random, uint256 min, uint256 max ) internal pure returns (uint256 result) { uint256 newSeed = random.seed; uint256 newOffset = random.offsetBit + 3; uint256 maxOffset = 4; uint256 mask = 0xf; if (max > 0xfffff) { mask = 0xffffff; maxOffset = 24; } else if (max > 0xffff) { mask = 0xfffff; maxOffset = 20; } else if (max > 0xfff) { mask = 0xffff; maxOffset = 16; } else if (max > 0xff) { mask = 0xfff; maxOffset = 12; } else if (max > 0xf) { mask = 0xff; maxOffset = 8; } // if offsetBit is too high to get the max number // just get new seed and restart offset to 0 if (newOffset > (256 - maxOffset)) { newOffset = 0; newSeed = uint256(keccak256(abi.encode(newSeed))); } uint256 offseted = (newSeed >> newOffset); uint256 part = offseted & mask; result = min + (part % (max - min)); random.seed = newSeed; random.offsetBit = newOffset; } function nextInt( Random memory random, uint256 min, uint256 max ) internal pure returns (int256 result) { result = int256(Randomize.next(random, min, max)); } } // SPDX-License-Identifier: MIT // Copyright 2021 Arran Schlosberg / Twitter @divergence_art pragma solidity >=0.8.0 <0.9.0; /// @title IBMP interface /// @dev interface of BMP.sol originally used in brotchain (0xd31fc221d2b0e0321c43e9f6824b26ebfff01d7d) interface IBMP { /// @notice Returns an 8-bit grayscale palette for bitmap images. function grayscale() external pure returns (bytes memory); /// @notice Returns an 8-bit BMP encoding of the pixels. /// @param pixels bytes array of pixels /// @param width - /// @param height - /// @param palette bytes array function bmp(bytes memory pixels, uint32 width, uint32 height, bytes memory palette) external pure returns (bytes memory); /// @notice Returns the buffer, presumably from bmp(), as a base64 data URI. /// @param bmpBuf encoded bytes of pixels function bmpDataURI(bytes memory bmpBuf) external pure returns (string memory); /// @notice Scale pixels by repetition along both axes. /// @param pixels bytes array of pixels /// @param width - /// @param height - /// @param scale - function scalePixels(bytes memory pixels, uint32 width, uint32 height, uint32 scale) external pure returns (bytes memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title OpenSea contract helper that defines a few things /// @author Simon Fremaux (@dievardump) /// @dev This is a contract used to add OpenSea's support contract BaseOpenSea { string private _contractURI; ProxyRegistry private _proxyRegistry; /// @notice Returns the contract URI function. Used on OpenSea to get details // about a contract (owner, royalties etc...) function contractURI() public view returns (string memory) { return _contractURI; } /// @notice Helper for OpenSea gas-less trading /// @dev Allows to check if `operator` is owner's OpenSea proxy /// @param owner the owner we check for /// @param operator the operator (proxy) we check for function isOwnersOpenSeaProxy(address owner, address operator) public view returns (bool) { ProxyRegistry proxyRegistry = _proxyRegistry; return // we have a proxy registry address address(proxyRegistry) != address(0) && // current operator is owner's proxy address address(proxyRegistry.proxies(owner)) == operator; } /// @dev Internal function to set the _contractURI /// @param contractURI_ the new contract uri function _setContractURI(string memory contractURI_) internal { _contractURI = contractURI_; } /// @dev Internal function to set the _proxyRegistry /// @param proxyRegistryAddress the new proxy registry address function _setOpenSeaRegistry(address proxyRegistryAddress) internal { _proxyRegistry = ProxyRegistry(proxyRegistryAddress); } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "./extensions/IERC721Enumerable.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}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Gas eater function, to generate cells on grid rule CA rule 1-255 random to generate random initial row.
function getCells(uint256 rule, Randomize.Random memory random) internal view returns(bytes memory) { unchecked { bytes memory pixels = new bytes(uint256(SIZE * SIZE)); bytes memory oldRow = new bytes(SIZE); uint256 x; for(x=1; x < SIZE; x++) { uint256 random = random.next(1,255); oldRow[x] = random % 2 == 0 ? bytes1(uint8(1)) : bytes1(uint8(0)); } for(uint256 y=0; y< SIZE; y+=4) { bytes memory newRow = new bytes(uint256(SIZE)); uint8 gr = 0; for(x = 0; x < SIZE; x+=4) { gr += 3; bytes1 px = uint8(oldRow[x]) == 1 ? bytes1(uint8(1)) : bytes1(uint8(255-gr)); { uint yp1 = y + 1; uint yp2 = y + 2; uint xp1 = x + 1; uint xp2 = x + 2; pixels[y * SIZE + x ] = px; pixels[y * SIZE + xp1] = px; pixels[y * SIZE + xp2] = px; pixels[ yp1 * SIZE + x ] = px; pixels[ yp1 * SIZE + xp1] = px; pixels[ yp1 * SIZE + xp2] = px; pixels[ yp2 * SIZE + x ] = px; pixels[ yp2 * SIZE + xp1] = px; pixels[ yp2 * SIZE + xp2] = px; } uint8 combine; if(x == 0) { combine = (uint8(1) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } else if(x == SIZE - 4) { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(1) << 0); } else { combine = (uint8(oldRow[x-4]) << 2) + (uint8(oldRow[x]) << 1) + (uint8(oldRow[x+4]) << 0); } uint8 nValue = ( uint8(rule) >> combine ) & 1; newRow[x] = nValue == 1 ? bytes1(uint8(1)) : bytes1(uint8(0)); } oldRow = newRow; } return pixels; } }
534,035
./full_match/7700/0x759e390D946249c63e0A1d8a810C5A577a591719/sources/src/Pair.sol
this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock { require(!PairFactory(factory).isPaused()); (uint _reserve0, uint _reserve1) = (reserve0, reserve1); uint _balance0; uint _balance1; (address _token0, address _token1) = (token0, token1); _balance0 = IERC20(_token0).balanceOf(address(this)); _balance1 = IERC20(_token1).balanceOf(address(this)); } uint amount0In = _balance0 > _reserve0 - amount0Out ? _balance0 - (_reserve0 - amount0Out) : 0; uint amount1In = _balance1 > _reserve1 - amount1Out ? _balance1 - (_reserve1 - amount1Out) : 0; (address _token0, address _token1) = (token0, token1); _balance1 = IERC20(_token1).balanceOf(address(this));
4,660,067
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./SmartToken.sol"; import "./Math.sol"; import "./SafeMath.sol"; /** * @dev Extension of BEP20 to support voting and delegation. This version supports token supply up to 2 ** 96 - 1. * * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting * power can be queried through the public accessors {getVotes} and {getPastVotes}. * * By default, token balance does not account for voting power. This makes transfers cheaper. Acquiring vote power * requires token holders to delegate to themselves in order to activate checkpoints and have their voting power * tracked. */ contract VotingToken is SmartToken { using SafeMath for uint256; struct Checkpoint { uint32 fromBlock; uint96 votes; } struct Delegatee { address _delegatee; uint96 votes; } /// @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; mapping(address => Delegatee) private _delegates; mapping(address => Checkpoint[]) private _checkpoints; Checkpoint[] private _totalSupplyCheckpoints; /** * @dev Emitted when an account changes their delegate. */ event DelegateeChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /** * @dev Emitted when a token transfer or delegate change results in changes to an account's voting power. */ event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @dev Get the `pos`-th checkpoint for `account`. */ function checkpoints(address account, uint32 pos) public view returns (Checkpoint memory) { return _checkpoints[account][pos]; } /** * @dev Get number of checkpoints for `account`. */ function numCheckpoints(address account) public view returns (uint256) { return _checkpoints[account].length; } /** * @dev Get the address `account` is currently delegating to. */ function delegates(address account) public view returns (address) { return _delegates[account]._delegatee; } /** * @dev Gets the current votes balance for `account` */ function getVotes(address account) public view returns (uint96) { uint256 pos = _checkpoints[account].length; return pos == 0 ? 0 : _checkpoints[account][pos.sub(1)].votes; } /** * @dev Retrieve the number of votes for `account` at the end of `blockNumber`. * * Requirements: * * - `blockNumber` must have been already mined */ function getPastVotes(address account, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "BEP20Votes: block not yet mined"); return _checkpointsLookup(_checkpoints[account], blockNumber); } /** * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. * It is but NOT the sum of all the delegated votes! * * Requirements: * * - `blockNumber` must have been already mined */ function getPastTotalSupply(uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "BEP20Votes: block not yet mined"); return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber); } /** * @dev Lookup a value in a list of (sorted) checkpoints. */ function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint96) { // We run a binary search to look for the earliest checkpoint taken after `blockNumber`. // // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid) // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high) // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not // out of bounds (in which case we're looking too far in the past and the result is 0). // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out // the same. uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = Math.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else { low = mid.add(1); } } return high == 0 ? 0 : ckpts[high.sub(1)].votes; } /** * @dev Delegate votes from the sender to `delegatee`. */ function delegate(address delegatee) public { _delegate(_msgSender(), delegatee); } /** * @dev Remove previous delegatee and set it to zero address. After receiving more tokens, token owner needs to * delegates once more to update voting powers. If source and destination delegatee be the same (means token owner * wants to delegate the same address and update vote powers of the same address), voting powers will not be updated. * In such case, token owner should call resetDelegate function and then delegate to the address again. */ function resetDelegate() public { _delegate(_msgSender(), address(0)); } /** * @dev Delegates votes from signer to `delegatee` * @notice Delegates votes from signer 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 ) public { require(block.timestamp <= expiry, "BEP20Votes: signature expired"); 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 signer = ecrecover(digest, v, r, s); require(signer != address(0), "LQR::delegateBySig: invalid signature"); require(nonce == nonces[signer]++, "LQR::delegateBySig: invalid nonce"); return _delegate(signer, delegatee); } /** * @dev Maximum token supply is limited to 10 ** 10 units in order to avoid inflation and overflow in voting mechanism. */ function _maxSupply() internal pure returns (uint96) { return 10 ** 28; } /** * @dev Snapshots the totalSupply after it has been increased. */ function _mint(address account, uint256 amount) internal override { super._mint(account, amount); require(totalSupply() <= _maxSupply(), "BEP20Votes: total supply risks overflowing votes"); _writeCheckpoint(_totalSupplyCheckpoints, _add, amount); } /** * @dev Snapshots the totalSupply after it has been decreased. */ function _burn(address account, uint256 amount) internal override { super._burn(account, amount); if (delegates(account) != address(0)) { uint256 currentBalance = balanceOf(account); uint96 delegateeVotePower = _delegates[account].votes; if (currentBalance < delegateeVotePower) { uint256 diff = castTo256(delegateeVotePower).sub(currentBalance); _moveVotingPower(delegates(account), address(0), diff, currentBalance); _delegates[account].votes = safeCastTo96(currentBalance, "LQR::_writeCheckpoint: number exceeds 96 bits"); } } _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); } /** * @dev Move voting power when tokens are transferred. * * Emits a {DelegateVotesChanged} event. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal override { super._afterTokenTransfer(from, to, amount); if (delegates(from) != address(0)) { uint256 currentBalance = balanceOf(from); uint96 delegateeVotePower = _delegates[from].votes; if (currentBalance < delegateeVotePower) { uint256 diff = castTo256(delegateeVotePower).sub(currentBalance); _moveVotingPower(delegates(from), address(0), diff, currentBalance); _delegates[from].votes = safeCastTo96(currentBalance, "LQR::_writeCheckpoint: number exceeds 96 bits"); } } } /** * @dev Change delegation for `delegator` to `delegatee`. * * Emits events {DelegateeChanged} and {DelegateVotesChanged}. */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates(delegator); uint256 currentVotePower = castTo256(_delegates[delegator].votes); uint256 delegatorBalance = balanceOf(delegator); if (currentDelegate != delegatee) { _delegates[delegator]._delegatee = delegatee; _delegates[delegator].votes = delegatee == address(0) ? 0 : safeCastTo96(delegatorBalance, "LQR::_writeCheckpoint: number exceeds 96 bits"); emit DelegateeChanged(delegator, currentDelegate, delegatee); } _moveVotingPower(currentDelegate, delegatee, currentVotePower, delegatorBalance); } /** * @dev The function returns the chain id in which token contract */ function getChainId() internal view returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } function safeCastTo96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function safeCastTo32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function castTo256(uint96 n) internal pure returns (uint256) { return uint256(n); } function _moveVotingPower( address src, address dst, uint256 transferredVote, uint256 amount ) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, transferredVote); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function _writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; oldWeight = pos == 0 ? 0 : castTo256(ckpts[pos.sub(1)].votes); newWeight = op(oldWeight, delta); uint32 blockNumber = safeCastTo32(block.number, "LQR::_writeCheckpoint: block number exceeds 32 bits"); if (pos > 0 && ckpts[pos.sub(1)].fromBlock == blockNumber) { ckpts[pos.sub(1)].votes = safeCastTo96(newWeight, "LQR::_writeCheckpoint: number exceeds 96 bits"); } else { ckpts.push(Checkpoint({fromBlock: blockNumber, votes: safeCastTo96(newWeight, "LQR::_writeCheckpoint: number exceeds 96 bits")})); } } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } }
Change delegation for `delegator` to `delegatee`. Emits events {DelegateeChanged} and {DelegateVotesChanged}./
function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates(delegator); uint256 currentVotePower = castTo256(_delegates[delegator].votes); uint256 delegatorBalance = balanceOf(delegator); if (currentDelegate != delegatee) { _delegates[delegator]._delegatee = delegatee; _delegates[delegator].votes = delegatee == address(0) ? 0 : safeCastTo96(delegatorBalance, "LQR::_writeCheckpoint: number exceeds 96 bits"); emit DelegateeChanged(delegator, currentDelegate, delegatee); } _moveVotingPower(currentDelegate, delegatee, currentVotePower, delegatorBalance); }
5,537,679
pragma solidity ^0.5.0; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/ownership/Ownable.sol"; /// @title Factory Contract for creating Uniswap Market for Tokens /// @author Manank Patni /// @notice The contract creates a uniswap factory taking token as input and also add inital liquidity /// @dev Interface for ERC20 Token interface ERC20Interface { function totalSupply() external view returns (uint); function balanceOf(address tokenOwner) external view returns (uint balance); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function transfer(address to, uint tokens) external returns (bool success); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } /// @dev Interface for Uniswap Factory Contract interface UniswapFactoryInterface { function createExchange(address token) external returns (address exchange); function getExchange(address token) external view returns (address exchange); function getToken(address exchange) external view returns (address token); function getTokenWithId(uint256 tokenId) external view returns (address token); } /// @dev Interface for Uniswap Exchange Created interface UniswapExchangeInterface { function tokenAddress() external view returns (address token); function factoryAddress() external view returns (address factory); function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256); function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256); } /// @dev Main Factory contract with creation and liquidity logic contract ExchangeFactory is Ownable{ address public uniswapfactory; address public myexchange; address public erctoken; /// @dev Provide Uniswap Factory Contract on Deployment constructor(address _uniswapaddress) public { uniswapfactory = _uniswapaddress; } /// @dev Change Uniswap factory contract address. Only Owner can perform action. function change_factory(address _uniswapfactory) public onlyOwner returns(bool){ uniswapfactory = _uniswapfactory; return true; } /// @dev Get Exchange Address using the Token Address function getExchangefromToken(address _erctoken) public view returns(address) { address _exchange; UniswapFactoryInterface unifactory = UniswapFactoryInterface(uniswapfactory); _exchange = unifactory.getExchange(_erctoken); } /// @dev Generate exchange for the token given function create(address token) public returns(address) { UniswapFactoryInterface unifactory = UniswapFactoryInterface(uniswapfactory); erctoken = token; myexchange = unifactory.createExchange(token); return myexchange; } /// @dev Add initial liquidity to the exchange. Payable function. Token should be approved. function addliquidity(uint256 tokens) payable public { address self = address(this); ERC20Interface tokeninterface = ERC20Interface(erctoken); tokeninterface.approve(myexchange, 2**256 - 1); tokeninterface.transferFrom(msg.sender,self, tokens); UniswapExchangeInterface exchangeinter = UniswapExchangeInterface(myexchange); exchangeinter.addLiquidity.value(msg.value)(0, tokens, block.timestamp + 3000); } }
Change Uniswap factory contract address. Only Owner can perform action.
function change_factory(address _uniswapfactory) public onlyOwner returns(bool){ uniswapfactory = _uniswapfactory; return true; }
12,768,778
//Address: 0x6381947999a27896e4125ffba9160646dbe4accb //Contract name: UKTToken //Balance: 0 Ether //Verification Date: 5/31/2018 //Transacion Count: 75 // CODE STARTS HERE pragma solidity ^0.4.21; /** * @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 public potentialOwner; event OwnershipRemoved(address indexed previousOwner); event OwnershipTransfer(address indexed previousOwner, address indexed newOwner); 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 Throws if called by any account other than the owner. */ modifier onlyPotentialOwner() { require(msg.sender == potentialOwner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address of potential new owner to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransfer(owner, newOwner); potentialOwner = newOwner; } /** * @dev Allow the potential owner confirm ownership of the contract. */ function confirmOwnership() public onlyPotentialOwner { emit OwnershipTransferred(owner, potentialOwner); owner = potentialOwner; potentialOwner = address(0); } /** * @dev Remove the contract owner permanently */ function removeOwnership() public onlyOwner { emit OwnershipRemoved(owner); owner = address(0); } } /** * @title AddressTools * @dev Useful tools for address type */ library AddressTools { /** * @dev Returns true if given address is the contract address, otherwise - returns false */ function isContract(address a) internal view returns (bool) { if(a == address(0)) { return false; } uint codeSize; // solium-disable-next-line security/no-inline-assembly assembly { codeSize := extcodesize(a) } if(codeSize > 0) { return true; } return false; } } /** * @title Contract that will work with ERC223 tokens */ contract ERC223Reciever { /** * @dev Standard ERC223 function that will handle incoming token transfers * * @param _from address Token sender address * @param _value uint256 Amount of tokens * @param _data bytes Transaction metadata */ function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool); } /** * @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) { uint256 c = a / b; 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; } /** * @dev Powers the first number to the second, throws on overflow. */ function pow(uint a, uint b) internal pure returns (uint) { if (b == 0) { return 1; } uint c = a ** b; assert(c >= a); return c; } /** * @dev Multiplies the given number by 10**decimals */ function withDecimals(uint number, uint decimals) internal pure returns (uint) { return mul(number, pow(10, decimals)); } } /** * @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 Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) public balances; uint256 public totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(burner, _value); emit Transfer(burner, address(0), _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 Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title ERC223 interface * @dev see https://github.com/ethereum/EIPs/issues/223 */ contract ERC223 is ERC20 { function transfer(address to, uint256 value, bytes data) public returns (bool); event ERC223Transfer(address indexed from, address indexed to, uint256 value, bytes data); } /** * @title (Not)Reference implementation of the ERC223 standard token. */ contract ERC223Token is ERC223, StandardToken { using AddressTools for address; /** * @dev Transfer the specified amount of tokens to the specified address. * Invokes the `tokenFallback` function if the recipient is a contract. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallback` function * or the fallback function to receive funds. * * @param _to Receiver address * @param _value Amount of tokens that will be transferred * @param _data Transaction metadata */ function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { return executeTransfer(_to, _value, _data); } /** * @dev Transfer the specified amount of tokens to the specified address. * This function works the same with the previous one * but doesn"t contain `_data` param. * Added due to backwards compatibility reasons. * * @param _to Receiver address * @param _value Amount of tokens that will be transferred */ function transfer(address _to, uint256 _value) public returns (bool) { bytes memory _data; return executeTransfer(_to, _value, _data); } /** * @dev Makes execution of the token fallback method from if reciever address is contract */ function executeTokenFallback(address _to, uint256 _value, bytes _data) private returns (bool) { ERC223Reciever receiver = ERC223Reciever(_to); return receiver.tokenFallback(msg.sender, _value, _data); } /** * @dev Makes execution of the tokens transfer method from super class */ function executeTransfer(address _to, uint256 _value, bytes _data) private returns (bool) { require(super.transfer(_to, _value)); if(_to.isContract()) { require(executeTokenFallback(_to, _value, _data)); emit ERC223Transfer(msg.sender, _to, _value, _data); } return true; } } /** * @title UKTTokenBasic * @dev UKTTokenBasic interface */ contract UKTTokenBasic is ERC223, BurnableToken { bool public isControlled = false; bool public isConfigured = false; bool public isAllocated = false; // mapping of string labels to initial allocated addresses mapping(bytes32 => address) public allocationAddressesTypes; // mapping of addresses to time lock period mapping(address => uint32) public timelockedAddresses; // mapping of addresses to lock flag mapping(address => bool) public lockedAddresses; function setConfiguration(string _name, string _symbol, uint _totalSupply) external returns (bool); function setInitialAllocation(address[] addresses, bytes32[] addressesTypes, uint[] amounts) external returns (bool); function setInitialAllocationLock(address allocationAddress ) external returns (bool); function setInitialAllocationUnlock(address allocationAddress ) external returns (bool); function setInitialAllocationTimelock(address allocationAddress, uint32 timelockTillDate ) external returns (bool); // fires when the token contract becomes controlled event Controlled(address indexed tokenController); // fires when the token contract becomes configured event Configured(string tokenName, string tokenSymbol, uint totalSupply); event InitiallyAllocated(address indexed owner, bytes32 addressType, uint balance); event InitiallAllocationLocked(address indexed owner); event InitiallAllocationUnlocked(address indexed owner); event InitiallAllocationTimelocked(address indexed owner, uint32 timestamp); } /** * @title Basic UKT token contract * @author Oleg Levshin <[email protected]> */ contract UKTToken is UKTTokenBasic, ERC223Token, Ownable { using AddressTools for address; string public name; string public symbol; uint public constant decimals = 18; // address of the controller contract address public controller; modifier onlyController() { require(msg.sender == controller); _; } modifier onlyUnlocked(address _address) { address from = _address != address(0) ? _address : msg.sender; require( lockedAddresses[from] == false && ( timelockedAddresses[from] == 0 || timelockedAddresses[from] <= now ) ); _; } /** * @dev Sets the controller contract address and removes token contract ownership */ function setController( address _controller ) public onlyOwner { // cannot be invoked after initial setting require(!isControlled); // _controller should be an address of the smart contract require(_controller.isContract()); controller = _controller; removeOwnership(); emit Controlled(controller); isControlled = true; } /** * @dev Sets the token contract configuration */ function setConfiguration( string _name, string _symbol, uint _totalSupply ) external onlyController returns (bool) { // not configured yet require(!isConfigured); // not empty name of the token require(bytes(_name).length > 0); // not empty ticker symbol of the token require(bytes(_symbol).length > 0); // pre-defined total supply require(_totalSupply > 0); name = _name; symbol = _symbol; totalSupply_ = _totalSupply.withDecimals(decimals); emit Configured(name, symbol, totalSupply_); isConfigured = true; return isConfigured; } /** * @dev Sets initial balances allocation */ function setInitialAllocation( address[] addresses, bytes32[] addressesTypes, uint[] amounts ) external onlyController returns (bool) { // cannot be invoked after initial allocation require(!isAllocated); // the array of addresses should be the same length as the array of addresses types require(addresses.length == addressesTypes.length); // the array of addresses should be the same length as the array of allocating amounts require(addresses.length == amounts.length); // sum of the allocating balances should be equal to totalSupply uint balancesSum = 0; for(uint b = 0; b < amounts.length; b++) { balancesSum = balancesSum.add(amounts[b]); } require(balancesSum.withDecimals(decimals) == totalSupply_); for(uint a = 0; a < addresses.length; a++) { balances[addresses[a]] = amounts[a].withDecimals(decimals); allocationAddressesTypes[addressesTypes[a]] = addresses[a]; emit InitiallyAllocated(addresses[a], addressesTypes[a], balanceOf(addresses[a])); } isAllocated = true; return isAllocated; } /** * @dev Sets lock for given allocation address */ function setInitialAllocationLock( address allocationAddress ) external onlyController returns (bool) { require(allocationAddress != address(0)); lockedAddresses[allocationAddress] = true; emit InitiallAllocationLocked(allocationAddress); return true; } /** * @dev Sets unlock for given allocation address */ function setInitialAllocationUnlock( address allocationAddress ) external onlyController returns (bool) { require(allocationAddress != address(0)); lockedAddresses[allocationAddress] = false; emit InitiallAllocationUnlocked(allocationAddress); return true; } /** * @dev Sets time lock for given allocation address */ function setInitialAllocationTimelock( address allocationAddress, uint32 timelockTillDate ) external onlyController returns (bool) { require(allocationAddress != address(0)); require(timelockTillDate >= now); timelockedAddresses[allocationAddress] = timelockTillDate; emit InitiallAllocationTimelocked(allocationAddress, timelockTillDate); return true; } /** * @dev Allows transfer of the tokens after locking conditions checking */ function transfer( address _to, uint256 _value ) public onlyUnlocked(address(0)) returns (bool) { require(super.transfer(_to, _value)); return true; } /** * @dev Allows transfer of the tokens (with additional _data) after locking conditions checking */ function transfer( address _to, uint256 _value, bytes _data ) public onlyUnlocked(address(0)) returns (bool) { require(super.transfer(_to, _value, _data)); return true; } /** * @dev Allows transfer of the tokens after locking conditions checking */ function transferFrom( address _from, address _to, uint256 _value ) public onlyUnlocked(_from) returns (bool) { require(super.transferFrom(_from, _to, _value)); return true; } }
Allows transfer of the tokens after locking conditions checking/
function transferFrom( address _from, address _to, uint256 _value ) public onlyUnlocked(_from) returns (bool) { require(super.transferFrom(_from, _to, _value)); return true; }
1,774,878
pragma solidity 0.4.20; contract IAugur { function createChildUniverse(bytes32 _parentPayoutDistributionHash, uint256[] _parentPayoutNumerators, bool _parentInvalid) public returns (IUniverse); function isKnownUniverse(IUniverse _universe) public view returns (bool); function trustedTransfer(ERC20 _token, address _from, address _to, uint256 _amount) public returns (bool); function logMarketCreated(bytes32 _topic, string _description, string _extraInfo, IUniverse _universe, address _market, address _marketCreator, bytes32[] _outcomes, int256 _minPrice, int256 _maxPrice, IMarket.MarketType _marketType) public returns (bool); function logMarketCreated(bytes32 _topic, string _description, string _extraInfo, IUniverse _universe, address _market, address _marketCreator, int256 _minPrice, int256 _maxPrice, IMarket.MarketType _marketType) public returns (bool); function logInitialReportSubmitted(IUniverse _universe, address _reporter, address _market, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] _payoutNumerators, bool _invalid) public returns (bool); function disputeCrowdsourcerCreated(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] _payoutNumerators, uint256 _size, bool _invalid) public returns (bool); function logDisputeCrowdsourcerContribution(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked) public returns (bool); function logDisputeCrowdsourcerCompleted(IUniverse _universe, address _market, address _disputeCrowdsourcer) public returns (bool); function logInitialReporterRedeemed(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256 _reportingFeesReceived, uint256[] _payoutNumerators) public returns (bool); function logDisputeCrowdsourcerRedeemed(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256 _reportingFeesReceived, uint256[] _payoutNumerators) public returns (bool); function logFeeWindowRedeemed(IUniverse _universe, address _reporter, uint256 _amountRedeemed, uint256 _reportingFeesReceived) public returns (bool); function logMarketFinalized(IUniverse _universe) public returns (bool); function logMarketMigrated(IMarket _market, IUniverse _originalUniverse) public returns (bool); function logReportingParticipantDisavowed(IUniverse _universe, IMarket _market) public returns (bool); function logMarketParticipantsDisavowed(IUniverse _universe) public returns (bool); function logOrderCanceled(IUniverse _universe, address _shareToken, address _sender, bytes32 _orderId, Order.Types _orderType, uint256 _tokenRefund, uint256 _sharesRefund) public returns (bool); function logOrderCreated(Order.Types _orderType, uint256 _amount, uint256 _price, address _creator, uint256 _moneyEscrowed, uint256 _sharesEscrowed, bytes32 _tradeGroupId, bytes32 _orderId, IUniverse _universe, address _shareToken) public returns (bool); function logOrderFilled(IUniverse _universe, address _shareToken, address _filler, bytes32 _orderId, uint256 _numCreatorShares, uint256 _numCreatorTokens, uint256 _numFillerShares, uint256 _numFillerTokens, uint256 _marketCreatorFees, uint256 _reporterFees, uint256 _amountFilled, bytes32 _tradeGroupId) public returns (bool); function logCompleteSetsPurchased(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool); function logCompleteSetsSold(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool); function logTradingProceedsClaimed(IUniverse _universe, address _shareToken, address _sender, address _market, uint256 _numShares, uint256 _numPayoutTokens, uint256 _finalTokenBalance) public returns (bool); function logUniverseForked() public returns (bool); function logFeeWindowTransferred(IUniverse _universe, address _from, address _to, uint256 _value) public returns (bool); function logReputationTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value) public returns (bool); function logDisputeCrowdsourcerTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value) public returns (bool); function logShareTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value) public returns (bool); function logReputationTokenBurned(IUniverse _universe, address _target, uint256 _amount) public returns (bool); function logReputationTokenMinted(IUniverse _universe, address _target, uint256 _amount) public returns (bool); function logShareTokenBurned(IUniverse _universe, address _target, uint256 _amount) public returns (bool); function logShareTokenMinted(IUniverse _universe, address _target, uint256 _amount) public returns (bool); function logFeeWindowBurned(IUniverse _universe, address _target, uint256 _amount) public returns (bool); function logFeeWindowMinted(IUniverse _universe, address _target, uint256 _amount) public returns (bool); function logDisputeCrowdsourcerTokensBurned(IUniverse _universe, address _target, uint256 _amount) public returns (bool); function logDisputeCrowdsourcerTokensMinted(IUniverse _universe, address _target, uint256 _amount) public returns (bool); function logFeeWindowCreated(IFeeWindow _feeWindow, uint256 _id) public returns (bool); function logFeeTokenTransferred(IUniverse _universe, address _from, address _to, uint256 _value) public returns (bool); function logFeeTokenBurned(IUniverse _universe, address _target, uint256 _amount) public returns (bool); function logFeeTokenMinted(IUniverse _universe, address _target, uint256 _amount) public returns (bool); function logTimestampSet(uint256 _newTimestamp) public returns (bool); function logInitialReporterTransferred(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool); function logMarketTransferred(IUniverse _universe, address _from, address _to) public returns (bool); function logMarketMailboxTransferred(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool); function logEscapeHatchChanged(bool _isOn) public returns (bool); } contract IControlled { function getController() public view returns (IController); function setController(IController _controller) public returns(bool); } contract Controlled is IControlled { IController internal controller; modifier onlyWhitelistedCallers { require(controller.assertIsWhitelisted(msg.sender)); _; } modifier onlyCaller(bytes32 _key) { require(msg.sender == controller.lookup(_key)); _; } modifier onlyControllerCaller { require(IController(msg.sender) == controller); _; } modifier onlyInGoodTimes { require(controller.stopInEmergency()); _; } modifier onlyInBadTimes { require(controller.onlyInEmergency()); _; } function Controlled() public { controller = IController(msg.sender); } function getController() public view returns(IController) { return controller; } function setController(IController _controller) public onlyControllerCaller returns(bool) { controller = _controller; return true; } } contract IController { function assertIsWhitelisted(address _target) public view returns(bool); function lookup(bytes32 _key) public view returns(address); function stopInEmergency() public view returns(bool); function onlyInEmergency() public view returns(bool); function getAugur() public view returns (IAugur); function getTimestamp() public view returns (uint256); } contract CashAutoConverter is Controlled { /** * @dev Convert any ETH provided in the transaction into Cash before the function executes and convert any remaining Cash balance into ETH after the function completes */ modifier convertToAndFromCash() { ethToCash(); _; cashToEth(); } function ethToCash() private returns (bool) { if (msg.value > 0) { ICash(controller.lookup("Cash")).depositEtherFor.value(msg.value)(msg.sender); } return true; } function cashToEth() private returns (bool) { ICash _cash = ICash(controller.lookup("Cash")); uint256 _tokenBalance = _cash.balanceOf(msg.sender); if (_tokenBalance > 0) { IAugur augur = controller.getAugur(); augur.trustedTransfer(_cash, msg.sender, this, _tokenBalance); _cash.withdrawEtherTo(msg.sender, _tokenBalance); } return true; } } contract IOwnable { function getOwner() public view returns (address); function transferOwnership(address newOwner) public returns (bool); } contract ITyped { function getTypeName() public view returns (bytes32); } contract Initializable { bool private initialized = false; modifier afterInitialized { require(initialized); _; } modifier beforeInitialized { require(!initialized); _; } function endInitialization() internal beforeInitialized returns (bool) { initialized = true; return true; } function getInitialized() public view returns (bool) { return initialized; } } contract MarketValidator is Controlled { modifier marketIsLegit(IMarket _market) { IUniverse _universe = _market.getUniverse(); require(controller.getAugur().isKnownUniverse(_universe)); require(_universe.isContainerForMarket(_market)); _; } } contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private rentrancyLock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also mark it `external`. Calling one nonReentrant function from another is not supported. Instead, you can implement a `private` function doing the actual work, and a `external` wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!rentrancyLock); rentrancyLock = true; _; rentrancyLock = false; } } library SafeMathUint256 { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(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) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a <= b) { return a; } else { return b; } } function max(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a; } else { return b; } } function getUint256Min() internal pure returns (uint256) { return 0; } function getUint256Max() internal pure returns (uint256) { return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; } function isMultipleOf(uint256 a, uint256 b) internal pure returns (bool) { return a % b == 0; } // Float [fixed point] Operations function fxpMul(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { return div(mul(a, b), base); } function fxpDiv(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { return div(mul(a, base), b); } } contract ERC20Basic { event Transfer(address indexed from, address indexed to, uint256 value); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function totalSupply() public view returns (uint256); } contract ERC20 is ERC20Basic { event Approval(address indexed owner, address indexed spender, uint256 value); 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); } contract IFeeToken is ERC20, Initializable { function initialize(IFeeWindow _feeWindow) public returns (bool); function getFeeWindow() public view returns (IFeeWindow); function feeWindowBurn(address _target, uint256 _amount) public returns (bool); function mintForReportingParticipant(address _target, uint256 _amount) public returns (bool); } contract IFeeWindow is ITyped, ERC20 { function initialize(IUniverse _universe, uint256 _feeWindowId) public returns (bool); function getUniverse() public view returns (IUniverse); function getReputationToken() public view returns (IReputationToken); function getStartTime() public view returns (uint256); function getEndTime() public view returns (uint256); function getNumMarkets() public view returns (uint256); function getNumInvalidMarkets() public view returns (uint256); function getNumIncorrectDesignatedReportMarkets() public view returns (uint256); function getNumDesignatedReportNoShows() public view returns (uint256); function getFeeToken() public view returns (IFeeToken); function isActive() public view returns (bool); function isOver() public view returns (bool); function onMarketFinalized() public returns (bool); function buy(uint256 _attotokens) public returns (bool); function redeem(address _sender) public returns (bool); function redeemForReportingParticipant() public returns (bool); function mintFeeTokens(uint256 _amount) public returns (bool); function trustedUniverseBuy(address _buyer, uint256 _attotokens) public returns (bool); } contract IMailbox { function initialize(address _owner, IMarket _market) public returns (bool); function depositEther() public payable returns (bool); } contract IMarket is ITyped, IOwnable { enum MarketType { YES_NO, CATEGORICAL, SCALAR } function initialize(IUniverse _universe, uint256 _endTime, uint256 _feePerEthInAttoeth, ICash _cash, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public payable returns (bool _success); function derivePayoutDistributionHash(uint256[] _payoutNumerators, bool _invalid) public view returns (bytes32); function getUniverse() public view returns (IUniverse); function getFeeWindow() public view returns (IFeeWindow); function getNumberOfOutcomes() public view returns (uint256); function getNumTicks() public view returns (uint256); function getDenominationToken() public view returns (ICash); function getShareToken(uint256 _outcome) public view returns (IShareToken); function getMarketCreatorSettlementFeeDivisor() public view returns (uint256); function getForkingMarket() public view returns (IMarket _market); function getEndTime() public view returns (uint256); function getMarketCreatorMailbox() public view returns (IMailbox); function getWinningPayoutDistributionHash() public view returns (bytes32); function getWinningPayoutNumerator(uint256 _outcome) public view returns (uint256); function getReputationToken() public view returns (IReputationToken); function getFinalizationTime() public view returns (uint256); function getInitialReporterAddress() public view returns (address); function deriveMarketCreatorFeeAmount(uint256 _amount) public view returns (uint256); function isContainerForShareToken(IShareToken _shadyTarget) public view returns (bool); function isContainerForReportingParticipant(IReportingParticipant _reportingParticipant) public view returns (bool); function isInvalid() public view returns (bool); function finalize() public returns (bool); function designatedReporterWasCorrect() public view returns (bool); function designatedReporterShowed() public view returns (bool); function isFinalized() public view returns (bool); function finalizeFork() public returns (bool); function assertBalances() public view returns (bool); } contract IReportingParticipant { function getStake() public view returns (uint256); function getPayoutDistributionHash() public view returns (bytes32); function liquidateLosing() public returns (bool); function redeem(address _redeemer) public returns (bool); function isInvalid() public view returns (bool); function isDisavowed() public view returns (bool); function migrate() public returns (bool); function getPayoutNumerator(uint256 _outcome) public view returns (uint256); function getMarket() public view returns (IMarket); function getSize() public view returns (uint256); } contract IDisputeCrowdsourcer is IReportingParticipant, ERC20 { function initialize(IMarket market, uint256 _size, bytes32 _payoutDistributionHash, uint256[] _payoutNumerators, bool _invalid) public returns (bool); function contribute(address _participant, uint256 _amount) public returns (uint256); } contract IReputationToken is ITyped, ERC20 { function initialize(IUniverse _universe) public returns (bool); function migrateOut(IReputationToken _destination, uint256 _attotokens) public returns (bool); function migrateIn(address _reporter, uint256 _attotokens) public returns (bool); function trustedReportingParticipantTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function trustedMarketTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function trustedFeeWindowTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function trustedUniverseTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function getUniverse() public view returns (IUniverse); function getTotalMigrated() public view returns (uint256); function getTotalTheoreticalSupply() public view returns (uint256); function mintForReportingParticipant(uint256 _amountMigrated) public returns (bool); } contract IUniverse is ITyped { function initialize(IUniverse _parentUniverse, bytes32 _parentPayoutDistributionHash) external returns (bool); function fork() public returns (bool); function getParentUniverse() public view returns (IUniverse); function createChildUniverse(uint256[] _parentPayoutNumerators, bool _invalid) public returns (IUniverse); function getChildUniverse(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse); function getReputationToken() public view returns (IReputationToken); function getForkingMarket() public view returns (IMarket); function getForkEndTime() public view returns (uint256); function getForkReputationGoal() public view returns (uint256); function getParentPayoutDistributionHash() public view returns (bytes32); function getDisputeRoundDurationInSeconds() public view returns (uint256); function getOrCreateFeeWindowByTimestamp(uint256 _timestamp) public returns (IFeeWindow); function getOrCreateCurrentFeeWindow() public returns (IFeeWindow); function getOrCreateNextFeeWindow() public returns (IFeeWindow); function getOpenInterestInAttoEth() public view returns (uint256); function getRepMarketCapInAttoeth() public view returns (uint256); function getTargetRepMarketCapInAttoeth() public view returns (uint256); function getOrCacheValidityBond() public returns (uint256); function getOrCacheDesignatedReportStake() public returns (uint256); function getOrCacheDesignatedReportNoShowBond() public returns (uint256); function getOrCacheReportingFeeDivisor() public returns (uint256); function getDisputeThresholdForFork() public view returns (uint256); function getInitialReportMinValue() public view returns (uint256); function calculateFloatingValue(uint256 _badMarkets, uint256 _totalMarkets, uint256 _targetDivisor, uint256 _previousValue, uint256 _defaultValue, uint256 _floor) public pure returns (uint256 _newValue); function getOrCacheMarketCreationCost() public returns (uint256); function getCurrentFeeWindow() public view returns (IFeeWindow); function getOrCreateFeeWindowBefore(IFeeWindow _feeWindow) public returns (IFeeWindow); function isParentOf(IUniverse _shadyChild) public view returns (bool); function updateTentativeWinningChildUniverse(bytes32 _parentPayoutDistributionHash) public returns (bool); function isContainerForFeeWindow(IFeeWindow _shadyTarget) public view returns (bool); function isContainerForMarket(IMarket _shadyTarget) public view returns (bool); function isContainerForReportingParticipant(IReportingParticipant _reportingParticipant) public view returns (bool); function isContainerForShareToken(IShareToken _shadyTarget) public view returns (bool); function isContainerForFeeToken(IFeeToken _shadyTarget) public view returns (bool); function addMarketTo() public returns (bool); function removeMarketFrom() public returns (bool); function decrementOpenInterest(uint256 _amount) public returns (bool); function decrementOpenInterestFromMarket(uint256 _amount) public returns (bool); function incrementOpenInterest(uint256 _amount) public returns (bool); function incrementOpenInterestFromMarket(uint256 _amount) public returns (bool); function getWinningChildUniverse() public view returns (IUniverse); function isForking() public view returns (bool); } contract ICash is ERC20 { function depositEther() external payable returns(bool); function depositEtherFor(address _to) external payable returns(bool); function withdrawEther(uint256 _amount) external returns(bool); function withdrawEtherTo(address _to, uint256 _amount) external returns(bool); function withdrawEtherToIfPossible(address _to, uint256 _amount) external returns (bool); } contract ICompleteSets { function buyCompleteSets(address _sender, IMarket _market, uint256 _amount) external returns (bool); function sellCompleteSets(address _sender, IMarket _market, uint256 _amount) external returns (uint256, uint256); } contract CompleteSets is Controlled, CashAutoConverter, ReentrancyGuard, MarketValidator, ICompleteSets { using SafeMathUint256 for uint256; /** * Buys `_amount` shares of every outcome in the specified market. **/ function publicBuyCompleteSets(IMarket _market, uint256 _amount) external marketIsLegit(_market) payable convertToAndFromCash onlyInGoodTimes returns (bool) { this.buyCompleteSets(msg.sender, _market, _amount); controller.getAugur().logCompleteSetsPurchased(_market.getUniverse(), _market, msg.sender, _amount); _market.assertBalances(); return true; } function publicBuyCompleteSetsWithCash(IMarket _market, uint256 _amount) external marketIsLegit(_market) onlyInGoodTimes returns (bool) { this.buyCompleteSets(msg.sender, _market, _amount); controller.getAugur().logCompleteSetsPurchased(_market.getUniverse(), _market, msg.sender, _amount); _market.assertBalances(); return true; } function buyCompleteSets(address _sender, IMarket _market, uint256 _amount) external onlyWhitelistedCallers nonReentrant returns (bool) { require(_sender != address(0)); uint256 _numOutcomes = _market.getNumberOfOutcomes(); ICash _denominationToken = _market.getDenominationToken(); IAugur _augur = controller.getAugur(); uint256 _cost = _amount.mul(_market.getNumTicks()); require(_augur.trustedTransfer(_denominationToken, _sender, _market, _cost)); for (uint256 _outcome = 0; _outcome < _numOutcomes; ++_outcome) { _market.getShareToken(_outcome).createShares(_sender, _amount); } if (!_market.isFinalized()) { _market.getUniverse().incrementOpenInterest(_cost); } return true; } function publicSellCompleteSets(IMarket _market, uint256 _amount) external marketIsLegit(_market) convertToAndFromCash onlyInGoodTimes returns (bool) { this.sellCompleteSets(msg.sender, _market, _amount); controller.getAugur().logCompleteSetsSold(_market.getUniverse(), _market, msg.sender, _amount); _market.assertBalances(); return true; } function publicSellCompleteSetsWithCash(IMarket _market, uint256 _amount) external marketIsLegit(_market) onlyInGoodTimes returns (bool) { this.sellCompleteSets(msg.sender, _market, _amount); controller.getAugur().logCompleteSetsSold(_market.getUniverse(), _market, msg.sender, _amount); _market.assertBalances(); return true; } function sellCompleteSets(address _sender, IMarket _market, uint256 _amount) external onlyWhitelistedCallers nonReentrant returns (uint256 _creatorFee, uint256 _reportingFee) { require(_sender != address(0)); uint256 _numOutcomes = _market.getNumberOfOutcomes(); ICash _denominationToken = _market.getDenominationToken(); uint256 _payout = _amount.mul(_market.getNumTicks()); if (!_market.isFinalized()) { _market.getUniverse().decrementOpenInterest(_payout); } _creatorFee = _market.deriveMarketCreatorFeeAmount(_payout); uint256 _reportingFeeDivisor = _market.getUniverse().getOrCacheReportingFeeDivisor(); _reportingFee = _payout.div(_reportingFeeDivisor); _payout = _payout.sub(_creatorFee).sub(_reportingFee); // Takes shares away from participant and decreases the amount issued in the market since we're exchanging complete sets for (uint256 _outcome = 0; _outcome < _numOutcomes; ++_outcome) { _market.getShareToken(_outcome).destroyShares(_sender, _amount); } if (_creatorFee != 0) { require(_denominationToken.transferFrom(_market, _market.getMarketCreatorMailbox(), _creatorFee)); } if (_reportingFee != 0) { IFeeWindow _feeWindow = _market.getUniverse().getOrCreateNextFeeWindow(); require(_denominationToken.transferFrom(_market, _feeWindow, _reportingFee)); } require(_denominationToken.transferFrom(_market, _sender, _payout)); return (_creatorFee, _reportingFee); } } contract IOrders { function saveOrder(Order.Types _type, IMarket _market, uint256 _fxpAmount, uint256 _price, address _sender, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed, bytes32 _betterOrderId, bytes32 _worseOrderId, bytes32 _tradeGroupId) public returns (bytes32 _orderId); function removeOrder(bytes32 _orderId) public returns (bool); function getMarket(bytes32 _orderId) public view returns (IMarket); function getOrderType(bytes32 _orderId) public view returns (Order.Types); function getOutcome(bytes32 _orderId) public view returns (uint256); function getAmount(bytes32 _orderId) public view returns (uint256); function getPrice(bytes32 _orderId) public view returns (uint256); function getOrderCreator(bytes32 _orderId) public view returns (address); function getOrderSharesEscrowed(bytes32 _orderId) public view returns (uint256); function getOrderMoneyEscrowed(bytes32 _orderId) public view returns (uint256); function getBetterOrderId(bytes32 _orderId) public view returns (bytes32); function getWorseOrderId(bytes32 _orderId) public view returns (bytes32); function getBestOrderId(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); function getWorstOrderId(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); function getLastOutcomePrice(IMarket _market, uint256 _outcome) public view returns (uint256); function getOrderId(Order.Types _type, IMarket _market, uint256 _fxpAmount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) public pure returns (bytes32); function getTotalEscrowed(IMarket _market) public view returns (uint256); function isBetterPrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); function isWorsePrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); function assertIsNotBetterPrice(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool); function assertIsNotWorsePrice(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool); function recordFillOrder(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled) public returns (bool); function setPrice(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool); function incrementTotalEscrowed(IMarket _market, uint256 _amount) external returns (bool); function decrementTotalEscrowed(IMarket _market, uint256 _amount) external returns (bool); } contract IShareToken is ITyped, ERC20 { function initialize(IMarket _market, uint256 _outcome) external returns (bool); function createShares(address _owner, uint256 _amount) external returns (bool); function destroyShares(address, uint256 balance) external returns (bool); function getMarket() external view returns (IMarket); function getOutcome() external view returns (uint256); function trustedOrderTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function trustedFillOrderTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function trustedCancelOrderTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); } library Order { using SafeMathUint256 for uint256; enum Types { Bid, Ask } enum TradeDirections { Long, Short } struct Data { // Contracts IOrders orders; IMarket market; IAugur augur; // Order bytes32 id; address creator; uint256 outcome; Order.Types orderType; uint256 amount; uint256 price; uint256 sharesEscrowed; uint256 moneyEscrowed; bytes32 betterOrderId; bytes32 worseOrderId; } // // Constructor // // No validation is needed here as it is simply a librarty function for organizing data function create(IController _controller, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data) { require(_outcome < _market.getNumberOfOutcomes()); require(_price < _market.getNumTicks()); IOrders _orders = IOrders(_controller.lookup("Orders")); IAugur _augur = _controller.getAugur(); return Data({ orders: _orders, market: _market, augur: _augur, id: 0, creator: _creator, outcome: _outcome, orderType: _type, amount: _attoshares, price: _price, sharesEscrowed: 0, moneyEscrowed: 0, betterOrderId: _betterOrderId, worseOrderId: _worseOrderId }); } // // "public" functions // function getOrderId(Order.Data _orderData) internal view returns (bytes32) { if (_orderData.id == bytes32(0)) { bytes32 _orderId = _orderData.orders.getOrderId(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed); require(_orderData.orders.getAmount(_orderId) == 0); _orderData.id = _orderId; } return _orderData.id; } function getOrderTradingTypeFromMakerDirection(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) { return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask; } function getOrderTradingTypeFromFillerDirection(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) { return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid; } function escrowFunds(Order.Data _orderData) internal returns (bool) { if (_orderData.orderType == Order.Types.Ask) { return escrowFundsForAsk(_orderData); } else if (_orderData.orderType == Order.Types.Bid) { return escrowFundsForBid(_orderData); } } function saveOrder(Order.Data _orderData, bytes32 _tradeGroupId) internal returns (bytes32) { return _orderData.orders.saveOrder(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed, _orderData.betterOrderId, _orderData.worseOrderId, _tradeGroupId); } // // Private functions // function escrowFundsForBid(Order.Data _orderData) private returns (bool) { require(_orderData.moneyEscrowed == 0); require(_orderData.sharesEscrowed == 0); uint256 _attosharesToCover = _orderData.amount; uint256 _numberOfOutcomes = _orderData.market.getNumberOfOutcomes(); // Figure out how many almost-complete-sets (just missing `outcome` share) the creator has uint256 _attosharesHeld = 2**254; for (uint256 _i = 0; _i < _numberOfOutcomes; _i++) { if (_i != _orderData.outcome) { uint256 _creatorShareTokenBalance = _orderData.market.getShareToken(_i).balanceOf(_orderData.creator); _attosharesHeld = SafeMathUint256.min(_creatorShareTokenBalance, _attosharesHeld); } } // Take shares into escrow if they have any almost-complete-sets if (_attosharesHeld > 0) { _orderData.sharesEscrowed = SafeMathUint256.min(_attosharesHeld, _attosharesToCover); _attosharesToCover -= _orderData.sharesEscrowed; for (_i = 0; _i < _numberOfOutcomes; _i++) { if (_i != _orderData.outcome) { _orderData.market.getShareToken(_i).trustedOrderTransfer(_orderData.creator, _orderData.market, _orderData.sharesEscrowed); } } } // If not able to cover entire order with shares alone, then cover remaining with tokens if (_attosharesToCover > 0) { _orderData.moneyEscrowed = _attosharesToCover.mul(_orderData.price); require(_orderData.augur.trustedTransfer(_orderData.market.getDenominationToken(), _orderData.creator, _orderData.market, _orderData.moneyEscrowed)); } return true; } function escrowFundsForAsk(Order.Data _orderData) private returns (bool) { require(_orderData.moneyEscrowed == 0); require(_orderData.sharesEscrowed == 0); IShareToken _shareToken = _orderData.market.getShareToken(_orderData.outcome); uint256 _attosharesToCover = _orderData.amount; // Figure out how many shares of the outcome the creator has uint256 _attosharesHeld = _shareToken.balanceOf(_orderData.creator); // Take shares in escrow if user has shares if (_attosharesHeld > 0) { _orderData.sharesEscrowed = SafeMathUint256.min(_attosharesHeld, _attosharesToCover); _attosharesToCover -= _orderData.sharesEscrowed; _shareToken.trustedOrderTransfer(_orderData.creator, _orderData.market, _orderData.sharesEscrowed); } // If not able to cover entire order with shares alone, then cover remaining with tokens if (_attosharesToCover > 0) { _orderData.moneyEscrowed = _orderData.market.getNumTicks().sub(_orderData.price).mul(_attosharesToCover); require(_orderData.augur.trustedTransfer(_orderData.market.getDenominationToken(), _orderData.creator, _orderData.market, _orderData.moneyEscrowed)); } return true; } }
Buys `_amount` shares of every outcome in the specified market./
function initialize(IUniverse _universe, uint256 _endTime, uint256 _feePerEthInAttoeth, ICash _cash, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public payable returns (bool _success); function derivePayoutDistributionHash(uint256[] _payoutNumerators, bool _invalid) public view returns (bytes32); function getUniverse() public view returns (IUniverse); function getFeeWindow() public view returns (IFeeWindow); function getNumberOfOutcomes() public view returns (uint256); function getNumTicks() public view returns (uint256); function getDenominationToken() public view returns (ICash); function getShareToken(uint256 _outcome) public view returns (IShareToken); function getMarketCreatorSettlementFeeDivisor() public view returns (uint256); function getForkingMarket() public view returns (IMarket _market); function getEndTime() public view returns (uint256); function getMarketCreatorMailbox() public view returns (IMailbox); function getWinningPayoutDistributionHash() public view returns (bytes32); function getWinningPayoutNumerator(uint256 _outcome) public view returns (uint256); function getReputationToken() public view returns (IReputationToken); function getFinalizationTime() public view returns (uint256); function getInitialReporterAddress() public view returns (address); function deriveMarketCreatorFeeAmount(uint256 _amount) public view returns (uint256); function isContainerForShareToken(IShareToken _shadyTarget) public view returns (bool); function isContainerForReportingParticipant(IReportingParticipant _reportingParticipant) public view returns (bool); function isInvalid() public view returns (bool); function finalize() public returns (bool); function designatedReporterWasCorrect() public view returns (bool); function designatedReporterShowed() public view returns (bool); function isFinalized() public view returns (bool); function finalizeFork() public returns (bool); function assertBalances() public view returns (bool); } } } } } } } function publicBuyCompleteSets(IMarket _market, uint256 _amount) external marketIsLegit(_market) payable convertToAndFromCash onlyInGoodTimes returns (bool) { this.buyCompleteSets(msg.sender, _market, _amount); controller.getAugur().logCompleteSetsPurchased(_market.getUniverse(), _market, msg.sender, _amount); _market.assertBalances(); return true; }
12,186,731
pragma solidity ^0.4.2; import "LibTrieProof.sol"; import "LibVerifySign.sol"; contract Meshchain { /* errcode: 10001:用户已存在 10002:用户状态不正常 10003:用户不存在 10004:热点账户不存在 10005:热点账户状态不正常 10006:用户余额不足 10007:冻结余额不合法 10008:热点账户余额为0 10009:没有可释放的金额 10010:非热点账户 10011:非影子户 10012:trie proof验证失败 10013:影子户不存在 10014:影子户状态不正常 10015:影子户已存在 10016:公钥列表不存在 10017:验证签名失败 10018:金额非法 10019:交易不存在 10020:热点账户已存在 */ struct UserInfo { bytes32 uid; uint availAssets; uint unAvailAssets; uint8 identity;//0:普通账户 1:热点账户 2:影子户 bytes32 name;//用户名字 } struct Transfer { uint id; bytes32 from; bytes32 to; uint amount; uint8 status;//0:success 1:assets error 2:pending 3:verify error 4:endpoint receive error } struct Deposit { uint id; bytes32 uid; uint amount; uint8 status; } mapping(bytes32 => UserInfo) userMap;//uid as key mapping(bytes32 => bytes32) hotAccountMap;//name as key, uid as value mapping(bytes32 => bytes32) subHotAccountMap;//name as key, uid as value mapping(uint => Transfer) transferMap; mapping(uint => Deposit) depositMap; uint incrTrans; uint incrDep; event retLog(int code); event depLog(uint id); event transferLog(uint id); event assetsLog(int code, uint availAssets, uint frozenAssets); //user register function register(bytes32 uid, uint assets, uint8 identity, bytes32 name) public returns(bool) { if (userMap[uid].uid != "") { retLog(10001); return false; } UserInfo memory user = UserInfo(uid, assets, 0, identity, name); if (identity == 1 && hotAccountMap[name] != "") { retLog(10020); return false; } else if (identity == 1) { if (hotAccountMap[name] != "") { retLog(10020); return false; } hotAccountMap[name] = user.uid; } else if (identity == 2) { if (subHotAccountMap[name] != "") { retLog(10015); return false; } subHotAccountMap[name] = user.uid; } userMap[uid] = user; retLog(0); return true; } //充值 function deposit(bytes32 uid, uint assets) public returns(bool) { if (userMap[uid].uid == "") { retLog(10003); return false; } if (assets == 0) { retLog(10018); return false; } UserInfo storage user = userMap[uid]; user.availAssets += assets; userMap[uid] = user; incrDep += 1; Deposit memory dep = Deposit(incrDep, uid, assets, 0); depositMap[incrDep] = dep; retLog(0); depLog(incrDep); return true; } //transfer:from, to are in same chain function transferOneChain(bytes32 from, bytes32 to, uint assets) public returns(bool) { if (userMap[from].uid == "" || userMap[to].uid == "") { retLog(10003); return false; } if (assets == 0) { retLog(10018); return false; } UserInfo storage fromUser = userMap[from]; UserInfo storage toUser = userMap[to]; incrTrans += 1; Transfer memory transfer = Transfer(incrTrans, from, to, assets, 0); if (fromUser.availAssets < assets) { transfer.status = 1;//from asset error transferMap[incrTrans] = transfer; retLog(10006); return false; } fromUser.availAssets -= assets; toUser.availAssets += assets; userMap[from] = fromUser; userMap[to] = toUser; transferMap[incrTrans] = transfer; retLog(0); transferLog(incrTrans); return true; } //transfer:from, to are not in same chain function transferInterChainByFrom(bytes32 from, bytes32 to, uint assets) public returns(bool) { if (userMap[from].uid == "") { retLog(10003); return false; } if (assets == 0) { retLog(10018); return false; } UserInfo storage fromUser = userMap[from]; incrTrans += 1; Transfer memory transfer = Transfer(incrTrans, from, to, assets, 0); if (fromUser.availAssets < assets) { transfer.status = 1;//from asset error transferMap[incrTrans] = transfer; retLog(10006); return false; } fromUser.availAssets -= assets; fromUser.unAvailAssets += assets; transfer.status = 2; transferMap[incrTrans] = transfer; retLog(0); transferLog(incrTrans); return true; } function transferInterChainByTo(string merkleRoot, string merkleProofs, string key, string value, bytes32 from, bytes32 to, uint assets) public returns(bool) { if (userMap[to].uid == "") { retLog(10003); return false; } if (assets == 0) { retLog(10018); return false; } UserInfo storage toUser = userMap[to]; incrTrans += 1; Transfer memory transfer = Transfer(incrTrans, from, to, assets, 0); uint ret = LibTrieProof.verifyProof(merkleRoot, merkleProofs, key, value); if (ret != 0) { transfer.status = 3; transferMap[incrTrans] = transfer; retLog(10012); return false; } toUser.availAssets += assets; transferMap[incrTrans] = transfer; retLog(0); transferLog(incrTrans); return true; } //transfer confirm when `to` receive assets successfully. function transferInterChainConfirm(uint transId) public returns(bool) { if (transferMap[transId].id == 0) { retLog(10019); return false; } Transfer storage transfer = transferMap[transId]; UserInfo storage fromUser = userMap[transfer.from]; fromUser.unAvailAssets -= transfer.amount; transfer.status = 0; transferMap[transId] = transfer; userMap[transfer.from] = fromUser; retLog(0); transferLog(transId); return true; } //transfer cancel when `to` can not receive assets. function transferInterChainCancel(uint transId) public returns(bool) { if (transferMap[transId].id == 0) { retLog(10019); return false; } Transfer storage transfer = transferMap[transId]; UserInfo storage fromUser = userMap[transfer.from]; fromUser.unAvailAssets -= transfer.amount; fromUser.availAssets += transfer.amount; transfer.status = 4; transferMap[transId] = transfer; userMap[transfer.from] = fromUser; retLog(0); transferLog(transId); return true; } //验证签名 pubs,signs用";"分隔 function verifySign(string hash, string pubs, string signs, string idxs) constant public returns(uint) { uint ret = LibVerifySign.verifySign(hash, pubs, signs, idxs); if (ret != 0) { return 10017; } return ret; } function getUserInfo(bytes32 uid) constant public returns(uint, uint, uint, bytes32) { if (userMap[uid].uid == "") { return (0, 0, 0, ""); } UserInfo storage user = userMap[uid]; return (user.availAssets, user.unAvailAssets, user.identity, user.name); } //get account by hot account name function getHotAccoutByName(bytes32 name) constant public returns(bytes32, uint, uint, uint) { if (hotAccountMap[name] == "") { return ("", 0, 0, 0); } bytes32 uid = hotAccountMap[name]; UserInfo storage user = userMap[uid]; return (user.uid, user.availAssets, user.unAvailAssets, user.identity); } //get account by sub hot account name function getSubHotAccoutByName(bytes32 name) constant public returns(bytes32, uint, uint, uint) { if (subHotAccountMap[name] == "") { return ("", 0, 0, 0); } bytes32 uid = subHotAccountMap[name]; UserInfo storage user = userMap[uid]; return (user.uid, user.availAssets, user.unAvailAssets, user.identity); } }
transfer:from, to are not in same chain
function transferInterChainByFrom(bytes32 from, bytes32 to, uint assets) public returns(bool) { if (userMap[from].uid == "") { retLog(10003); return false; } if (assets == 0) { retLog(10018); return false; } UserInfo storage fromUser = userMap[from]; incrTrans += 1; Transfer memory transfer = Transfer(incrTrans, from, to, assets, 0); if (fromUser.availAssets < assets) { transferMap[incrTrans] = transfer; retLog(10006); return false; } fromUser.availAssets -= assets; fromUser.unAvailAssets += assets; transfer.status = 2; transferMap[incrTrans] = transfer; retLog(0); transferLog(incrTrans); return true; }
14,065,472
./full_match/4/0xCE54e4Aed274990062F43Ba3579dCAedbfA6E27d/sources/contracts/permissions/IERC721CreatorMintPermissions.sol
Required interface of an ERC721Creator compliant extension contracts./
interface IERC721CreatorMintPermissions is IERC165, IAdminControl { function approveMint(address extension, address to, uint256 tokenId) external; }
12,367,155
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "./LiteSwapDAO1.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract LiteSwapDAOFactory is Ownable { using SafeMath for uint; LiteSwapDAO1 new_cooperative; mapping(address => CooperativeGroup) groupMapping; address[] public cooperativeGroups; string[] public createdGroupNames; address public currentGroupAddress; string public currentGroupName; /// Empty constructor constructor() public { new_cooperative = new LiteSwapDAO1(msg.sender); } //create Cooperative Group function createCooperativeGroup(string memory groupName, uint amount) public payable returns (bool) { new_cooperative.createCooperativeGroup(groupName, amount ); } //All users to join a cooperative group function joinCooperativeGroup(string memory groupName) public payable returns (bool) { new_cooperative.addMember(groupName); } //get group members count function getGroupCount(string memory name) public payable returns (uint){ new_cooperative.getAllGroupMembersCount(name); } /// Allow retrieving the the array of created contracts /// @return An array of all created Cooperative Group contracts function getcooperativeGroups() public view returns(address[] memory) { return cooperativeGroups; } /// Allow retrieving the the array of created group names /// @return An array of all created Cooperative Group names contracts function getcooperativeGroupNames() public view returns (string[] memory) { return new_cooperative.getCooperativeNames(); } }
Allow retrieving the the array of created group names return An array of all created Cooperative Group names contracts
function getcooperativeGroupNames() public view returns (string[] memory) { return new_cooperative.getCooperativeNames(); }
12,761,114
// SPDX-License-Identifier: MIT pragma solidity =0.8.10; import "../../utils/TokenUtils.sol"; import "../ActionBase.sol"; /// @title Helper action to un-wrap WETH9 to Eth contract UnwrapEth is ActionBase { using TokenUtils for address; struct Params { uint256 amount; address to; } /// @inheritdoc ActionBase function executeAction( bytes memory _callData, bytes32[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { Params memory inputData = parseInputs(_callData); inputData.amount = _parseParamUint(inputData.amount, _paramMapping[0], _subData, _returnValues); inputData.to = _parseParamAddr(inputData.to, _paramMapping[1], _subData, _returnValues); return bytes32(_unwrapEth(inputData.amount, inputData.to)); } // solhint-disable-next-line no-empty-blocks function executeActionDirect(bytes memory _callData) public payable override { Params memory inputData = parseInputs(_callData); _unwrapEth(inputData.amount, inputData.to); } /// @inheritdoc ActionBase function actionType() public pure virtual override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } //////////////////////////// ACTION LOGIC //////////////////////////// /// @notice Unwraps WETH9 -> Eth /// @param _amount Amount of Weth to unwrap /// @param _to Address where to send the unwrapped Eth function _unwrapEth(uint256 _amount, address _to) internal returns (uint256) { if (_amount == type(uint256).max) { _amount = TokenUtils.WETH_ADDR.getBalance(address(this)); } TokenUtils.withdrawWeth(_amount); // if _to == proxy, it will stay on proxy TokenUtils.ETH_ADDR.withdrawTokens(_to, _amount); return _amount; } function parseInputs(bytes memory _callData) public pure returns (Params memory params) { params = abi.decode(_callData, (Params)); } }
solhint-disable-next-line no-empty-blocks
function executeActionDirect(bytes memory _callData) public payable override { Params memory inputData = parseInputs(_callData); _unwrapEth(inputData.amount, inputData.to); }
938,597
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol'; import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol'; import './interfaces/IDexPriceAggregator.sol'; import './libraries/SafeCast.sol'; import './Owned.sol'; /// @title DexPriceAggregatorUniswapV3 /// @notice A DexPriceAggregator sourcing prices from Uniswap V3. /// Provides the minimum output between an asset's "spot" price and TWAP from the last n seconds. /// The "spot" price is always the last block's ending price. contract DexPriceAggregatorUniswapV3 is IDexPriceAggregator, Owned { address public immutable uniswapV3Factory; address public immutable weth; uint24 public immutable defaultPoolFee; mapping(bytes32 => address) public overriddenPoolForRoute; constructor( address _owner, address _uniswapV3Factory, address _weth, uint24 _defaultPoolFee ) Owned(_owner) { uniswapV3Factory = _uniswapV3Factory; weth = _weth; defaultPoolFee = _defaultPoolFee; } /******************** * Oracle functions * ********************/ /// @inheritdoc IDexPriceAggregator function assetToAsset( address _tokenIn, uint256 _amountIn, address _tokenOut, uint256 _twapPeriod ) public view override returns (uint256 amountOut) { if (_tokenIn == weth) { return ethToAsset(_amountIn, _tokenOut, _twapPeriod); } else if (_tokenOut == weth) { return assetToEth(_tokenIn, _amountIn, _twapPeriod); } else { return _fetchAmountCrossingPools(_tokenIn, _amountIn, _tokenOut, _twapPeriod); } } /// @notice Given a token and its amount, return the equivalent value in ETH /// @param _tokenIn Address of an ERC20 token contract to be converted /// @param _amountIn Amount of tokenIn to be converted /// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate /// @return ethAmountOut Amount of ETH received for amountIn of tokenIn function assetToEth( address _tokenIn, uint256 _amountIn, uint256 _twapPeriod ) public view returns (uint256 ethAmountOut) { address tokenOut = weth; address pool = _getPoolForRoute(PoolAddress.getPoolKey(_tokenIn, tokenOut, defaultPoolFee)); return _fetchAmountFromSinglePool(_tokenIn, _amountIn, tokenOut, pool, _twapPeriod); } /// @notice Given an amount of ETH, return the equivalent value in another token /// @param _ethAmountIn Amount of ETH to be converted /// @param _tokenOut Address of an ERC20 token contract to convert into /// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate /// @return amountOut Amount of tokenOut received for ethAmountIn of ETH function ethToAsset( uint256 _ethAmountIn, address _tokenOut, uint256 _twapPeriod ) public view returns (uint256 amountOut) { address tokenIn = weth; address pool = _getPoolForRoute(PoolAddress.getPoolKey(tokenIn, _tokenOut, defaultPoolFee)); return _fetchAmountFromSinglePool(tokenIn, _ethAmountIn, _tokenOut, pool, _twapPeriod); } /************************ * Management functions * ************************/ /// @notice Override the Uniswap V3 pool queried on a tokenA:tokenB route /// @dev Override can be reset by using address(0) for _pool /// @param _tokenA Address of an ERC20 token contract /// @param _tokenB Address of another ERC20 token contract /// @param _pool Address of a Uniswap V3 pool constructed with _tokenA and _tokenB function setPoolForRoute( address _tokenA, address _tokenB, address _pool ) public onlyOwner { PoolAddress.PoolKey memory poolKey = PoolAddress.getPoolKey( _tokenA, _tokenB, uint24(0) // pool fee is unused ); if (_pool != address(0)) { require( poolKey.token0 == IUniswapV3Pool(_pool).token0() && poolKey.token1 == IUniswapV3Pool(_pool).token1(), 'Tokens or pool not correct' ); } overriddenPoolForRoute[_identifyRouteFromPoolKey(poolKey)] = _pool; emit PoolForRouteSet(poolKey.token0, poolKey.token1, _pool); } /// @notice Fetch the Uniswap V3 pool to be queried for a tokenA:tokenB route /// @param _tokenA Address of an ERC20 token contract /// @param _tokenB Address of another ERC20 token contract /// @return pool Address of a Uniswap V3 pool constructed with _tokenA and _tokenB function getPoolForRoute(address _tokenA, address _tokenB) public view returns (address pool) { return _getPoolForRoute(PoolAddress.getPoolKey(_tokenA, _tokenB, defaultPoolFee)); } /************************** * Utility view functions * **************************/ /// @notice Fetch a Uniswap V3 pool's current "spot" and TWAP tick values /// @param _pool Address of a Uniswap V3 pool /// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate /// @return spotTick The pool's current "spot" tick /// @return twapTick The twap tick for the last _twapPeriod seconds function fetchCurrentTicks(address _pool, uint32 _twapPeriod) public view returns (int24 spotTick, int24 twapTick) { spotTick = OracleLibrary.getBlockStartingTick(_pool); twapTick = OracleLibrary.consult(_pool, _twapPeriod); } /// @notice Given a tick and a token amount, calculates the amount of token received in exchange /// @param _tokenIn Address of an ERC20 token contract to be converted /// @param _amountIn Amount of tokenIn to be converted /// @param _tokenOut Address of an ERC20 token contract to convert into /// @param _tick Tick value representing conversion ratio between _tokenIn and _tokenOut /// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn function getQuoteAtTick( address _tokenIn, uint128 _amountIn, address _tokenOut, int24 _tick ) public pure returns (uint256 amountOut) { return OracleLibrary.getQuoteAtTick(_tick, _amountIn, _tokenIn, _tokenOut); } /// @notice Similar to getQuoteAtTick() but calculates the amount of token received in exchange /// by first adjusting into ETH /// (ie. when a route goes through an intermediary pool with ETH) /// @param _tokenIn Address of an ERC20 token contract to be converted /// @param _amountIn Amount of tokenIn to be converted /// @param _tokenOut Address of an ERC20 token contract to convert into /// @param _tick1 First tick value representing conversion ratio between _tokenIn and ETH /// @param _tick2 Second tick value representing conversion ratio between ETH and _tokenOut /// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn function getQuoteCrossingTicksThroughWeth( address _tokenIn, uint128 _amountIn, address _tokenOut, int24 _tick1, int24 _tick2 ) public view returns (uint256 amountOut) { return _getQuoteCrossingTicksThroughWeth(_tokenIn, _amountIn, _tokenOut, _tick1, _tick2); } /************* * Internals * *************/ /// @notice Given a token and amount, return the equivalent value in another token by exchanging /// within a single liquidity pool /// @dev _pool _must_ be previously checked to contain _tokenIn and _tokenOut. /// It is exposed as a parameter only as a gas optimization. /// @param _tokenIn Address of an ERC20 token contract to be converted /// @param _amountIn Amount of tokenIn to be converted /// @param _tokenOut Address of an ERC20 token contract to convert into /// @param _pool Address of a Uniswap V3 pool containing _tokenIn and _tokenOut /// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate /// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn function _fetchAmountFromSinglePool( address _tokenIn, uint256 _amountIn, address _tokenOut, address _pool, uint256 _twapPeriod ) internal view returns (uint256 amountOut) { // Leave ticks as int256s to avoid solidity casting int256 spotTick = OracleLibrary.getBlockStartingTick(_pool); int256 twapTick = OracleLibrary.consult(_pool, SafeCast.toUint32(_twapPeriod)); // Return min amount between spot price and twap // Ticks are based on the ratio between token0:token1 so if the input token is token1 then // we need to treat the tick as an inverse int256 minTick; if (_tokenIn < _tokenOut) { minTick = spotTick < twapTick ? spotTick : twapTick; } else { minTick = spotTick > twapTick ? spotTick : twapTick; } return OracleLibrary.getQuoteAtTick( int24(minTick), // can assume safe being result from consult() SafeCast.toUint128(_amountIn), _tokenIn, _tokenOut ); } /// @notice Given a token and amount, return the equivalent value in another token by "crossing" /// liquidity across an intermediary pool with ETH (ie. _tokenIn:ETH and ETH:_tokenOut) /// @dev If an overridden pool has been set for _tokenIn and _tokenOut, this pool will be used /// used directly in lieu of "crossing" against an intermediary pool with ETH /// @param _tokenIn Address of an ERC20 token contract to be converted /// @param _amountIn Amount of tokenIn to be converted /// @param _tokenOut Address of an ERC20 token contract to convert into /// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate /// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn function _fetchAmountCrossingPools( address _tokenIn, uint256 _amountIn, address _tokenOut, uint256 _twapPeriod ) internal view returns (uint256 amountOut) { // If the tokenIn:tokenOut route was overridden to use a single pool, derive price directly from that pool address overriddenPool = _getOverriddenPool( PoolAddress.getPoolKey( _tokenIn, _tokenOut, uint24(0) // pool fee is unused ) ); if (overriddenPool != address(0)) { return _fetchAmountFromSinglePool(_tokenIn, _amountIn, _tokenOut, overriddenPool, _twapPeriod); } // Otherwise, derive the price by "crossing" through tokenIn:ETH -> ETH:tokenOut // To keep consistency, we cross through with the same price source (spot vs. twap) address pool1 = _getPoolForRoute(PoolAddress.getPoolKey(_tokenIn, weth, defaultPoolFee)); address pool2 = _getPoolForRoute(PoolAddress.getPoolKey(_tokenOut, weth, defaultPoolFee)); int24 spotTick1 = OracleLibrary.getBlockStartingTick(pool1); int24 spotTick2 = OracleLibrary.getBlockStartingTick(pool2); uint256 spotAmountOut = _getQuoteCrossingTicksThroughWeth(_tokenIn, _amountIn, _tokenOut, spotTick1, spotTick2); uint32 castedTwapPeriod = SafeCast.toUint32(_twapPeriod); int24 twapTick1 = OracleLibrary.consult(pool1, castedTwapPeriod); int24 twapTick2 = OracleLibrary.consult(pool2, castedTwapPeriod); uint256 twapAmountOut = _getQuoteCrossingTicksThroughWeth(_tokenIn, _amountIn, _tokenOut, twapTick1, twapTick2); // Return min amount between spot price and twap return spotAmountOut < twapAmountOut ? spotAmountOut : twapAmountOut; } /// @notice Similar to OracleLibrary#getQuoteAtTick but calculates the amount of token received /// in exchange by first adjusting into ETH /// (ie. when a route goes through an intermediary pool with ETH) /// @param _tokenIn Address of an ERC20 token contract to be converted /// @param _amountIn Amount of tokenIn to be converted /// @param _tokenOut Address of an ERC20 token contract to convert into /// @param _tick1 First tick value used to adjust from _tokenIn to ETH /// @param _tick2 Second tick value used to adjust from ETH to _tokenOut /// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn function _getQuoteCrossingTicksThroughWeth( address _tokenIn, uint256 _amountIn, address _tokenOut, int24 _tick1, int24 _tick2 ) internal view returns (uint256 amountOut) { uint256 ethAmountOut = OracleLibrary.getQuoteAtTick(_tick1, SafeCast.toUint128(_amountIn), _tokenIn, weth); return OracleLibrary.getQuoteAtTick(_tick2, SafeCast.toUint128(ethAmountOut), weth, _tokenOut); } /// @notice Fetch the Uniswap V3 pool to be queried for a route denoted by a PoolKey /// @param _poolKey PoolKey representing the route /// @return pool Address of the Uniswap V3 pool to use for the route function _getPoolForRoute(PoolAddress.PoolKey memory _poolKey) internal view returns (address pool) { pool = _getOverriddenPool(_poolKey); if (pool == address(0)) { pool = PoolAddress.computeAddress(uniswapV3Factory, _poolKey); } } /// @notice Obtain the canonical identifier for a route denoted by a PoolKey /// @param _poolKey PoolKey representing the route /// @return id identifier for the route function _identifyRouteFromPoolKey(PoolAddress.PoolKey memory _poolKey) internal pure returns (bytes32 id) { return keccak256(abi.encodePacked(_poolKey.token0, _poolKey.token1)); } /// @notice Fetch an overridden pool for a route denoted by a PoolKey, if any /// @param _poolKey PoolKey representing the route /// @return pool Address of the Uniswap V3 pool overridden for the route. /// address(0) if no overridden pool has been set. function _getOverriddenPool(PoolAddress.PoolKey memory _poolKey) internal view returns (address pool) { return overriddenPoolForRoute[_identifyRouteFromPoolKey(_poolKey)]; } /********** * Events * **********/ event PoolForRouteSet(address indexed token0, address indexed token1, address indexed pool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0 <0.8.0; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol'; import '../libraries/PoolAddress.sol'; /// @title Oracle library /// @notice Provides functions to integrate with V3 pool oracle library OracleLibrary { /// @notice Fetches time-weighted average tick using Uniswap V3 oracle /// @param pool Address of Uniswap V3 pool that we want to observe /// @param period Number of seconds in the past to start calculating time-weighted average /// @return timeWeightedAverageTick The time-weighted average tick from (block.timestamp - period) to block.timestamp function consult(address pool, uint32 period) internal view returns (int24 timeWeightedAverageTick) { require(period != 0, 'BP'); uint32[] memory secondAgos = new uint32[](2); secondAgos[0] = period; secondAgos[1] = 0; (int56[] memory tickCumulatives, ) = IUniswapV3Pool(pool).observe(secondAgos); int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0]; timeWeightedAverageTick = int24(tickCumulativesDelta / period); // Always round to negative infinity if (tickCumulativesDelta < 0 && (tickCumulativesDelta % period != 0)) timeWeightedAverageTick--; } /// @notice Given a tick and a token amount, calculates the amount of token received in exchange /// @param tick Tick value used to calculate the quote /// @param baseAmount Amount of token to be converted /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken function getQuoteAtTick( int24 tick, uint128 baseAmount, address baseToken, address quoteToken ) internal pure returns (uint256 quoteAmount) { uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick); // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself if (sqrtRatioX96 <= type(uint128).max) { uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96; quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192) : FullMath.mulDiv(1 << 192, baseAmount, ratioX192); } else { uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64); quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128) : FullMath.mulDiv(1 << 128, baseAmount, ratioX128); } } /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation /// @param pool Address of Uniswap V3 pool that we want to observe /// @return The number of seconds ago of the oldest observation stored for the pool function getOldestObservationSecondsAgo(address pool) internal view returns (uint32) { (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0(); require(observationCardinality > 0, 'NI'); (uint32 observationTimestamp, , , bool initialized) = IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality); // The next index might not be initialized if the cardinality is in the process of increasing // In this case the oldest observation is always in index 0 if (!initialized) { (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0); } return uint32(block.timestamp) - observationTimestamp; } /// @notice Given a pool, it returns the tick value as of the start of the current block /// @param pool Address of Uniswap V3 pool /// @return The tick that the pool was in at the start of the current block function getBlockStartingTick(address pool) internal view returns (int24) { (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0(); // 2 observations are needed to reliably calculate the block starting tick require(observationCardinality > 1, 'NEO'); // If the latest observation occurred in the past, then no tick-changing trades have happened in this block // therefore the tick in `slot0` is the same as at the beginning of the current block. // We don't need to check if this observation is initialized - it is guaranteed to be. (uint32 observationTimestamp, int56 tickCumulative, , ) = IUniswapV3Pool(pool).observations(observationIndex); if (observationTimestamp != uint32(block.timestamp)) { return tick; } uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality; (uint32 prevObservationTimestamp, int56 prevTickCumulative, , bool prevInitialized) = IUniswapV3Pool(pool).observations(prevIndex); require(prevInitialized, 'ONI'); return int24((tickCumulative - prevTickCumulative) / (observationTimestamp - prevObservationTimestamp)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; /// @title DexPriceAggregator interface /// @notice Provides interface for querying an asset's price from one or more DEXes interface IDexPriceAggregator { /// @notice Given a token and its amount, return the equivalent value in another token /// @param tokenIn Address of an ERC20 token contract to be converted /// @param amountIn Amount of tokenIn to be converted /// @param tokenOut Address of an ERC20 token contract to convert into /// @param twapPeriod Number of seconds in the past to consider for the TWAP rate, if applicable /// @return amountOut Amount of tokenOut received for amountIn of tokenIn function assetToAsset( address tokenIn, uint256 amountIn, address tokenOut, uint256 twapPeriod ) external view returns (uint256 amountOut); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Safe casting methods /// @notice Contains methods for safely casting between types /// Adapted from UniswapV3: https://github.com/Uniswap/uniswap-v3-core/blob/v1.0.0/contracts/libraries/SafeCast.sol library SafeCast { /// @notice Cast a uint256 to a uint128, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint128 function toUint128(uint256 y) internal pure returns (uint128 z) { require((z = uint128(y)) == y); } /// @notice Cast a uint256 to a uint32, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint32 function toUint32(uint256 y) internal pure returns (uint32 z) { require((z = uint32(y)) == y); } } // SPDX-License-Identifier: MIT // Adapted from https://github.com/Synthetixio/synthetix/blob/v2.46.0/contracts/Owned.sol pragma solidity >=0.5.0 <0.8.0; /// @title Only-owner utility /// @notice Provides subclasses with only-owner permission utilities abstract contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) { 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); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.0; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } }
Fetch an overridden pool for a route denoted by a PoolKey, if any _poolKey PoolKey representing the route return pool Address of the Uniswap V3 pool overridden for the route. address(0) if no overridden pool has been set.
function _getOverriddenPool(PoolAddress.PoolKey memory _poolKey) internal view returns (address pool) { return overriddenPoolForRoute[_identifyRouteFromPoolKey(_poolKey)]; } event PoolForRouteSet(address indexed token0, address indexed token1, address indexed pool);
1,180,861
./partial_match/42/0x1e01587409a3054CE02B7A7512616BA7dCe71a51/sources/InsuranceFund.sol
to be compatible with some erc20 tokens like USDT
function _approve( IERC20Upgradeable _token, address _spender, Decimal.decimal memory _value ) internal { _updateDecimal(address(_token)); __approve(_token, _spender, Decimal.zero()); __approve(_token, _spender, _value); }
3,472,767
/** *Submitted for verification at Etherscan.io on 2021-02-17 */ // File: @openzeppelin/contracts-upgradeable/proxy/Initializable.sol // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( _initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized" ); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // 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; } } // File: @openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.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 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; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: @openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.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 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; } } // File: @openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.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 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; } // File: @openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract 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; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/ERC20PausableUpgradeable.sol pragma solidity >=0.6.0 <0.8.0; /** * @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 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; } // File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.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 OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File: contracts/CropToken.sol pragma solidity 0.6.11; pragma experimental ABIEncoderV2; struct FrozenWallet { address wallet; uint256 totalAmount; uint256 monthlyAmount; uint256 initialAmount; uint256 startDay; uint256 afterDays; bool scheduled; uint256 monthDelay; } struct VestingType { uint256 monthlyRate; uint256 initialRate; uint256 afterDays; uint256 monthDelay; bool vesting; } contract CropToken is Initializable, OwnableUpgradeable, ERC20PausableUpgradeable { mapping(address => FrozenWallet) public frozenWallets; VestingType[] public vestingTypes; function initialize() public initializer { __Ownable_init(); __ERC20_init("Crop Token", "CROP"); __ERC20Pausable_init(); _mint( address(0x76C76680bb8A80513b0a261e8b978cDC61eAdaaf), 6000000000000000000000000 ); _mint( address(0x5AB2Cd68A3e6F7FfEA77dE5f4991BA50F99a3E2C), 6000000000000000000000000 ); _mint( // dev address(0xC27B0f3965B1eD78442F16E861A2bB2230f9757c), address(0x19a953816F5dCb7cCDb8b37bB684320304E2fD18), 1000000000000000000000000 ); _mint( // dev address(0x6a97955673F2DEC62325800f1814014C062037F6), address(0x0dAE97dE55Af3243B6cD95F1Ffc3443f1da77B72), 1050000000000000000000000 ); _mint( address(0x5Fb00CFdf85020584ec19318996bd1bAd3E13295), 25000000000000000000000000 ); _mint( address(0x80329C32F6D28F487efdc9f6c43c4d4a6ce0493c), 20000000000000000000000000 ); _mint( address(0x7A56Bab3FF72fDAAF044b4362d892A650325Eda8), 20000000000000000000000000 ); vestingTypes.push( VestingType(5000000000000000000, 5000000000000000000, 0, 1, true) // %5 initial -> 19 month %5 ); vestingTypes.push( VestingType(5000000000000000000, 0, 180 days, 0, true) ); // 180 DaysAfter %5 20 months } function getReleaseTime() public pure returns (uint256) { return 1613347200; // 02/15/2021 @ 12:00am (UTC) -> 30 mart olacak } function getMaxTotalSupply() public pure returns (uint256) { return 100000000000000000000000000; } function addAllocations( address[] memory addresses, uint256[] memory totalAmounts, uint256 vestingTypeIndex ) external onlyOwner returns (bool) { require( addresses.length == totalAmounts.length, "Address and totalAmounts length must be same" ); require( vestingTypes[vestingTypeIndex].vesting, "Vesting type isn't found" ); VestingType memory vestingType = vestingTypes[vestingTypeIndex]; uint256 addressesLength = addresses.length; for (uint256 i = 0; i < addressesLength; i++) { address _address = addresses[i]; uint256 totalAmount = totalAmounts[i]; uint256 monthlyAmount = totalAmounts[i].mul(vestingType.monthlyRate).div( 100000000000000000000 ); uint256 initialAmount = totalAmounts[i].mul(vestingType.initialRate).div( 100000000000000000000 ); uint256 afterDay = vestingType.afterDays; uint256 monthDelay = vestingType.monthDelay; addFrozenWallet( _address, totalAmount, monthlyAmount, initialAmount, afterDay, monthDelay ); } return true; } function _mint(address account, uint256 amount) internal override { uint256 totalSupply = super.totalSupply(); require( getMaxTotalSupply() >= totalSupply.add(amount), "Max total supply over" ); super._mint(account, amount); } function addFrozenWallet( address wallet, uint256 totalAmount, uint256 monthlyAmount, uint256 initialAmount, uint256 afterDays, uint256 monthDelay ) internal { uint256 releaseTime = getReleaseTime(); if (!frozenWallets[wallet].scheduled) { _mint(wallet, totalAmount); } // Create frozen wallets FrozenWallet memory frozenWallet = FrozenWallet( wallet, totalAmount, monthlyAmount, initialAmount, releaseTime.add(afterDays), afterDays, true, monthDelay ); // Add wallet to frozen wallets frozenWallets[wallet] = frozenWallet; } function getTimestamp() external view returns (uint256) { return block.timestamp; } function getMonths(uint256 afterDays, uint256 monthDelay) public view returns (uint256) { uint256 releaseTime = getReleaseTime(); uint256 time = releaseTime.add(afterDays); if (block.timestamp < time) { return 0; } uint256 diff = block.timestamp.sub(time); uint256 months = diff.div(30 days).add(1).sub(monthDelay); return months; } function isStarted(uint256 startDay) public view returns (bool) { uint256 releaseTime = getReleaseTime(); if (block.timestamp < releaseTime || block.timestamp < startDay) { return false; } return true; } function getTransferableAmount(address sender) public view returns (uint256) { uint256 months = getMonths( frozenWallets[sender].afterDays, frozenWallets[sender].monthDelay ); uint256 monthlyTransferableAmount = frozenWallets[sender].monthlyAmount.mul(months); uint256 transferableAmount = monthlyTransferableAmount.add(frozenWallets[sender].initialAmount); if (transferableAmount > frozenWallets[sender].totalAmount) { return frozenWallets[sender].totalAmount; } return transferableAmount; } function getRestAmount(address sender) public view returns (uint256) { uint256 transferableAmount = getTransferableAmount(sender); uint256 restAmount = frozenWallets[sender].totalAmount.sub(transferableAmount); return restAmount; } // Transfer control function canTransfer(address sender, uint256 amount) public view returns (bool) { if (!frozenWallets[sender].scheduled) { return true; } uint256 balance = balanceOf(sender); uint256 restAmount = getRestAmount(sender); if ( balance > frozenWallets[sender].totalAmount && balance.sub(frozenWallets[sender].totalAmount) >= amount ) { return true; } if ( !isStarted(frozenWallets[sender].startDay) || balance.sub(amount) < restAmount ) { return false; } return true; } // @override function _beforeTokenTransfer( address sender, address recipient, uint256 amount ) internal virtual override { require(canTransfer(sender, amount), "Wait for vesting day!"); super._beforeTokenTransfer(sender, recipient, amount); } function pause(bool status) public onlyOwner { if (status) { _pause(); } else { _unpause(); } } }
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;
2,168,402
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity =0.8.7; interface IAuctioneerLike { function getExpectedAmount(uint256 swapAmount_) external view returns (uint256 expectedAmount_); } interface IERC20Like { function approve(address spender_, uint256 amount_) external returns (bool success_); function balanceOf(address account_) external view returns (uint256 balanceOf_); function decimals() external view returns (uint8 decimals_); function transfer(address recipient_, uint256 amount_) external returns (bool success_); function transferFrom(address owner_, address recipient_, uint256 amount_) external returns (bool success_); } interface IMapleGlobalsLike { function getLatestPrice(address asset_) external view returns (uint256 price_); function protocolPaused() external view returns (bool protocolPaused_); } interface IMapleLoanLike { function acceptNewTerms(address refinancer_, bytes[] calldata calls_, uint256 amount_) external; function claimableFunds() external view returns (uint256 claimableFunds_); function collateralAsset() external view returns (address collateralAsset_); function fundsAsset() external view returns (address fundsAsset_); function principal() external view returns (uint256 principal_); function claimFunds(uint256 amount_, address destination_) external; function repossess(address destination_) external returns (uint256 collateralAssetAmount_, uint256 fundsAssetAmount_); } interface IMapleProxyFactoryLike { function upgradeInstance(uint256 toVersion_, bytes calldata arguments_) external; } interface IPoolFactoryLike { function globals() external pure returns (address globals_); } interface IPoolLike { function poolDelegate() external view returns (address poolDelegate_); function superFactory() external view returns (address superFactory_); } /// @title Small Library to standardize erc20 token interactions. library ERC20Helper { /**************************/ /*** Internal Functions ***/ /**************************/ function transfer(address token_, address to_, uint256 amount_) internal returns (bool success_) { return _call(token_, abi.encodeWithSelector(IERC20Like.transfer.selector, to_, amount_)); } function transferFrom(address token_, address from_, address to_, uint256 amount_) internal returns (bool success_) { return _call(token_, abi.encodeWithSelector(IERC20Like.transferFrom.selector, from_, to_, amount_)); } function approve(address token_, address spender_, uint256 amount_) internal returns (bool success_) { // If setting approval to zero fails, return false. if (!_call(token_, abi.encodeWithSelector(IERC20Like.approve.selector, spender_, uint256(0)))) return false; // If `amount_` is zero, return true as the previous step already did this. if (amount_ == uint256(0)) return true; // Return the result of setting the approval to `amount_`. return _call(token_, abi.encodeWithSelector(IERC20Like.approve.selector, spender_, amount_)); } function _call(address token_, bytes memory data_) private returns (bool success_) { if (token_.code.length == uint256(0)) return false; bytes memory returnData; ( success_, returnData ) = token_.call(data_); return success_ && (returnData.length == uint256(0) || abi.decode(returnData, (bool))); } } interface ILiquidator { /** * @dev Auctioneer was set. * @param auctioneer_ Address of the auctioneer. */ event AuctioneerSet(address auctioneer_); /** * @dev Funds were withdrawn from the liquidator. * @param token_ Address of the token that was withdrawn. * @param destination_ Address of where tokens were sent. * @param amount_ Amount of tokens that were sent. */ event FundsPulled(address token_, address destination_, uint256 amount_); /** * @dev Portion of collateral was liquidated. * @param swapAmount_ Amount of collateralAsset that was liquidated. * @param returnedAmount_ Amount of fundsAsset that was returned. */ event PortionLiquidated(uint256 swapAmount_, uint256 returnedAmount_); /** * @dev Getter function that returns `collateralAsset`. */ function collateralAsset() external view returns (address collateralAsset_); /** * @dev Getter function that returns `destination` - address that liquidated funds are sent to. */ function destination() external view returns (address destination_); /** * @dev Getter function that returns `auctioneer`. */ function auctioneer() external view returns (address auctioneer_); /** * @dev Getter function that returns `fundsAsset`. */ function fundsAsset() external view returns (address fundsAsset_); /** * @dev Getter function that returns `globals`. */ function globals() external view returns (address); /** * @dev Getter function that returns `owner`. */ function owner() external view returns (address owner_); /** * @dev Set the auctioneer contract address, which is used to pull the `getExpectedAmount`. * Can only be set by `owner`. * @param auctioneer_ The auctioneer contract address. */ function setAuctioneer(address auctioneer_) external; /** * @dev Pulls a specified amount of ERC-20 tokens from the contract. * Can only be called by `owner`. * @param token_ The ERC-20 token contract address. * @param destination_ The destination of the transfer. * @param amount_ The amount to transfer. */ function pullFunds(address token_, address destination_, uint256 amount_) external; /** * @dev Returns the expected amount to be returned from a flash loan given a certain amount of `collateralAsset`. * @param swapAmount_ Amount of `collateralAsset` to be flash-borrowed. * @return expectedAmount_ Amount of `fundsAsset` that must be returned in the same transaction. */ function getExpectedAmount(uint256 swapAmount_) external returns (uint256 expectedAmount_); /** * @dev Flash loan function that: * 1. Transfers a specified amount of `collateralAsset` to `msg.sender`. * 2. Performs an arbitrary call to `msg.sender`, to trigger logic necessary to get `fundsAsset` (e.g., AMM swap). * 3. Performs a `transferFrom`, taking the corresponding amount of `fundsAsset` from the user. * If the required amount of `fundsAsset` is not returned in step 3, the entire transaction reverts. * @param swapAmount_ Amount of `collateralAsset` that is to be borrowed in the flash loan. * @param maxReturnAmount_ Max amount of `fundsAsset` that can be returned to the liquidator contract. * @param data_ ABI-encoded arguments to be used in the low-level call to perform step 2. */ function liquidatePortion(uint256 swapAmount_, uint256 maxReturnAmount_, bytes calldata data_) external; } contract Liquidator is ILiquidator { uint256 private constant NOT_LOCKED = uint256(0); uint256 private constant LOCKED = uint256(1); uint256 internal _locked; address public override immutable collateralAsset; address public override immutable destination; address public override immutable fundsAsset; address public override immutable globals; address public override immutable owner; address public override auctioneer; /*****************/ /*** Modifiers ***/ /*****************/ modifier whenProtocolNotPaused() { require(!IMapleGlobalsLike(globals).protocolPaused(), "LIQ:PROTOCOL_PAUSED"); _; } modifier lock() { require(_locked == NOT_LOCKED, "LIQ:LOCKED"); _locked = LOCKED; _; _locked = NOT_LOCKED; } /** * @param owner_ The address of an account that will have administrative privileges on this contract. * @param collateralAsset_ The address of the collateral asset being liquidated. * @param fundsAsset_ The address of the funds asset. * @param auctioneer_ The address of an Auctioneer. * @param destination_ The address to send funds asset after liquidation. * @param globals_ The address of a Maple Globals contract. */ constructor(address owner_, address collateralAsset_, address fundsAsset_, address auctioneer_, address destination_, address globals_) { require((owner = owner_) != address(0), "LIQ:C:INVALID_OWNER"); require((collateralAsset = collateralAsset_) != address(0), "LIQ:C:INVALID_COL_ASSET"); require((fundsAsset = fundsAsset_) != address(0), "LIQ:C:INVALID_FUNDS_ASSET"); require((destination = destination_) != address(0), "LIQ:C:INVALID_DEST"); require(!IMapleGlobalsLike(globals = globals_).protocolPaused(), "LIQ:C:INVALID_GLOBALS"); // NOTE: Auctioneer of zero is valid, since it is starting the contract off in a paused state. auctioneer = auctioneer_; } function setAuctioneer(address auctioneer_) external override { require(msg.sender == owner, "LIQ:SA:NOT_OWNER"); emit AuctioneerSet(auctioneer = auctioneer_); } function pullFunds(address token_, address destination_, uint256 amount_) external override { require(msg.sender == owner, "LIQ:PF:NOT_OWNER"); emit FundsPulled(token_, destination_, amount_); require(ERC20Helper.transfer(token_, destination_, amount_), "LIQ:PF:TRANSFER"); } function getExpectedAmount(uint256 swapAmount_) public view override returns (uint256 expectedAmount_) { return IAuctioneerLike(auctioneer).getExpectedAmount(swapAmount_); } function liquidatePortion(uint256 collateralAmount_, uint256 maxReturnAmount_, bytes calldata data_) external override whenProtocolNotPaused lock { // Transfer a requested amount of collateralAsset to the borrwer. require(ERC20Helper.transfer(collateralAsset, msg.sender, collateralAmount_), "LIQ:LP:TRANSFER"); // Perform a low-level call to msg.sender, allowing a swap strategy to be executed with the transferred collateral. msg.sender.call(data_); // Calculate the amount of fundsAsset required based on the amount of collateralAsset borrowed. uint256 returnAmount = getExpectedAmount(collateralAmount_); require(returnAmount <= maxReturnAmount_, "LIQ:LP:MAX_RETURN_EXCEEDED"); emit PortionLiquidated(collateralAmount_, returnAmount); // Pull required amount of fundsAsset from the borrower, if this amount of funds cannot be recovered atomically, revert. require(ERC20Helper.transferFrom(fundsAsset, msg.sender, destination, returnAmount), "LIQ:LP:TRANSFER_FROM"); } } /// @title An implementation that is to be proxied, must implement IProxied. interface IProxied { /** * @dev The address of the proxy factory. */ function factory() external view returns (address factory_); /** * @dev The address of the implementation contract being proxied. */ function implementation() external view returns (address implementation_); /** * @dev Modifies the proxy's implementation address. * @param newImplementation_ The address of an implementation contract. */ function setImplementation(address newImplementation_) external; /** * @dev Modifies the proxy's storage by delegate-calling a migrator contract with some arguments. * Access control logic critical since caller can force a selfdestruct via a malicious `migrator_` which is delegatecalled. * @param migrator_ The address of a migrator contract. * @param arguments_ Some encoded arguments to use for the migration. */ function migrate(address migrator_, bytes calldata arguments_) external; } /// @title A Maple implementation that is to be proxied, must implement IMapleProxied. interface IMapleProxied is IProxied { /** * @dev The instance was upgraded. * @param toVersion_ The new version of the loan. * @param arguments_ The upgrade arguments, if any. */ event Upgraded(uint256 toVersion_, bytes arguments_); /** * @dev Upgrades a contract implementation to a specific version. * Access control logic critical since caller can force a selfdestruct via a malicious `migrator_` which is delegatecalled. * @param toVersion_ The version to upgrade to. * @param arguments_ Some encoded arguments to use for the upgrade. */ function upgrade(uint256 toVersion_, bytes calldata arguments_) external; } /// @title DebtLocker interacts with Loans on behalf of PoolV1. interface IDebtLocker is IMapleProxied { /**************/ /*** Events ***/ /**************/ /** * @dev Emitted when `setAllowedSlippage` is called. * @param newSlippage_ New value for `allowedSlippage`. */ event AllowedSlippageSet(uint256 newSlippage_); /** * @dev Emitted when `setAuctioneer` is called. * @param newAuctioneer_ New value for `auctioneer` in Liquidator. */ event AuctioneerSet(address newAuctioneer_); /** * @dev Emitted when `fundsToCapture` is set. * @param amount_ The amount of funds that will be captured next claim. */ event FundsToCaptureSet(uint256 amount_); /** * @dev Emitted when `stopLiquidation` is called. */ event LiquidationStopped(); /** * @dev Emitted when `setMinRatio` is called. * @param newMinRatio_ New value for `minRatio`. */ event MinRatioSet(uint256 newMinRatio_); /*****************/ /*** Functions ***/ /*****************/ /** * @dev Accept the new loan terms and trigger a refinance. * @param refinancer_ The address of the refinancer contract. * @param calls_ The array of encoded data that are to be executed as delegatecalls by the refinancer. * @param amount_ The amount of `fundsAsset` that is to be sent to the Loan as part of the transaction. */ function acceptNewTerms(address refinancer_, bytes[] calldata calls_, uint256 amount_) external; /** * @dev Claims funds to send to Pool. Handles funds from payments and liquidations. * Only the Pool can call this function. * @return details_ * [0] => Total Claimed. * [1] => Interest Claimed. * [2] => Principal Claimed. * [3] => Pool Delegate Fees Claimed. * [4] => Excess Returned Claimed. * [5] => Amount Recovered (from Liquidation). * [6] => Default Suffered. */ function claim() external returns (uint256[7] memory details_); /** * @dev Allows the poolDelegate to pull some funds from liquidator contract. * @param liquidator_ The liquidator to which pull funds from. * @param token_ The token address of the funds. * @param destination_ The destination address of captured funds. * @param amount_ The amount to pull. */ function pullFundsFromLiquidator(address liquidator_, address token_, address destination_, uint256 amount_) external; /** * @dev Returns the address of the Pool Delegate that has control of the DebtLocker. */ function poolDelegate() external view returns (address poolDelegate_); /** * @dev Repossesses funds and collateral from a loan and transfers them to the Liquidator. */ function triggerDefault() external; /** * @dev Sets the allowed slippage for auctioneer (used to determine expected amount to be returned in flash loan). * @param allowedSlippage_ Basis points representation of allowed percent slippage from market price. */ function setAllowedSlippage(uint256 allowedSlippage_) external; /** * @dev Sets the auctioneer contract for the liquidator. * @param auctioneer_ Address of auctioneer contract. */ function setAuctioneer(address auctioneer_) external; /** * @dev Sets the minimum "price" for auctioneer (used to determine expected amount to be returned in flash loan). * @param minRatio_ Price in fundsAsset precision (e.g., 10 * 10 ** 6 for $10 price for USDC). */ function setMinRatio(uint256 minRatio_) external; /** * @dev Returns the expected amount to be returned to the liquidator during a flash borrower liquidation. * @param swapAmount_ Amount of collateralAsset being swapped. * @return returnAmount_ Amount of fundsAsset that must be returned in the same transaction. */ function getExpectedAmount(uint256 swapAmount_) external view returns (uint256 returnAmount_); /** * @dev Returns the expected amount to be returned to the liquidator during a flash borrower liquidation. * @param amount_ The amount of funds that should be captured next claim. */ function setFundsToCapture(uint256 amount_) external; /** * @dev Called by the PoolDelegate in case of a DoS, where a user transfers small amounts of collateralAsset into the Liquidator * to make `_isLiquidationActive` remain true. * CALLING THIS MAY RESULT IN RECOGNIZED LOSSES IN POOL ACCOUNTING. CONSULT MAPLE TEAM FOR GUIDANCE. */ function stopLiquidation() external; /*************/ /*** State ***/ /*************/ /** * @dev The Loan contract this locker is holding tokens for. */ function loan() external view returns (address loan_); /** * @dev The address of the liquidator. */ function liquidator() external view returns (address liquidator_); /** * @dev The owner of this Locker (the Pool). */ function pool() external view returns (address pool_); /** * @dev The maximum slippage allowed during liquidations. */ function allowedSlippage() external view returns (uint256 allowedSlippage_); /** * @dev The amount in funds asset recovered during liquidations. */ function amountRecovered() external view returns (uint256 amountRecovered_); /** * @dev The minimum exchange ration between funds asset and collateral asset. */ function minRatio() external view returns (uint256 minRatio_); /** * @dev Returns the principal that was present at the time of last claim. */ function principalRemainingAtLastClaim() external view returns (uint256 principalRemainingAtLastClaim_); /** * @dev Returns if the funds have been repossessed. */ function repossessed() external view returns (bool repossessed_); /** * @dev Returns the amount of funds that will be captured next claim. */ function fundsToCapture() external view returns (uint256 fundsToCapture_); } /// @title DebtLockerStorage maps the storage layout of a DebtLocker. contract DebtLockerStorage { address internal _liquidator; address internal _loan; address internal _pool; bool internal _repossessed; uint256 internal _allowedSlippage; uint256 internal _amountRecovered; uint256 internal _fundsToCapture; uint256 internal _minRatio; uint256 internal _principalRemainingAtLastClaim; } abstract contract SlotManipulatable { function _getReferenceTypeSlot(bytes32 slot_, bytes32 key_) internal pure returns (bytes32 value_) { return keccak256(abi.encodePacked(key_, slot_)); } function _getSlotValue(bytes32 slot_) internal view returns (bytes32 value_) { assembly { value_ := sload(slot_) } } function _setSlotValue(bytes32 slot_, bytes32 value_) internal { assembly { sstore(slot_, value_) } } } /// @title An implementation that is to be proxied, will need ProxiedInternals. abstract contract ProxiedInternals is SlotManipulatable { /// @dev Storage slot with the address of the current factory. `keccak256('eip1967.proxy.factory') - 1`. bytes32 private constant FACTORY_SLOT = bytes32(0x7a45a402e4cb6e08ebc196f20f66d5d30e67285a2a8aa80503fa409e727a4af1); /// @dev Storage slot with the address of the current factory. `keccak256('eip1967.proxy.implementation') - 1`. bytes32 private constant IMPLEMENTATION_SLOT = bytes32(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc); /// @dev Delegatecalls to a migrator contract to manipulate storage during an initialization or migration. function _migrate(address migrator_, bytes calldata arguments_) internal virtual returns (bool success_) { uint256 size; assembly { size := extcodesize(migrator_) } if (size == uint256(0)) return false; ( success_, ) = migrator_.delegatecall(arguments_); } /// @dev Sets the factory address in storage. function _setFactory(address factory_) internal virtual returns (bool success_) { _setSlotValue(FACTORY_SLOT, bytes32(uint256(uint160(factory_)))); return true; } /// @dev Sets the implementation address in storage. function _setImplementation(address implementation_) internal virtual returns (bool success_) { _setSlotValue(IMPLEMENTATION_SLOT, bytes32(uint256(uint160(implementation_)))); return true; } /// @dev Returns the factory address. function _factory() internal view virtual returns (address factory_) { return address(uint160(uint256(_getSlotValue(FACTORY_SLOT)))); } /// @dev Returns the implementation address. function _implementation() internal view virtual returns (address implementation_) { return address(uint160(uint256(_getSlotValue(IMPLEMENTATION_SLOT)))); } } /// @title A Maple implementation that is to be proxied, will need MapleProxiedInternals. abstract contract MapleProxiedInternals is ProxiedInternals {} /// @title DebtLocker interacts with Loans on behalf of PoolV1. contract DebtLocker is IDebtLocker, DebtLockerStorage, MapleProxiedInternals { /*****************/ /*** Modifiers ***/ /*****************/ modifier whenProtocolNotPaused() { require(!IMapleGlobalsLike(_getGlobals()).protocolPaused(), "DL:PROTOCOL_PAUSED"); _; } /********************************/ /*** Administrative Functions ***/ /********************************/ function migrate(address migrator_, bytes calldata arguments_) external override { require(msg.sender == _factory(), "DL:M:NOT_FACTORY"); require(_migrate(migrator_, arguments_), "DL:M:FAILED"); } function setImplementation(address newImplementation_) external override { require(msg.sender == _factory(), "DL:SI:NOT_FACTORY"); require(_setImplementation(newImplementation_), "DL:SI:FAILED"); } function upgrade(uint256 toVersion_, bytes calldata arguments_) external override { require(msg.sender == _getPoolDelegate(), "DL:U:NOT_POOL_DELEGATE"); emit Upgraded(toVersion_, arguments_); IMapleProxyFactoryLike(_factory()).upgradeInstance(toVersion_, arguments_); } /*******************************/ /*** Pool Delegate Functions ***/ /*******************************/ function acceptNewTerms(address refinancer_, bytes[] calldata calls_, uint256 amount_) external override whenProtocolNotPaused { require(msg.sender == _getPoolDelegate(), "DL:ANT:NOT_PD"); address loanAddress = _loan; require( (IMapleLoanLike(loanAddress).claimableFunds() + _fundsToCapture == uint256(0)) && (IMapleLoanLike(loanAddress).principal() == _principalRemainingAtLastClaim), "DL:ANT:NEED_TO_CLAIM" ); require( amount_ == uint256(0) || ERC20Helper.transfer(IMapleLoanLike(loanAddress).fundsAsset(), loanAddress, amount_), "DL:ANT:TRANSFER_FAILED" ); IMapleLoanLike(loanAddress).acceptNewTerms(refinancer_, calls_, uint256(0)); // NOTE: This must be set after accepting the new terms, which affects the loan principal. _principalRemainingAtLastClaim = IMapleLoanLike(loanAddress).principal(); } function claim() external override whenProtocolNotPaused returns (uint256[7] memory details_) { require(msg.sender == _pool, "DL:C:NOT_POOL"); return _repossessed ? _handleClaimOfRepossessed(msg.sender, _loan) : _handleClaim(msg.sender, _loan); } function pullFundsFromLiquidator(address liquidator_, address token_, address destination_, uint256 amount_) external override { require(msg.sender == _getPoolDelegate(), "DL:SA:NOT_PD"); Liquidator(liquidator_).pullFunds(token_, destination_, amount_); } function setAllowedSlippage(uint256 allowedSlippage_) external override whenProtocolNotPaused { require(msg.sender == _getPoolDelegate(), "DL:SAS:NOT_PD"); require(allowedSlippage_ <= uint256(10_000), "DL:SAS:INVALID_SLIPPAGE"); emit AllowedSlippageSet(_allowedSlippage = allowedSlippage_); } function setAuctioneer(address auctioneer_) external override whenProtocolNotPaused { require(msg.sender == _getPoolDelegate(), "DL:SA:NOT_PD"); emit AuctioneerSet(auctioneer_); Liquidator(_liquidator).setAuctioneer(auctioneer_); } function setFundsToCapture(uint256 amount_) override external whenProtocolNotPaused { require(msg.sender == _getPoolDelegate(), "DL:SFTC:NOT_PD"); emit FundsToCaptureSet(_fundsToCapture = amount_); } function setMinRatio(uint256 minRatio_) external override whenProtocolNotPaused { require(msg.sender == _getPoolDelegate(), "DL:SMR:NOT_PD"); emit MinRatioSet(_minRatio = minRatio_); } // Pool delegate can prematurely stop liquidation when there's still significant amount to be liquidated. function stopLiquidation() external override { require(msg.sender == _getPoolDelegate(), "DL:SL:NOT_PD"); _liquidator = address(0); emit LiquidationStopped(); } function triggerDefault() external override whenProtocolNotPaused { require(msg.sender == _pool, "DL:TD:NOT_POOL"); address loanAddress = _loan; require( (IMapleLoanLike(loanAddress).claimableFunds() == uint256(0)) && (IMapleLoanLike(loanAddress).principal() == _principalRemainingAtLastClaim), "DL:TD:NEED_TO_CLAIM" ); _repossessed = true; // Ensure that principal is always up to date, claim function will clear out all payments, but on refinance we need to ensure that // accounting is updated properly when principal is updated and there are no claimable funds. // Repossess collateral and funds from Loan. ( uint256 collateralAssetAmount, ) = IMapleLoanLike(loanAddress).repossess(address(this)); address collateralAsset = IMapleLoanLike(loanAddress).collateralAsset(); address fundsAsset = IMapleLoanLike(loanAddress).fundsAsset(); if (collateralAsset == fundsAsset || collateralAssetAmount == uint256(0)) return; // Deploy Liquidator contract and transfer collateral. require( ERC20Helper.transfer( collateralAsset, _liquidator = address(new Liquidator(address(this), collateralAsset, fundsAsset, address(this), address(this), _getGlobals())), collateralAssetAmount ), "DL:TD:TRANSFER" ); } /**************************/ /*** Internal Functions ***/ /**************************/ function _handleClaim(address pool_, address loan_) internal returns (uint256[7] memory details_) { // Get loan state variables needed uint256 claimableFunds = IMapleLoanLike(loan_).claimableFunds(); require(claimableFunds > uint256(0), "DL:HC:NOTHING_TO_CLAIM"); // Send funds to pool IMapleLoanLike(loan_).claimFunds(claimableFunds, pool_); uint256 currentPrincipalRemaining = IMapleLoanLike(loan_).principal(); // Determine how much of `claimableFunds` is principal uint256 principalPortion = _principalRemainingAtLastClaim - currentPrincipalRemaining; // Update state variables _principalRemainingAtLastClaim = currentPrincipalRemaining; // Set return values // Note: All fees get deducted and transferred during `loan.fundLoan()` that omits the need to // return the fees distribution to the pool. details_[0] = claimableFunds; details_[1] = claimableFunds - principalPortion; details_[2] = principalPortion; uint256 amountOfFundsToCapture = _fundsToCapture; if (amountOfFundsToCapture > uint256(0)) { details_[0] += amountOfFundsToCapture; details_[2] += amountOfFundsToCapture; _fundsToCapture = uint256(0); require(ERC20Helper.transfer(IMapleLoanLike(loan_).fundsAsset(), pool_, amountOfFundsToCapture), "DL:HC:CAPTURE_FAILED"); } } function _handleClaimOfRepossessed(address pool_, address loan_) internal returns (uint256[7] memory details_) { require(!_isLiquidationActive(), "DL:HCOR:LIQ_NOT_FINISHED"); address fundsAsset = IMapleLoanLike(loan_).fundsAsset(); uint256 principalToCover = _principalRemainingAtLastClaim; // Principal remaining at time of liquidation uint256 fundsCaptured = _fundsToCapture; // Funds recovered from liquidation and any unclaimed previous payment amounts uint256 recoveredFunds = IERC20Like(fundsAsset).balanceOf(address(this)) - fundsCaptured; uint256 totalClaimed = recoveredFunds + fundsCaptured; // If `recoveredFunds` is greater than `principalToCover`, the remaining amount is treated as interest in the context of the pool. // If `recoveredFunds` is less than `principalToCover`, the difference is registered as a shortfall. details_[0] = totalClaimed; details_[1] = recoveredFunds > principalToCover ? recoveredFunds - principalToCover : uint256(0); details_[2] = fundsCaptured; details_[5] = recoveredFunds > principalToCover ? principalToCover : recoveredFunds; details_[6] = principalToCover > recoveredFunds ? principalToCover - recoveredFunds : uint256(0); _fundsToCapture = uint256(0); _repossessed = false; require(ERC20Helper.transfer(fundsAsset, pool_, totalClaimed), "DL:HCOR:TRANSFER"); } /**********************/ /*** View Functions ***/ /**********************/ function allowedSlippage() external view override returns (uint256 allowedSlippage_) { return _allowedSlippage; } function amountRecovered() external view override returns (uint256 amountRecovered_) { return _amountRecovered; } function factory() external view override returns (address factory_) { return _factory(); } function fundsToCapture() external view override returns (uint256 fundsToCapture_) { return _fundsToCapture; } function getExpectedAmount(uint256 swapAmount_) external view override whenProtocolNotPaused returns (uint256 returnAmount_) { address loanAddress = _loan; address collateralAsset = IMapleLoanLike(loanAddress).collateralAsset(); address fundsAsset = IMapleLoanLike(loanAddress).fundsAsset(); address globals = _getGlobals(); uint8 collateralAssetDecimals = IERC20Like(collateralAsset).decimals(); uint256 oracleAmount = swapAmount_ * IMapleGlobalsLike(globals).getLatestPrice(collateralAsset) // Convert from `fromAsset` value. * uint256(10) ** uint256(IERC20Like(fundsAsset).decimals()) // Convert to `toAsset` decimal precision. * (uint256(10_000) - _allowedSlippage) // Multiply by allowed slippage basis points / IMapleGlobalsLike(globals).getLatestPrice(fundsAsset) // Convert to `toAsset` value. / uint256(10) ** uint256(collateralAssetDecimals) // Convert from `fromAsset` decimal precision. / uint256(10_000); // Divide basis points for slippage. uint256 minRatioAmount = (swapAmount_ * _minRatio) / (uint256(10) ** collateralAssetDecimals); return oracleAmount > minRatioAmount ? oracleAmount : minRatioAmount; } function implementation() external view override returns (address implementation_) { return _implementation(); } function liquidator() external view override returns (address liquidator_) { return _liquidator; } function loan() external view override returns (address loan_) { return _loan; } function minRatio() external view override returns (uint256 minRatio_) { return _minRatio; } function pool() external view override returns (address pool_) { return _pool; } function poolDelegate() external override view returns (address poolDelegate_) { return _getPoolDelegate(); } function principalRemainingAtLastClaim() external view override returns (uint256 principalRemainingAtLastClaim_) { return _principalRemainingAtLastClaim; } function repossessed() external view override returns (bool repossessed_) { return _repossessed; } /*******************************/ /*** Internal View Functions ***/ /*******************************/ function _getGlobals() internal view returns (address globals_) { return IPoolFactoryLike(IPoolLike(_pool).superFactory()).globals(); } function _getPoolDelegate() internal view returns(address poolDelegate_) { return IPoolLike(_pool).poolDelegate(); } function _isLiquidationActive() internal view returns (bool isActive_) { address liquidatorAddress = _liquidator; return (liquidatorAddress != address(0)) && (IERC20Like(IMapleLoanLike(_loan).collateralAsset()).balanceOf(liquidatorAddress) != uint256(0)); } }
A Maple implementation that is to be proxied, must implement IMapleProxied.
interface IMapleProxied is IProxied { event Upgraded(uint256 toVersion_, bytes arguments_); function upgrade(uint256 toVersion_, bytes calldata arguments_) external; } }
11,977,380
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; // import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ReentrancyGuard.sol"; // PolkaBridgeFarm is the master of PolkaBridge. He can make PolkaBridge 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 PBR is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract PolkaBridgeFarm is Ownable, ReentrancyGuard { 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 PBRs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accPBRPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPBRPerShare` (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 lpAmount; // LP token amount in the pool. uint256 allocPoint; // How many allocation points assigned to this pool. PBRs to distribute per block. uint256 lastRewardBlock; // Last block number that PBRs distribution occurs. uint256 accPBRPerShare; // Accumulated PBRs per share, times 1e18. See below. } // The PBR TOKEN! address public polkaBridge; // PBR tokens created per block. uint256 public PBRPerBlock; // Bonus muliplier for early polkaBridge makers. uint256 public constant BONUS_MULTIPLIER = 1; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when PBR mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, bool withUpdate); event LogSetPool(uint256 indexed pid, uint256 allocPoint, bool withUpdate); event LogUpdatePool(uint256 indexed pid, uint256 lastRewardBlock, uint256 lpSupply, uint256 accPBRPerShare); constructor( address _polkaBridge, uint256 _PBRPerBlock, uint256 _startBlock ) { polkaBridge = _polkaBridge; PBRPerBlock = _PBRPerBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } function changePBRBlock(uint256 _PBRPerBlock) external onlyOwner { PBRPerBlock = _PBRPerBlock; } // 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 ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, lpAmount: 0, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accPBRPerShare: 0 }) ); emit LogPoolAddition(poolInfo.length - 1, _allocPoint, _lpToken, _withUpdate); } // Update the given pool's PBR allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if(_withUpdate) { massUpdatePools(); } else { updatePool(_pid); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; emit LogSetPool(_pid, _allocPoint, _withUpdate); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to - _from * BONUS_MULTIPLIER; } // View function to see pending PBRs on frontend. function pendingPBR(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accPBRPerShare = pool.accPBRPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 PBRReward = multiplier * PBRPerBlock * pool.allocPoint / totalAllocPoint; accPBRPerShare = accPBRPerShare + PBRReward * 1e18 / lpSupply; } return user.amount * accPBRPerShare / 1e18 - user.rewardDebt; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 PBRReward = multiplier * PBRPerBlock * pool.allocPoint / totalAllocPoint; pool.accPBRPerShare = pool.accPBRPerShare + PBRReward * 1e18 / lpSupply; pool.lastRewardBlock = block.number; emit LogUpdatePool(_pid, pool.lastRewardBlock, lpSupply, pool.accPBRPerShare); } // Harvest function harvest(uint256 _pid) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount * pool.accPBRPerShare / 1e18 - user.rewardDebt; IERC20(polkaBridge).safeTransfer(msg.sender, pending); } // pool.lpToken.safeTransferFrom( // address(msg.sender), // address(this), // _amount // ); // user.amount = user.amount + _amount; user.rewardDebt = user.amount * pool.accPBRPerShare / 1e18; // emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to PolkaBridgeFarm for PBR allocation. function deposit(uint256 _pid, uint256 _amount) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount * pool.accPBRPerShare / 1e18 - user.rewardDebt; IERC20(polkaBridge).safeTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount + _amount; pool.lpAmount = pool.lpAmount + _amount; user.rewardDebt = user.amount * pool.accPBRPerShare / 1e18; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from PolkaBridgeFarm. function withdraw(uint256 _pid, uint256 _amount) external nonReentrant { 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 * pool.accPBRPerShare / 1e18 - user.rewardDebt; IERC20(polkaBridge).safeTransfer(msg.sender, pending); user.amount = user.amount - _amount; pool.lpAmount = pool.lpAmount - _amount; user.rewardDebt = user.amount * pool.accPBRPerShare / 1e18; pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); pool.lpAmount = pool.lpAmount - user.amount; user.amount = 0; user.rewardDebt = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; abstract contract ReentrancyGuard { 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 Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
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 ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, lpAmount: 0, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accPBRPerShare: 0 }) ); emit LogPoolAddition(poolInfo.length - 1, _allocPoint, _lpToken, _withUpdate); }
1,146,442
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 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 ERC721 interface * @dev see https://github.com/ethereum/eips/issues/721 */ contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function transfer(address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) public; function takeOwnership(uint256 _tokenId) public; } /// @title CryptoCelebritiesMarket /// @dev Contains models, variables, and internal methods for sales. contract CelebrityMarket is Pausable{ ERC721 ccContract; // Represents a sale item on an NFT struct Sale { // Current owner of NFT address seller; // Price (in wei) at beginning of a sale item uint256 salePrice; // Time when sale started // NOTE: 0 if this sale has been concluded uint64 startedAt; } // Owner of this contract address public owner; // Map from token ID to their corresponding sale. mapping (uint256 => Sale) tokenIdToSale; event SaleCreated(address seller,uint256 tokenId, uint256 salePrice, uint256 startedAt); event SaleSuccessful(address seller, uint256 tokenId, uint256 totalPrice, address winner); event SaleCancelled(address seller, uint256 tokenId); event SaleUpdated(address seller, uint256 tokenId, uint256 oldPrice, uint256 newPrice); /// @dev Constructor registers the nft address (CCAddress) /// @param _ccAddress - Address of the CryptoCelebrities contract function CelebrityMarket(address _ccAddress) public { ccContract = ERC721(_ccAddress); owner = msg.sender; } /// @dev DON'T give me your money. function() external {} /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { require( msg.sender == owner ); msg.sender.transfer(address(this).balance); } /// @dev Creates and begins a new sale. /// @param _tokenId - ID of token to sell, sender must be owner. /// @param _salePrice - Sale Price of item (in wei). function createSale( uint256 _tokenId, uint256 _salePrice ) public whenNotPaused { require(_owns(msg.sender, _tokenId)); _escrow(_tokenId); Sale memory sale = Sale( msg.sender, _salePrice, uint64(now) ); _addSale(_tokenId, sale); } /// @dev Update sale price of a sale item that hasn't been completed yet. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on sale /// @param _newPrice - new sale price function updateSalePrice(uint256 _tokenId, uint256 _newPrice) public { Sale storage sale = tokenIdToSale[_tokenId]; require(_isOnSale(sale)); address seller = sale.seller; require(msg.sender == seller); _updateSalePrice(_tokenId, _newPrice, seller); } /// @dev Allows to buy a sale item, completing the sale and transferring /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to buy. function buy(uint256 _tokenId) public payable whenNotPaused { // _bid will throw if the bid or funds transfer fails _buy(_tokenId, msg.value); _transfer(msg.sender, _tokenId); } /// @dev Cancels a sale that hasn't been completed yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on sale function cancelSale(uint256 _tokenId) public { Sale storage sale = tokenIdToSale[_tokenId]; require(_isOnSale(sale)); address seller = sale.seller; require(msg.sender == seller); _cancelSale(_tokenId, seller); } /// @dev Cancels a sale when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on sale to cancel. function cancelSaleWhenPaused(uint256 _tokenId) whenPaused onlyOwner public { Sale storage sale = tokenIdToSale[_tokenId]; require(_isOnSale(sale)); _cancelSale(_tokenId, sale.seller); } /// @dev Returns sale info for an NFT on sale. /// @param _tokenId - ID of NFT on sale. function getSale(uint256 _tokenId) public view returns ( address seller, uint256 salePrice, uint256 startedAt ) { Sale storage sale = tokenIdToSale[_tokenId]; require(_isOnSale(sale)); return ( sale.seller, sale.salePrice, sale.startedAt ); } /// @dev Returns the current price of a sale item. /// @param _tokenId - ID of the token price we are checking. function getSalePrice(uint256 _tokenId) public view returns (uint256) { Sale storage sale = tokenIdToSale[_tokenId]; require(_isOnSale(sale)); return sale.salePrice; } /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (ccContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the CCToken, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _tokenId - ID of token whose approval to verify. function _escrow(uint256 _tokenId) internal { // it will throw if transfer fails ccContract.takeOwnership(_tokenId); } /// @dev Transfers a CCToken owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails ccContract.transfer(_receiver, _tokenId); } /// @dev Adds a sale to the list of open sales. Also fires the /// SaleCreated event. /// @param _tokenId The ID of the token to be put on sale. /// @param _sale Sale to add. function _addSale(uint256 _tokenId, Sale _sale) internal { tokenIdToSale[_tokenId] = _sale; SaleCreated( address(_sale.seller), uint256(_tokenId), uint256(_sale.salePrice), uint256(_sale.startedAt) ); } /// @dev Cancels a sale unconditionally. function _cancelSale(uint256 _tokenId, address _seller) internal { _removeSale(_tokenId); _transfer(_seller, _tokenId); SaleCancelled(_seller, _tokenId); } /// @dev updates sale price of item function _updateSalePrice(uint256 _tokenId, uint256 _newPrice, address _seller) internal { // Get a reference to the sale struct Sale storage sale = tokenIdToSale[_tokenId]; uint256 oldPrice = sale.salePrice; sale.salePrice = _newPrice; SaleUpdated(_seller, _tokenId, oldPrice, _newPrice); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _buy(uint256 _tokenId, uint256 _amount) internal returns (uint256) { // Get a reference to the sale struct Sale storage sale = tokenIdToSale[_tokenId]; // Explicitly check that this sale is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an sale object that is all zeros.) require(_isOnSale(sale)); // Check that the incoming bid is higher than the current // price uint256 price = sale.salePrice; require(_amount >= price); // Grab a reference to the seller before the sale struct // gets deleted. address seller = sale.seller; // The bid is good! Remove the sale before sending the fees // to the sender so we can't have a reentrancy attack. _removeSale(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the market owner's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 ownerCut = _computeCut(price); uint256 sellerProceeds = price - ownerCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the sale item // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelSale(). ) seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 amountExcess = _amount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the sale is // removed before any transfers occur. msg.sender.transfer(amountExcess); // Tell the world! SaleSuccessful(seller, _tokenId, price, msg.sender); return price; } /// @dev Removes a sale item from the list of open sales. /// @param _tokenId - ID of NFT on sale. function _removeSale(uint256 _tokenId) internal { delete tokenIdToSale[_tokenId]; } /// @dev Returns true if the NFT is on sale. /// @param _sale - Sale to check. function _isOnSale(Sale storage _sale) internal view returns (bool) { return (_sale.startedAt > 0); } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal pure returns (uint256) { return uint256(SafeMath.div(SafeMath.mul(_price, 6), 100)); } }
Update sale price of a sale item that hasn't been completed yet. This is a state-modifying function that can be called while the contract is paused. _tokenId - ID of token on sale _newPrice - new sale price
function updateSalePrice(uint256 _tokenId, uint256 _newPrice) public { Sale storage sale = tokenIdToSale[_tokenId]; require(_isOnSale(sale)); address seller = sale.seller; require(msg.sender == seller); _updateSalePrice(_tokenId, _newPrice, seller); }
1,749,273
// Sources flattened with hardhat v2.6.8 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 @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/token/ERC20/utils/[email protected] pragma solidity ^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 Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts/utils/structs/[email protected] pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File @openzeppelin/contracts/security/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/pool/HCPEPool.sol pragma solidity >=0.8.9; /** * @title HC PE Pool Contract * @author HASHLAND-TEAM * @notice In this contract PE round users can harvest HC */ contract HCPEPool is ReentrancyGuard { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; IERC20 public hc; uint256 public constant blockPerDay = 28800; uint256 public constant blockPerYear = blockPerDay * 365; uint256 public constant blockPerQuarter = blockPerYear / 4; uint256 public constant hcStartBlock = 12507000; uint256 public constant releaseStartBlock = hcStartBlock + blockPerQuarter; uint256 public constant releaseEndBlock = releaseStartBlock + blockPerYear; uint256 public constant releasedTotalToken = (120e4 * 1e18 * 90) / 100; uint256 public constant tokenPerBlock = releasedTotalToken / blockPerYear; uint256 public lastRewardBlock = releaseStartBlock; uint256 public stake; uint256 public accTokenPerStake; uint256 public releasedToken; uint256 public harvestedToken; mapping(address => uint256) public userStake; mapping(address => uint256) public userLastAccTokenPerStake; mapping(address => uint256) public userStoredToken; mapping(address => uint256) public userHarvestedToken; EnumerableSet.AddressSet private users; event HarvestToken(address indexed user, uint256 amount); /** * @param hcAddr Initialize HC Address * @param userAddrs Initialize users * @param userStakes Initialize user stake */ constructor( address hcAddr, address[] memory userAddrs, uint256[] memory userStakes ) { require( userAddrs.length == userStakes.length, "Data length does not match" ); hc = IERC20(hcAddr); for (uint256 i = 0; i < userAddrs.length; i++) { userStake[userAddrs[i]] += userStakes[i]; stake += userStakes[i]; users.add(userAddrs[i]); } } /** * @dev Harvest Token */ function harvestToken() external nonReentrant { updatePool(); uint256 pendingToken = (userStake[msg.sender] * (accTokenPerStake - userLastAccTokenPerStake[msg.sender])) / 1e18; uint256 amount = userStoredToken[msg.sender] + pendingToken; require(amount > 0, "Not enough token to harvest"); userStoredToken[msg.sender] = 0; userLastAccTokenPerStake[msg.sender] = accTokenPerStake; userHarvestedToken[msg.sender] += amount; harvestedToken += amount; hc.safeTransfer(msg.sender, amount); emit HarvestToken(msg.sender, amount); } /** * @dev Get Token Total Rewards of a User */ function getTokenTotalRewards(address user) external view returns (uint256) { return userHarvestedToken[user] + getTokenRewards(user); } /** * @dev Get Users Length */ function getUsersLength() external view returns (uint256) { return users.length(); } /** * @dev Get Users by Size */ function getUsersBySize(uint256 cursor, uint256 size) external view returns (address[] memory, uint256) { uint256 length = size; if (length > users.length() - cursor) { length = users.length() - cursor; } address[] memory values = new address[](length); for (uint256 i = 0; i < length; i++) { values[i] = users.at(cursor + i); } return (values, cursor + length); } /** * @dev Update Pool */ function updatePool() public { if (block.number <= lastRewardBlock) { return; } uint256 rewardsBlock = releaseEndBlock < block.number ? releaseEndBlock : block.number; if (rewardsBlock > lastRewardBlock && stake > 0) { uint256 amount = tokenPerBlock * (rewardsBlock - lastRewardBlock); accTokenPerStake += (amount * 1e18) / stake; releasedToken += amount; } lastRewardBlock = block.number; } /** * @dev Get Token Rewards of a User */ function getTokenRewards(address user) public view returns (uint256) { uint256 accTokenPerStakeTemp = accTokenPerStake; uint256 rewardsBlock = releaseEndBlock < block.number ? releaseEndBlock : block.number; if (rewardsBlock > lastRewardBlock && stake > 0) { accTokenPerStakeTemp += (tokenPerBlock * (rewardsBlock - lastRewardBlock) * 1e18) / stake; } return userStoredToken[user] + ((userStake[user] * (accTokenPerStakeTemp - userLastAccTokenPerStake[user])) / 1e18); } }
Harvest Token/
function harvestToken() external nonReentrant { updatePool(); uint256 pendingToken = (userStake[msg.sender] * (accTokenPerStake - userLastAccTokenPerStake[msg.sender])) / 1e18; uint256 amount = userStoredToken[msg.sender] + pendingToken; require(amount > 0, "Not enough token to harvest"); userStoredToken[msg.sender] = 0; userLastAccTokenPerStake[msg.sender] = accTokenPerStake; userHarvestedToken[msg.sender] += amount; harvestedToken += amount; hc.safeTransfer(msg.sender, amount); emit HarvestToken(msg.sender, amount); }
12,868,304
/* Copyright 2018 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.5.9; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/LibBytes.sol"; import "@0x/contracts-utils/contracts/src/LibEIP1271.sol"; import "@0x/contracts-utils/contracts/src/LibRichErrors.sol"; import "@0x/contracts-utils/contracts/src/ReentrancyGuard.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol"; import "./interfaces/IWallet.sol"; import "./interfaces/IEIP1271Wallet.sol"; import "./interfaces/IExchangeRichErrors.sol"; import "./interfaces/ISignatureValidator.sol"; import "./LibExchangeRichErrors.sol"; import "./MixinTransactions.sol"; contract MixinSignatureValidator is ReentrancyGuard, LibEIP1271, LibOrder, LibZeroExTransaction, ISignatureValidator, MixinTransactions { using LibBytes for bytes; // Mapping of hash => signer => signed mapping (bytes32 => mapping (address => bool)) public preSigned; // Mapping of signer => validator => approved mapping (address => mapping (address => bool)) public allowedValidators; /// @dev Approves a hash on-chain. /// After presigning a hash, the preSign signature type will become valid for that hash and signer. /// @param hash Any 32-byte hash. function preSign(bytes32 hash) external nonReentrant { address signerAddress = _getCurrentContextAddress(); preSigned[hash][signerAddress] = true; } /// @dev Approves/unnapproves a Validator contract to verify signatures on signer's behalf /// using the `Validator` signature type. /// @param validatorAddress Address of Validator contract. /// @param approval Approval or disapproval of Validator contract. function setSignatureValidatorApproval( address validatorAddress, bool approval ) external nonReentrant { address signerAddress = _getCurrentContextAddress(); allowedValidators[signerAddress][validatorAddress] = approval; emit SignatureValidatorApproval( signerAddress, validatorAddress, approval ); } /// @dev Verifies that a hash has been signed by the given signer. /// @param hash Any 32-byte hash. /// @param signerAddress Address that should have signed the given hash. /// @param signature Proof that the hash has been signed by signer. /// @return isValid `true` if the signature is valid for the given hash and signer. function isValidHashSignature( bytes32 hash, address signerAddress, bytes memory signature ) public view returns (bool isValid) { SignatureType signatureType = _readValidSignatureType( hash, signerAddress, signature ); // Only hash-compatible signature types can be handled by this // function. if ( signatureType == SignatureType.Validator || signatureType == SignatureType.EIP1271Wallet ) { LibRichErrors._rrevert(LibExchangeRichErrors.SignatureError( IExchangeRichErrors.SignatureErrorCodes.INAPPROPRIATE_SIGNATURE_TYPE, hash, signerAddress, signature )); } return _validateHashSignatureTypes( signatureType, hash, signerAddress, signature ); } /// @dev Verifies that a signature for an order is valid. /// @param order The order. /// @param signerAddress Address that should have signed the given order. /// @param signature Proof that the order has been signed by signer. /// @return isValid `true` if the signature is valid for the given order and signer. function isValidOrderSignature( Order memory order, address signerAddress, bytes memory signature ) public view returns (bool isValid) { bytes32 orderHash = getOrderHash(order); return _isValidOrderWithHashSignature( order, orderHash, signerAddress, signature ); } /// @dev Verifies that a signature for a transaction is valid. /// @param transaction The transaction. /// @param signerAddress Address that should have signed the given order. /// @param signature Proof that the order has been signed by signer. /// @return isValid `true` if the signature is valid for the given transaction and signer. function isValidTransactionSignature( ZeroExTransaction memory transaction, address signerAddress, bytes memory signature ) public view returns (bool isValid) { bytes32 transactionHash = getTransactionHash(transaction); isValid = _isValidTransactionWithHashSignature( transaction, transactionHash, signerAddress, signature ); } /// @dev Checks if a signature is of a type that should be verified for /// every action. /// @param hash The hash of the order/transaction. /// @param signerAddress The address of the signer. /// @param signature The signature for `hash`. /// @return needsRegularValidation True if the signature should be validated /// for every action. function doesSignatureRequireRegularValidation( bytes32 hash, address signerAddress, bytes memory signature ) public pure returns (bool needsRegularValidation) { SignatureType signatureType = _readValidSignatureType( hash, signerAddress, signature ); needsRegularValidation = signatureType == SignatureType.Wallet || signatureType == SignatureType.Validator || signatureType == SignatureType.EIP1271Wallet; } /// @dev Verifies that an order, with provided order hash, has been signed /// by the given signer. /// @param order The order. /// @param orderHash The hash of the order. /// @param signerAddress Address that should have signed the.Signat given hash. /// @param signature Proof that the hash has been signed by signer. /// @return isValid True if the signature is valid for the given order and signer. function _isValidOrderWithHashSignature( Order memory order, bytes32 orderHash, address signerAddress, bytes memory signature ) internal view returns (bool isValid) { SignatureType signatureType = _readValidSignatureType( orderHash, signerAddress, signature ); if (signatureType == SignatureType.Validator) { // The entire order is verified by a validator contract. isValid = _validateBytesWithValidator( abi.encode(order, orderHash), orderHash, signerAddress, signature ); } else if (signatureType == SignatureType.EIP1271Wallet) { // The entire order is verified by a wallet contract. isValid = _validateBytesWithWallet( abi.encode(order, orderHash), orderHash, signerAddress, signature ); } else { // Otherwise, it's one of the hash-only signature types. isValid = _validateHashSignatureTypes( signatureType, orderHash, signerAddress, signature ); } } /// @dev Verifies that a transaction, with provided order hash, has been signed /// by the given signer. /// @param transaction The transaction. /// @param transactionHash The hash of the transaction. /// @param signerAddress Address that should have signed the.Signat given hash. /// @param signature Proof that the hash has been signed by signer. /// @return isValid True if the signature is valid for the given transaction and signer. function _isValidTransactionWithHashSignature( ZeroExTransaction memory transaction, bytes32 transactionHash, address signerAddress, bytes memory signature ) internal view returns (bool isValid) { SignatureType signatureType = _readValidSignatureType( transactionHash, signerAddress, signature ); if (signatureType == SignatureType.Validator) { // The entire transaction is verified by a validator contract. isValid = _validateBytesWithValidator( abi.encode(transaction, transactionHash), transactionHash, signerAddress, signature ); } else if (signatureType == SignatureType.EIP1271Wallet) { // The entire transaction is verified by a wallet contract. isValid = _validateBytesWithWallet( abi.encode(transaction, transactionHash), transactionHash, signerAddress, signature ); } else { // Otherwise, it's one of the hash-only signature types. isValid = _validateHashSignatureTypes( signatureType, transactionHash, signerAddress, signature ); } } /// Validates a hash-only signature type /// (anything but `Validator` and `EIP1271Wallet`). function _validateHashSignatureTypes( SignatureType signatureType, bytes32 hash, address signerAddress, bytes memory signature ) private view returns (bool isValid) { // Always invalid signature. // Like Illegal, this is always implicitly available and therefore // offered explicitly. It can be implicitly created by providing // a correctly formatted but incorrect signature. if (signatureType == SignatureType.Invalid) { if (signature.length != 1) { LibRichErrors._rrevert(LibExchangeRichErrors.SignatureError( IExchangeRichErrors.SignatureErrorCodes.INVALID_LENGTH, hash, signerAddress, signature )); } isValid = false; // Signature using EIP712 } else if (signatureType == SignatureType.EIP712) { if (signature.length != 66) { LibRichErrors._rrevert(LibExchangeRichErrors.SignatureError( IExchangeRichErrors.SignatureErrorCodes.INVALID_LENGTH, hash, signerAddress, signature )); } uint8 v = uint8(signature[0]); bytes32 r = signature.readBytes32(1); bytes32 s = signature.readBytes32(33); address recovered = ecrecover( hash, v, r, s ); isValid = signerAddress == recovered; // Signed using web3.eth_sign } else if (signatureType == SignatureType.EthSign) { if (signature.length != 66) { LibRichErrors._rrevert(LibExchangeRichErrors.SignatureError( IExchangeRichErrors.SignatureErrorCodes.INVALID_LENGTH, hash, signerAddress, signature )); } uint8 v = uint8(signature[0]); bytes32 r = signature.readBytes32(1); bytes32 s = signature.readBytes32(33); address recovered = ecrecover( keccak256(abi.encodePacked( "\x19Ethereum Signed Message:\n32", hash )), v, r, s ); isValid = signerAddress == recovered; // Signature verified by wallet contract. } else if (signatureType == SignatureType.Wallet) { isValid = _validateHashWithWallet( hash, signerAddress, signature ); // Otherwise, signatureType == SignatureType.PreSigned } else { assert(signatureType == SignatureType.PreSigned); // Signer signed hash previously using the preSign function. isValid = preSigned[hash][signerAddress]; } } /// Reads the `SignatureType` from the end of a signature and validates it. function _readValidSignatureType( bytes32 hash, address signerAddress, bytes memory signature ) private pure returns (SignatureType signatureType) { if (signature.length == 0) { LibRichErrors._rrevert(LibExchangeRichErrors.SignatureError( IExchangeRichErrors.SignatureErrorCodes.INVALID_LENGTH, hash, signerAddress, signature )); } // Read the last byte off of signature byte array. uint8 signatureTypeRaw = uint8(signature[signature.length - 1]); // Ensure signature is supported if (signatureTypeRaw >= uint8(SignatureType.NSignatureTypes)) { LibRichErrors._rrevert(LibExchangeRichErrors.SignatureError( IExchangeRichErrors.SignatureErrorCodes.UNSUPPORTED, hash, signerAddress, signature )); } // Always illegal signature. // This is always an implicit option since a signer can create a // signature array with invalid type or length. We may as well make // it an explicit option. This aids testing and analysis. It is // also the initialization value for the enum type. if (SignatureType(signatureTypeRaw) == SignatureType.Illegal) { LibRichErrors._rrevert(LibExchangeRichErrors.SignatureError( IExchangeRichErrors.SignatureErrorCodes.ILLEGAL, hash, signerAddress, signature )); } return SignatureType(signatureTypeRaw); } /// @dev Verifies a hash and signature using logic defined by Wallet contract. /// @param hash Any 32 byte hash. /// @param walletAddress Address that should have signed the given hash /// and defines its own signature verification method. /// @param signature Proof that the hash has been signed by signer. /// @return isValid True if the signature is validated by the Wallet. function _validateHashWithWallet( bytes32 hash, address walletAddress, bytes memory signature ) private view returns (bool isValid) { // A signature using this type should be encoded as: // | Offset | Length | Contents | // | 0x00 | x | Signature to validate | // | 0x00 + x | 1 | Signature type is always "\x04" | uint256 signatureLength = signature.length; // HACK(dorothy-zbornak): Temporarily shave the signature type // from the signature for the encode call then restore // it immediately after because we want to keep signatures intact. assembly { mstore(signature, sub(signatureLength, 1)) } // Encode the call data. bytes memory callData = abi.encodeWithSelector( IWallet(walletAddress).isValidSignature.selector, hash, signature ); // Restore the full signature. assembly { mstore(signature, signatureLength) } // Static call the verification function. (bool didSucceed, bytes memory returnData) = walletAddress.staticcall(callData); // Return data should be a single bool. if (didSucceed && returnData.length == 32) { return returnData.readUint256(0) == 1; } // Static call to verifier failed. LibRichErrors._rrevert(LibExchangeRichErrors.SignatureWalletError( hash, walletAddress, signature, returnData )); } /// @dev Verifies arbitrary data and a signature via an EIP1271 Wallet /// contract, where the wallet address is also the signer address. /// @param data Arbitrary signed data. /// @param hash The hash associated with the data. /// @param walletAddress Contract that will verify the data and signature. /// @param signature Proof that the data has been signed by signer. /// @return isValid True if the signature is validated by the Wallet. function _validateBytesWithWallet( bytes memory data, bytes32 hash, address walletAddress, bytes memory signature ) private view returns (bool isValid) { // A signature using this type should be encoded as: // | Offset | Length | Contents | // | 0x00 | x | Signature to validate | // | 0x00 + x | 1 | Signature type is always "\x07" | uint256 signatureLength = signature.length; // HACK(dorothy-zbornak): Temporarily shave the signature type // from the signature for the encode call then restore // it immediately after because we want to keep signatures intact. assembly { mstore(signature, sub(signatureLength, 1)) } // Encode the call data. bytes memory callData = abi.encodeWithSelector( IEIP1271Wallet(walletAddress).isValidSignature.selector, data, signature ); // Restore the full signature. assembly { mstore(signature, signatureLength) } // Static call the verification function. (bool didSucceed, bytes memory returnData) = walletAddress.staticcall(callData); // Return data should be the `EIP1271_MAGIC_VALUE`. if (didSucceed && returnData.length <= 32) { return returnData.readBytes4(0) == EIP1271_MAGIC_VALUE; } // Static call to verifier failed. LibRichErrors._rrevert(LibExchangeRichErrors.SignatureWalletError( hash, walletAddress, signature, returnData )); } /// @dev Verifies arbitrary data and a signature via an EIP1271 contract /// whose address is encoded in the signature. /// @param data Arbitrary signed data. /// @param hash The hash associated with the data. /// @param signerAddress Address that should have signed the given hash. /// @param signature Proof that the data has been signed by signer. /// @return isValid True if the signature is validated by the validator contract. function _validateBytesWithValidator( bytes memory data, bytes32 hash, address signerAddress, bytes memory signature ) private view returns (bool isValid) { // A signature using this type should be encoded as: // | Offset | Length | Contents | // | 0x00 | x | Signature to validate | // | 0x00 + x | 20 | Address of validator contract | // | 0x14 + x | 1 | Signature type is always "\x05" | uint256 signatureLength = signature.length; // Read the validator address from the signature. address validatorAddress = signature.readAddress(signatureLength - 21); // Ensure signer has approved validator. if (!allowedValidators[signerAddress][validatorAddress]) { LibRichErrors._rrevert(LibExchangeRichErrors.SignatureValidatorNotApprovedError( signerAddress, validatorAddress )); } // HACK(dorothy-zbornak): Temporarily shave the validator address // and signature type from the signature for the encode call then restore // it immediately after because we want to keep signatures intact. assembly { mstore(signature, sub(signatureLength, 21)) } // Encode the call data. bytes memory callData = abi.encodeWithSelector( IEIP1271Wallet(validatorAddress).isValidSignature.selector, data, signature ); // Restore the full signature. assembly { mstore(signature, signatureLength) } // Static call the verification function. (bool didSucceed, bytes memory returnData) = validatorAddress.staticcall(callData); // Return data should be the `EIP1271_MAGIC_VALUE`. if (didSucceed && returnData.length <= 32) { return returnData.readBytes4(0) == EIP1271_MAGIC_VALUE; } // Static call to verifier failed. LibRichErrors._rrevert(LibExchangeRichErrors.SignatureValidatorError( hash, signerAddress, validatorAddress, signature, returnData )); } }
Verifies arbitrary data and a signature via an EIP1271 Wallet contract, where the wallet address is also the signer address. data Arbitrary signed data. hash The hash associated with the data. walletAddress Contract that will verify the data and signature. signature Proof that the data has been signed by signer. return isValid True if the signature is validated by the Wallet. A signature using this type should be encoded as: | Offset | Length | Contents | | 0x00 | x | Signature to validate | | 0x00 + x | 1 | Signature type is always "\x07" | HACK(dorothy-zbornak): Temporarily shave the signature type from the signature for the encode call then restore it immediately after because we want to keep signatures intact. Restore the full signature. Return data should be the `EIP1271_MAGIC_VALUE`.
function _validateBytesWithWallet( bytes memory data, bytes32 hash, address walletAddress, bytes memory signature ) private view returns (bool isValid) { uint256 signatureLength = signature.length; assembly { mstore(signature, sub(signatureLength, 1)) } IEIP1271Wallet(walletAddress).isValidSignature.selector, data, signature ); assembly { mstore(signature, signatureLength) } if (didSucceed && returnData.length <= 32) { return returnData.readBytes4(0) == EIP1271_MAGIC_VALUE; } hash, walletAddress, signature, returnData )); }
12,546,256
pragma solidity ^0.5.0; import "./BackingContract.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; /** * @title BackedToken * @author Rosco Kalis <[email protected]> */ contract BackedToken is ERC20 { BackingContract public backingContract; event Buy(address indexed buyer, uint256 ethAmount, uint256 tokenPrice, uint256 tokenAmount); event Sell(address indexed seller, uint256 ethAmount, uint256 tokenPrice, uint256 tokenAmount); modifier onlyWhenBacked() { require(address(backingContract) != address(0), "Can only be executed with a backing contract"); _; } modifier onlyWhenNotBacked() { require(address(backingContract) == address(0), "Can only be executed without a backing contract"); _; } modifier onlyBackingContract() { require(msg.sender == address(backingContract), "Can only be executed by backing contract"); _; } /** * @dev Fallback payable function forwarding funds to the backing contract. */ function() external payable onlyWhenBacked { backingContract.deposit.value(msg.value)(); } /** * @notice Payable function used by the backing contract to put funds back in the backed token contract. */ function deposit() external payable onlyWhenBacked onlyBackingContract {} /** * @notice Backs this token using the passed backing contract address. * @dev Only used in initialisation. * @param backingContractAddress The address of a BackingContract that will back this token. */ function back(address payable backingContractAddress) external onlyWhenNotBacked { backingContract = BackingContract(backingContractAddress); } /** * @notice Buys an amount of tokens. * @dev Uses the conversion functions. * @dev Emits Buy event. */ function buy() external payable onlyWhenBacked { require(msg.value > 0, "A purchase should be made"); uint256 tokenAmount = convertEthToToken(msg.value); uint256 currentTokenPrice = tokenPrice(); _mint(msg.sender, tokenAmount); backingContract.deposit.value(msg.value)(); emit Buy(msg.sender, msg.value, currentTokenPrice, tokenAmount); } /** * @notice Sells an amount of tokens and withdraws the corresponding eth from the backing contract. * @dev Uses the conversion functions. * @dev Emits Sell event. * @param tokenAmount The amount of tokens to sell. */ function sell(uint256 tokenAmount) external onlyWhenBacked { require(tokenAmount <= balanceOf(msg.sender), "Can not divest more than investment"); uint256 ethAmount = convertTokenToEth(tokenAmount); uint256 currentTokenPrice = tokenPrice(); _burn(msg.sender, tokenAmount); backingContract.withdraw(ethAmount); msg.sender.transfer(ethAmount); emit Sell(msg.sender, ethAmount, currentTokenPrice, tokenAmount); } /** * @notice Returns the token price, which is derived from the backing contract's balance and total token supply. * @return The token price. */ function tokenPrice() public view onlyWhenBacked returns (uint256) { if (totalSupply() == 0 || backingContract.balanceForBacking() == 0) { return 1 ether; } return backingContract.balanceForBacking().mul(1 ether).div(totalSupply()); } /** * @notice Converts an amount of eth to an amount of tokens. * @param ethAmount The amount of eth to convert. */ function convertEthToToken(uint256 ethAmount) public view onlyWhenBacked returns (uint256) { return ethAmount.mul(1 ether).div(tokenPrice()); } /** * @notice Converts an amount of tokens to an amount of eth. * @param tokenAmount The amount of tokens to convert. */ function convertTokenToEth(uint256 tokenAmount) public view onlyWhenBacked returns (uint256) { return tokenPrice().mul(tokenAmount).div(1 ether); } }
Returns the token price, which is derived from the backing contract's balance and total token supply. return The token price./
function tokenPrice() public view onlyWhenBacked returns (uint256) { if (totalSupply() == 0 || backingContract.balanceForBacking() == 0) { return 1 ether; } return backingContract.balanceForBacking().mul(1 ether).div(totalSupply()); }
14,042,430
// hevm: flattened sources of src/Dpass.sol pragma solidity >=0.4.23 >=0.5.0 <0.6.0 >=0.5.5 <0.6.0 >=0.5.11 <0.6.0; ////// lib/ds-auth/src/auth.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } ////// lib/openzeppelin-contracts/src/GSN/Context.sol /* pragma solidity ^0.5.0; */ /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } ////// lib/openzeppelin-contracts/src/math/SafeMath.sol /* pragma solidity ^0.5.0; */ /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } ////// lib/openzeppelin-contracts/src/drafts/Counters.sol /* pragma solidity ^0.5.0; */ /* import "../math/SafeMath.sol"; */ /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } ////// lib/openzeppelin-contracts/src/introspection/IERC165.sol /* pragma solidity ^0.5.0; */ /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } ////// lib/openzeppelin-contracts/src/introspection/ERC165.sol /* pragma solidity ^0.5.0; */ /* import "./IERC165.sol"; */ /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } ////// lib/openzeppelin-contracts/src/token/ERC721/IERC721.sol /* pragma solidity ^0.5.0; */ /* import "../../introspection/IERC165.sol"; */ /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } ////// lib/openzeppelin-contracts/src/token/ERC721/IERC721Receiver.sol /* pragma solidity ^0.5.0; */ /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } ////// lib/openzeppelin-contracts/src/utils/Address.sol /* pragma solidity ^0.5.5; */ /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } ////// lib/openzeppelin-contracts/src/token/ERC721/ERC721.sol /* pragma solidity ^0.5.0; */ /* import "../../GSN/Context.sol"; */ /* import "./IERC721.sol"; */ /* import "./IERC721Receiver.sol"; */ /* import "../../math/SafeMath.sol"; */ /* import "../../utils/Address.sol"; */ /* import "../../drafts/Counters.sol"; */ /* import "../../introspection/ERC165.sol"; */ /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } ////// lib/openzeppelin-contracts/src/token/ERC721/IERC721Enumerable.sol /* pragma solidity ^0.5.0; */ /* import "./IERC721.sol"; */ /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } ////// lib/openzeppelin-contracts/src/token/ERC721/ERC721Enumerable.sol /* pragma solidity ^0.5.0; */ /* import "../../GSN/Context.sol"; */ /* import "./IERC721Enumerable.sol"; */ /* import "./ERC721.sol"; */ /* import "../../introspection/ERC165.sol"; */ /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.length--; _allTokensIndex[tokenId] = 0; } } ////// lib/openzeppelin-contracts/src/token/ERC721/IERC721Metadata.sol /* pragma solidity ^0.5.0; */ /* import "./IERC721.sol"; */ /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } ////// lib/openzeppelin-contracts/src/token/ERC721/ERC721Metadata.sol /* pragma solidity ^0.5.0; */ /* import "../../GSN/Context.sol"; */ /* import "./ERC721.sol"; */ /* import "./IERC721Metadata.sol"; */ /* import "../../introspection/ERC165.sol"; */ contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } ////// lib/openzeppelin-contracts/src/token/ERC721/ERC721Full.sol /* pragma solidity ^0.5.0; */ /* import "./ERC721.sol"; */ /* import "./ERC721Enumerable.sol"; */ /* import "./ERC721Metadata.sol"; */ /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } } ////// src/Dpass.sol /* pragma solidity ^0.5.11; */ // /** // * How to use dapp and openzeppelin-solidity https://github.com/dapphub/dapp/issues/70 // * ERC-721 standart: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md // * // */ /* import "ds-auth/auth.sol"; */ /* import "openzeppelin-contracts/token/ERC721/ERC721Full.sol"; */ contract DpassEvents { event LogConfigChange(bytes32 what, bytes32 value1, bytes32 value2); event LogCustodianChanged(uint tokenId, address custodian); event LogDiamondAttributesHashChange(uint indexed tokenId, bytes8 hashAlgorithm); event LogDiamondMinted( address owner, uint indexed tokenId, bytes3 issuer, bytes16 report, bytes8 state ); event LogRedeem(uint indexed tokenId); event LogSale(uint indexed tokenId); event LogStateChanged(uint indexed tokenId, bytes32 state); } contract Dpass is DSAuth, ERC721Full, DpassEvents { string private _name = "Diamond Passport"; string private _symbol = "Dpass"; struct Diamond { bytes3 issuer; bytes16 report; bytes8 state; bytes20 cccc; uint24 carat; bytes8 currentHashingAlgorithm; // Current hashing algorithm to check in the proof mapping } Diamond[] diamonds; // List of Dpasses mapping(uint => address) public custodian; // custodian that holds a Dpass token mapping (uint => mapping(bytes32 => bytes32)) public proof; // Prof of attributes integrity [tokenId][hashingAlgorithm] => hash mapping (bytes32 => mapping (bytes32 => bool)) diamondIndex; // List of dpasses by issuer and report number [issuer][number] mapping (uint256 => uint256) public recreated; // List of recreated tokens. old tokenId => new tokenId mapping(bytes32 => mapping(bytes32 => bool)) public canTransit; // List of state transition rules in format from => to = true/false mapping(bytes32 => bool) public ccccs; constructor () public ERC721Full(_name, _symbol) { // Create dummy diamond to start real diamond minting from 1 Diamond memory _diamond = Diamond({ issuer: "Slf", report: "0", state: "invalid", cccc: "BR,IF,D,0001", carat: 1, currentHashingAlgorithm: "" }); diamonds.push(_diamond); _mint(address(this), 0); // Transition rules canTransit["valid"]["invalid"] = true; canTransit["valid"]["removed"] = true; canTransit["valid"]["sale"] = true; canTransit["valid"]["redeemed"] = true; canTransit["sale"]["valid"] = true; canTransit["sale"]["invalid"] = true; canTransit["sale"]["removed"] = true; } modifier onlyOwnerOf(uint _tokenId) { require(ownerOf(_tokenId) == msg.sender, "dpass-access-denied"); _; } modifier onlyApproved(uint _tokenId) { require( ownerOf(_tokenId) == msg.sender || isApprovedForAll(ownerOf(_tokenId), msg.sender) || getApproved(_tokenId) == msg.sender , "dpass-access-denied"); _; } modifier ifExist(uint _tokenId) { require(_exists(_tokenId), "dpass-diamond-does-not-exist"); _; } modifier onlyValid(uint _tokenId) { // TODO: DRY, _exists already check require(_exists(_tokenId), "dpass-diamond-does-not-exist"); Diamond storage _diamond = diamonds[_tokenId]; require(_diamond.state != "invalid", "dpass-invalid-diamond"); _; } /** * @dev Custom accessor to create a unique token * @param _to address of diamond owner * @param _issuer string the issuer agency name * @param _report string the issuer agency unique Nr. * @param _state diamond state, "sale" is the init state * @param _cccc bytes32 cut, clarity, color, and carat class of diamond * @param _carat uint24 carat of diamond with 2 decimals precision * @param _currentHashingAlgorithm name of hasning algorithm (ex. 20190101) * @param _custodian the custodian of minted dpass * @return Return Diamond tokenId of the diamonds list */ function mintDiamondTo( address _to, address _custodian, bytes3 _issuer, bytes16 _report, bytes8 _state, bytes20 _cccc, uint24 _carat, bytes32 _attributesHash, bytes8 _currentHashingAlgorithm ) public auth returns(uint) { require(ccccs[_cccc], "dpass-wrong-cccc"); _addToDiamondIndex(_issuer, _report); Diamond memory _diamond = Diamond({ issuer: _issuer, report: _report, state: _state, cccc: _cccc, carat: _carat, currentHashingAlgorithm: _currentHashingAlgorithm }); uint _tokenId = diamonds.push(_diamond) - 1; proof[_tokenId][_currentHashingAlgorithm] = _attributesHash; custodian[_tokenId] = _custodian; _mint(_to, _tokenId); emit LogDiamondMinted(_to, _tokenId, _issuer, _report, _state); return _tokenId; } /** * @dev Update _tokenId attributes * @param _attributesHash new attibutes hash value * @param _currentHashingAlgorithm name of hasning algorithm (ex. 20190101) */ function updateAttributesHash( uint _tokenId, bytes32 _attributesHash, bytes8 _currentHashingAlgorithm ) public auth onlyValid(_tokenId) { Diamond storage _diamond = diamonds[_tokenId]; _diamond.currentHashingAlgorithm = _currentHashingAlgorithm; proof[_tokenId][_currentHashingAlgorithm] = _attributesHash; emit LogDiamondAttributesHashChange(_tokenId, _currentHashingAlgorithm); } /** * @dev Link old and the same new dpass */ function linkOldToNewToken(uint _tokenId, uint _newTokenId) public auth { require(_exists(_tokenId), "dpass-old-diamond-doesnt-exist"); require(_exists(_newTokenId), "dpass-new-diamond-doesnt-exist"); recreated[_tokenId] = _newTokenId; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg.sender to be the owner, approved, or operator and not invalid token * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public onlyValid(_tokenId) { _checkTransfer(_tokenId); super.transferFrom(_from, _to, _tokenId); } /* * @dev Check if transferPossible */ function _checkTransfer(uint256 _tokenId) internal view { bytes32 state = diamonds[_tokenId].state; require(state != "removed", "dpass-token-removed"); require(state != "invalid", "dpass-token-deleted"); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { _checkTransfer(_tokenId); super.safeTransferFrom(_from, _to, _tokenId); } /* * @dev Returns the current state of diamond */ function getState(uint _tokenId) public view ifExist(_tokenId) returns (bytes32) { return diamonds[_tokenId].state; } /** * @dev Gets the Diamond at a given _tokenId of all the diamonds in this contract * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list * @return Returns all the relevant information about a specific diamond */ function getDiamondInfo(uint _tokenId) public view ifExist(_tokenId) returns ( address[2] memory ownerCustodian, bytes32[6] memory attrs, uint24 carat_ ) { Diamond storage _diamond = diamonds[_tokenId]; bytes32 attributesHash = proof[_tokenId][_diamond.currentHashingAlgorithm]; ownerCustodian[0] = ownerOf(_tokenId); ownerCustodian[1] = custodian[_tokenId]; attrs[0] = _diamond.issuer; attrs[1] = _diamond.report; attrs[2] = _diamond.state; attrs[3] = _diamond.cccc; attrs[4] = attributesHash; attrs[5] = _diamond.currentHashingAlgorithm; carat_ = _diamond.carat; } /** * @dev Gets the Diamond at a given _tokenId of all the diamonds in this contract * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list * @return Returns all the relevant information about a specific diamond */ function getDiamond(uint _tokenId) public view ifExist(_tokenId) returns ( bytes3 issuer, bytes16 report, bytes8 state, bytes20 cccc, uint24 carat, bytes32 attributesHash ) { Diamond storage _diamond = diamonds[_tokenId]; attributesHash = proof[_tokenId][_diamond.currentHashingAlgorithm]; return ( _diamond.issuer, _diamond.report, _diamond.state, _diamond.cccc, _diamond.carat, attributesHash ); } /** * @dev Gets the Diamond issuer and it unique nr at a given _tokenId of all the diamonds in this contract * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list * @return Issuer and unique Nr. a specific diamond */ function getDiamondIssuerAndReport(uint _tokenId) public view ifExist(_tokenId) returns(bytes32, bytes32) { Diamond storage _diamond = diamonds[_tokenId]; return (_diamond.issuer, _diamond.report); } /** * @dev Set cccc values that are allowed to be entered for diamonds * @param _cccc bytes32 cccc value that will be enabled/disabled * @param _allowed bool allow or disallow cccc */ function setCccc(bytes32 _cccc, bool _allowed) public auth { ccccs[_cccc] = _allowed; emit LogConfigChange("cccc", _cccc, _allowed ? bytes32("1") : bytes32("0")); } /** * @dev Set new custodian for dpass */ function setCustodian(uint _tokenId, address _newCustodian) public auth { require(_newCustodian != address(0), "dpass-wrong-address"); custodian[_tokenId] = _newCustodian; emit LogCustodianChanged(_tokenId, _newCustodian); } /** * @dev Get the custodian of Dpass. */ function getCustodian(uint _tokenId) public view returns(address) { return custodian[_tokenId]; } /** * @dev Enable transition _from -> _to state */ function enableTransition(bytes32 _from, bytes32 _to) public auth { canTransit[_from][_to] = true; emit LogConfigChange("canTransit", _from, _to); } /** * @dev Disable transition _from -> _to state */ function disableTransition(bytes32 _from, bytes32 _to) public auth { canTransit[_from][_to] = false; emit LogConfigChange("canNotTransit", _from, _to); } /** * @dev Set Diamond sale state * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list */ function setSaleState(uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) { _setState("sale", _tokenId); emit LogSale(_tokenId); } /** * @dev Set Diamond invalid state * @param _tokenId uint representing the index to be accessed of the diamonds list */ function setInvalidState(uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) { _setState("invalid", _tokenId); _removeDiamondFromIndex(_tokenId); } /** * @dev Make diamond state as redeemed, change owner to contract owner * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list */ function redeem(uint _tokenId) public ifExist(_tokenId) onlyOwnerOf(_tokenId) { _setState("redeemed", _tokenId); _removeDiamondFromIndex(_tokenId); emit LogRedeem(_tokenId); } /** * @dev Change diamond state. * @param _newState new token state * @param _tokenId represent the index of diamond */ function setState(bytes8 _newState, uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) { _setState(_newState, _tokenId); } // Private functions /** * @dev Validate transiton from currentState to newState. Revert on invalid transition * @param _currentState current diamond state * @param _newState new diamond state */ function _validateStateTransitionTo(bytes8 _currentState, bytes8 _newState) internal view { require(_currentState != _newState, "dpass-already-in-that-state"); require(canTransit[_currentState][_newState], "dpass-transition-now-allowed"); } /** * @dev Add Issuer and report with validation to uniqueness. Revert on invalid existance * @param _issuer issuer like GIA * @param _report issuer unique nr. */ function _addToDiamondIndex(bytes32 _issuer, bytes32 _report) internal { require(!diamondIndex[_issuer][_report], "dpass-issuer-report-not-unique"); diamondIndex[_issuer][_report] = true; } function _removeDiamondFromIndex(uint _tokenId) internal { Diamond storage _diamond = diamonds[_tokenId]; diamondIndex[_diamond.issuer][_diamond.report] = false; } /** * @dev Change diamond state with logging. Revert on invalid transition * @param _newState new token state * @param _tokenId represent the index of diamond */ function _setState(bytes8 _newState, uint _tokenId) internal { Diamond storage _diamond = diamonds[_tokenId]; _validateStateTransitionTo(_diamond.state, _newState); _diamond.state = _newState; emit LogStateChanged(_tokenId, _newState); } }
Make diamond state as redeemed, change owner to contract owner Reverts if the _tokenId is greater or equal to the total number of diamonds _tokenId uint representing the index to be accessed of the diamonds list/
function redeem(uint _tokenId) public ifExist(_tokenId) onlyOwnerOf(_tokenId) { _setState("redeemed", _tokenId); _removeDiamondFromIndex(_tokenId); emit LogRedeem(_tokenId); }
1,808,907
./full_match/1/0x76F56Df6b48D23A2Afe3Ae8B0E8a0C6309011A23/sources/contracts/tokens/USDRMigrationV2.sol
Function to check the integrity of the WUSDR token On the main chain, ensure that the balance of the Multichain WUSDR vault has not changed On other chains, ensure that the total supply of the Multichain WUSDR tokens has not changed
function _checkSnapshot() internal view { if (_isMain) { require( _snapshot == IERC20(oldWUSDR).balanceOf(MULTICHAIN_VAULT), "suspicious activity" ); require( _snapshot == IERC20(oldWUSDR).totalSupply(), "suspicious activity" ); } }
8,474,654
// SPDX-License-Identifier: MIT // File: contracts/true-currencies-new/ProxyStorage.sol pragma solidity 0.6.10; /** * Defines the storage layout of the token implementation contract. Any * newly declared state variables in future upgrades should be appended * to the bottom. Never remove state variables from this list, however variables * can be renamed. Please add _Deprecated to deprecated variables. */ contract ProxyStorage { address public owner; address public pendingOwner; bool initialized; address balances_Deprecated; address allowances_Deprecated; uint256 _totalSupply; bool private paused_Deprecated = false; address private globalPause_Deprecated; uint256 public burnMin = 0; uint256 public burnMax = 0; address registry_Deprecated; string name_Deprecated; string symbol_Deprecated; uint256[] gasRefundPool_Deprecated; uint256 private redemptionAddressCount_Deprecated; uint256 minimumGasPriceForFutureRefunds_Deprecated; mapping(address => uint256) _balances; mapping(address => mapping(address => uint256)) _allowances; mapping(bytes32 => mapping(address => uint256)) attributes_Deprecated; // reward token storage mapping(address => address) finOps_Deprecated; mapping(address => mapping(address => uint256)) finOpBalances_Deprecated; mapping(address => uint256) finOpSupply_Deprecated; // true reward allocation // proportion: 1000 = 100% struct RewardAllocation { uint256 proportion; address finOp; } mapping(address => RewardAllocation[]) _rewardDistribution_Deprecated; uint256 maxRewardProportion_Deprecated = 1000; mapping(address => bool) isBlacklisted; mapping(address => bool) public canBurn; /* Additionally, we have several keccak-based storage locations. * If you add more keccak-based storage mappings, such as mappings, you must document them here. * If the length of the keccak input is the same as an existing mapping, it is possible there could be a preimage collision. * A preimage collision can be used to attack the contract by treating one storage location as another, * which would always be a critical issue. * Carefully examine future keccak-based storage to ensure there can be no preimage collisions. ******************************************************************************************************* ** length input usage ******************************************************************************************************* ** 19 "trueXXX.proxy.owner" Proxy Owner ** 27 "trueXXX.pending.proxy.owner" Pending Proxy Owner ** 28 "trueXXX.proxy.implementation" Proxy Implementation ** 32 uint256(11) gasRefundPool_Deprecated ** 64 uint256(address),uint256(14) balanceOf ** 64 uint256(address),keccak256(uint256(address),uint256(15)) allowance ** 64 uint256(address),keccak256(bytes32,uint256(16)) attributes **/ } // File: contracts/true-currencies-new/ClaimableOwnable.sol pragma solidity 0.6.10; /** * @title ClamableOwnable * @dev The ClamableOwnable contract is a copy of Claimable Contract by Zeppelin. * and provides basic authorization control functions. Inherits storage layout of * ProxyStorage. */ contract ClaimableOwnable is ProxyStorage { /** * @dev emitted when ownership is transferred * @param previousOwner previous owner of this contract * @param newOwner new owner of this contract */ event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev sets the original `owner` of the contract to the sender * at construction. Must then be reinitialized */ constructor() public { owner = msg.sender; emit OwnershipTransferred(address(0), owner); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "only Owner"); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner, "only pending owner"); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/true-currencies-new/ERC20.sol /** * @notice This is a copy of openzeppelin ERC20 contract with removed state variables. * Removing state variables has been necessary due to proxy pattern usage. * Changes to Openzeppelin ERC20 https://github.com/OpenZeppelin/openzeppelin-contracts/blob/de99bccbfd4ecd19d7369d01b070aa72c64423c9/contracts/token/ERC20/ERC20.sol: * - Remove state variables _name, _symbol, _decimals * - Use state variables _balances, _allowances, _totalSupply from ProxyStorage * - Remove constructor * - Solidity version changed from ^0.6.0 to 0.6.10 * - Contract made abstract * * See also: ClaimableOwnable.sol and ProxyStorage.sol */ pragma solidity 0.6.10; /** * @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}. */ abstract contract ERC20 is ClaimableOwnable, Context, IERC20 { using SafeMath for uint256; using Address for address; /** * @dev Returns the name of the token. */ function name() public virtual pure returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public virtual pure returns (string memory); /** * @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 virtual pure returns (uint8) { return 18; } /** * @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 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]. */ // solhint-disable-next-line no-empty-blocks function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/true-currencies-new/ReclaimerToken.sol pragma solidity 0.6.10; /** * @title ReclaimerToken * @dev ERC20 token which allows owner to reclaim ERC20 tokens * or ether sent to this contract */ abstract contract ReclaimerToken is ERC20 { /** * @dev send all eth balance in the contract to another address * @param _to address to send eth balance to */ function reclaimEther(address payable _to) external onlyOwner { _to.transfer(address(this).balance); } /** * @dev send all token balance of an arbitrary erc20 token * in the contract to another address * @param token token to reclaim * @param _to address to send eth balance to */ function reclaimToken(IERC20 token, address _to) external onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(_to, balance); } } // File: contracts/true-currencies-new/BurnableTokenWithBounds.sol pragma solidity 0.6.10; /** * @title BurnableTokenWithBounds * @dev Burning functions as redeeming money from the system. * The platform will keep track of who burns coins, * and will send them back the equivalent amount of money (rounded down to the nearest cent). */ abstract contract BurnableTokenWithBounds is ReclaimerToken { /** * @dev Emitted when `value` tokens are burnt from one account (`burner`) * @param burner address which burned tokens * @param value amount of tokens burned */ event Burn(address indexed burner, uint256 value); /** * @dev Emitted when new burn bounds were set * @param newMin new minimum burn amount * @param newMax new maximum burn amount * @notice `newMin` should never be greater than `newMax` */ event SetBurnBounds(uint256 newMin, uint256 newMax); /** * @dev Destroys `amount` tokens from `msg.sender`, reducing the * total supply. * @param amount amount of tokens to burn * * Emits a {Transfer} event with `to` set to the zero address. * Emits a {Burn} event with `burner` set to `msg.sender` * * Requirements * * - `msg.sender` must have at least `amount` tokens. * */ function burn(uint256 amount) external { _burn(msg.sender, amount); } /** * @dev Change the minimum and maximum amount that can be burned at once. * Burning may be disabled by setting both to 0 (this will not be done * under normal operation, but we can't add checks to disallow it without * losing a lot of flexibility since burning could also be as good as disabled * by setting the minimum extremely high, and we don't want to lock * in any particular cap for the minimum) * @param _min minimum amount that can be burned at once * @param _max maximum amount that can be burned at once */ function setBurnBounds(uint256 _min, uint256 _max) external onlyOwner { require(_min <= _max, "BurnableTokenWithBounds: min > max"); burnMin = _min; burnMax = _max; emit SetBurnBounds(_min, _max); } /** * @dev Checks if amount is within allowed burn bounds and * destroys `amount` tokens from `account`, reducing the * total supply. * @param account account to burn tokens for * @param amount amount of tokens to burn * * Emits a {Burn} event */ function _burn(address account, uint256 amount) internal virtual override { require(amount >= burnMin, "BurnableTokenWithBounds: below min burn bound"); require(amount <= burnMax, "BurnableTokenWithBounds: exceeds max burn bound"); super._burn(account, amount); emit Burn(account, amount); } } // File: contracts/true-currencies-new/GasRefund.sol pragma solidity 0.6.10; /** * @title Gas Reclaim Legacy * * Note: this contract does not affect any of the token logic. It merely * exists so the TokenController (owner) can reclaim the sponsored gas * * Previously TrueCurrency has a feature called "gas boost" which allowed * us to sponsor gas by setting non-empty storage slots to 1. * We are depricating this feature, but there is a bunch of gas saved * from years of sponsoring gas. This contract is meant to allow the owner * to take advantage of this leftover gas. Once all the slots are used, * this contract can be removed from TrueCurrency. * * Utilitzes the gas refund mechanism in EVM. Each time an non-empty * storage slot is set to 0, evm will refund 15,000 to the sender. * Also utilized the refund for selfdestruct, see gasRefund39 * */ abstract contract GasRefund { /** * @dev Refund 15,000 gas per slot. * @param amount number of slots to free */ function gasRefund15(uint256 amount) internal { // refund gas assembly { // get number of free slots let offset := sload(0xfffff) // make sure there are enough slots if lt(offset, amount) { amount := offset } if eq(amount, 0) { stop() } let location := add(offset, 0xfffff) let end := sub(location, amount) // loop until amount is reached // i = storage location for { } gt(location, end) { location := sub(location, 1) } { // set storage location to zero // this refunds 15,000 gas sstore(location, 0) } // store new number of free slots sstore(0xfffff, sub(offset, amount)) } } /** * @dev use smart contract self-destruct to refund gas * will refund 39,000 * amount gas */ function gasRefund39(uint256 amount) internal { assembly { // get amount of gas slots let offset := sload(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) // make sure there are enough slots if lt(offset, amount) { amount := offset } if eq(amount, 0) { stop() } // first sheep pointer let location := sub(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, offset) // last sheep pointer let end := add(location, amount) for { } lt(location, end) { location := add(location, 1) } { // load sheep address let sheep := sload(location) // call selfdestruct on sheep pop(call(gas(), sheep, 0, 0, 0, 0, 0)) // clear sheep address sstore(location, 0) } sstore(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, sub(offset, amount)) } } /** * @dev Return the remaining sponsored gas slots */ function remainingGasRefundPool() public view returns (uint256 length) { assembly { length := sload(0xfffff) } } /** * @dev Return the remaining sheep slots */ function remainingSheepRefundPool() public view returns (uint256 length) { assembly { length := sload(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) } } } // File: contracts/true-currencies-new/TrueCurrency.sol pragma solidity 0.6.10; /** * @title TrueCurrency * @dev TrueCurrency is an ERC20 with blacklist & redemption addresses * * TrueCurrency is a compliant stablecoin with blacklist and redemption * addresses. Only the owner can blacklist accounts. Redemption addresses * are assigned automatically to the first 0x100000 addresses. Sending * tokens to the redemption address will trigger a burn operation. Only * the owner can mint or blacklist accounts. * * This contract is owned by the TokenController, which manages token * minting & admin functionality. See TokenController.sol * * See also: BurnableTokenWithBounds.sol * * ~~~~ Features ~~~~ * * Redemption Addresses * - The first 0x100000 addresses are redemption addresses * - Tokens sent to redemption addresses are burned * - Redemptions are tracked off-chain * - Cannot mint tokens to redemption addresses * * Blacklist * - Owner can blacklist accounts in accordance with local regulatory bodies * - Only a court order will merit a blacklist; blacklisting is extremely rare * * Burn Bounds & CanBurn * - Owner can set min & max burn amounts * - Only accounts flagged in canBurn are allowed to burn tokens * - canBurn prevents tokens from being sent to the incorrect address * * Reclaimer Token * - ERC20 Tokens and Ether sent to this contract can be reclaimed by the owner */ abstract contract TrueCurrency is BurnableTokenWithBounds, GasRefund { uint256 constant CENT = 10**16; uint256 constant REDEMPTION_ADDRESS_COUNT = 0x100000; /** * @dev Emitted when account blacklist status changes */ event Blacklisted(address indexed account, bool isBlacklisted); /** * @dev Emitted when `value` tokens are minted for `to` * @param to address to mint tokens for * @param value amount of tokens to be minted */ event Mint(address indexed to, uint256 value); /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * @param account address to mint tokens for * @param amount amount of tokens to be minted * * Emits a {Mint} event * * Requirements * * - `account` cannot be the zero address. * - `account` cannot be blacklisted. * - `account` cannot be a redemption address. */ function mint(address account, uint256 amount) external onlyOwner { require(!isBlacklisted[account], "TrueCurrency: account is blacklisted"); require(!isRedemptionAddress(account), "TrueCurrency: account is a redemption address"); _mint(account, amount); emit Mint(account, amount); } /** * @dev Set blacklisted status for the account. * @param account address to set blacklist flag for * @param _isBlacklisted blacklist flag value * * Requirements: * * - `msg.sender` should be owner. */ function setBlacklisted(address account, bool _isBlacklisted) external onlyOwner { require(uint256(account) >= REDEMPTION_ADDRESS_COUNT, "TrueCurrency: blacklisting of redemption address is not allowed"); isBlacklisted[account] = _isBlacklisted; emit Blacklisted(account, _isBlacklisted); } /** * @dev Set canBurn status for the account. * @param account address to set canBurn flag for * @param _canBurn canBurn flag value * * Requirements: * * - `msg.sender` should be owner. */ function setCanBurn(address account, bool _canBurn) external onlyOwner { canBurn[account] = _canBurn; } /** * @dev Check if neither account is blacklisted before performing transfer * If transfer recipient is a redemption address, burns tokens * @notice Transfer to redemption address will burn tokens with a 1 cent precision * @param sender address of sender * @param recipient address of recipient * @param amount amount of tokens to transfer */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual override { require(!isBlacklisted[sender], "TrueCurrency: sender is blacklisted"); require(!isBlacklisted[recipient], "TrueCurrency: recipient is blacklisted"); if (isRedemptionAddress(recipient)) { super._transfer(sender, recipient, amount.sub(amount.mod(CENT))); _burn(recipient, amount.sub(amount.mod(CENT))); } else { super._transfer(sender, recipient, amount); } } /** * @dev Requere neither accounts to be blacklisted before approval * @param owner address of owner giving approval * @param spender address of spender to approve for * @param amount amount of tokens to approve */ function _approve( address owner, address spender, uint256 amount ) internal override { require(!isBlacklisted[owner], "TrueCurrency: tokens owner is blacklisted"); require(!isBlacklisted[spender] || amount == 0, "TrueCurrency: tokens spender is blacklisted"); super._approve(owner, spender, amount); } /** * @dev Check if tokens can be burned at address before burning * @param account account to burn tokens from * @param amount amount of tokens to burn */ function _burn(address account, uint256 amount) internal override { require(canBurn[account], "TrueCurrency: cannot burn from this address"); super._burn(account, amount); } /** * @dev First 0x100000-1 addresses (0x0000000000000000000000000000000000000001 to 0x00000000000000000000000000000000000fffff) * are the redemption addresses. * @param account address to check is a redemption address * * All transfers to redemption address will trigger token burn. * * @notice For transfer to succeed, canBurn must be true for redemption address * * @return is `account` a redemption address */ function isRedemptionAddress(address account) internal pure returns (bool) { return uint256(account) < REDEMPTION_ADDRESS_COUNT && uint256(account) != 0; } /** * @dev reclaim gas from legacy gas refund #1 * will refund 15,000 * amount gas to sender (minus exection cost) * If gas pool is empty, refund 39,000 * amount gas by calling selfdestruct */ function refundGas(uint256 amount) external onlyOwner { if (remainingGasRefundPool() > 0) { gasRefund15(amount); } else { gasRefund39(amount.div(3)); } } } // File: contracts/true-currencies-new/TrueGBP.sol pragma solidity 0.6.10; /** * @title TrueGBP * @dev This is the top-level ERC20 contract, but most of the interesting functionality is * inherited - see the documentation on the corresponding contracts. */ contract TrueGBP is TrueCurrency { uint8 constant DECIMALS = 18; uint8 constant ROUNDING = 2; function decimals() public override pure returns (uint8) { return DECIMALS; } function rounding() public pure returns (uint8) { return ROUNDING; } function name() public override pure returns (string memory) { return "TrueGBP"; } function symbol() public override pure returns (string memory) { return "TGBP"; } }
Emitted when account blacklist status changes/ Emitted when `value` tokens are minted for `to` to address to mint tokens for value amount of tokens to be minted/ Creates `amount` tokens and assigns them to `account`, increasing the total supply. account address to mint tokens for amount amount of tokens to be minted Emits a {Mint} event Requirements - `account` cannot be the zero address. - `account` cannot be blacklisted. - `account` cannot be a redemption address./
function mint(address account, uint256 amount) external onlyOwner { require(!isBlacklisted[account], "TrueCurrency: account is blacklisted"); require(!isRedemptionAddress(account), "TrueCurrency: account is a redemption address"); _mint(account, amount); emit Mint(account, amount); }
59,305
// File: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/introspection/IERC165.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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 // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transfered from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @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 // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @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 // SPDX-License-Identifier: MIT pragma solidity ^0.6.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 // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) 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; } } // File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly {codehash := extcodehash(account)} return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success,) = recipient.call{value : amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value : weiValue}(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) {// Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping(bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) {// Equivalent to !contains(map, key) map._entries.push(MapEntry({_key : key, _value : value})); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) {// Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // File: @openzeppelin/contracts/utils/Strings.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping(address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId,) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mecanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual {} } // File: @openzeppelin/contracts/access/AccessControl.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @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()); } } } // File: contracts/common/AccessControlMixin.sol pragma solidity 0.6.6; contract AccessControlMixin is AccessControl { string private _revertMsg; function _setupContractId(string memory contractId) internal { _revertMsg = string(abi.encodePacked(contractId, ": INSUFFICIENT_PERMISSIONS")); } modifier only(bytes32 role) { require( hasRole(role, _msgSender()), _revertMsg ); _; } } // File: contracts/common/Initializable.sol pragma solidity 0.6.6; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File: contracts/common/EIP712Base.sol pragma solidity 0.6.6; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contractsa that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File: contracts/common/NativeMetaTransaction.sol pragma solidity 0.6.6; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce : nonces[userAddress], from : userAddress, functionSignature : functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, msg.sender, functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File: contracts/root/RootToken/IMintableERC721.sol pragma solidity 0.6.6; interface IMintableERC721 is IERC721 { /** * @notice called by predicate contract to mint tokens while withdrawing * @dev Should be callable only by MintableERC721Predicate * Make sure minting is done only by this function * @param user user address for whom token is being minted * @param tokenId tokenId being minted */ function mint(address user, uint256 tokenId) external; /** * @notice called by predicate contract to mint tokens while withdrawing with metadata from L2 * @dev Should be callable only by MintableERC721Predicate * Make sure minting is only done either by this function/ 👆 * @param user user address for whom token is being minted * @param tokenId tokenId being minted * @param metaData Associated token metadata, to be decoded & set using `setTokenMetadata` * * Note : If you're interested in taking token metadata from L2 to L1 during exit, you must * implement this method */ function mint(address user, uint256 tokenId, bytes calldata metaData) external; /** * @notice check if token already exists, return true if it does exist * @dev this check will be used by the predicate to determine if the token needs to be minted or transfered * @param tokenId tokenId being checked */ function exists(uint256 tokenId) external view returns (bool); } // File: contracts/common/ContextMixin.sol pragma solidity 0.6.6; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = msg.sender; } return sender; } } // File: contracts/root/RootToken/DummyMintableERC721.sol pragma experimental ABIEncoderV2; pragma solidity 0.6.6; contract ArtvatarsMintableERC721 is ERC721, AccessControlMixin, NativeMetaTransaction, IMintableERC721, ContextMixin { bytes32 public constant PREDICATE_ROLE = keccak256("PREDICATE_ROLE"); mapping(uint256 => Artvatar) public tokenToArtvatar; struct Attribute { string title; string name; } struct Artvatar { uint256 id; string series; string title; string description; string image; Attribute[] attributes; bool metadataChanged; } constructor(string memory name_, string memory symbol_, address predicateProxy_) public ERC721(name_, symbol_) { _setupContractId("ArtvatarsMintableERC721"); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(PREDICATE_ROLE, _msgSender()); _setupRole(PREDICATE_ROLE, predicateProxy_); _initializeEIP712(name_); } function _msgSender() internal override view returns (address payable sender) { return ContextMixin.msgSender(); } /** * @dev See {IMintableERC721-mint}. */ function mint(address user, uint256 tokenId) external override only(PREDICATE_ROLE) { _mint(user, tokenId); } /** * If you're attempting to bring metadata associated with token * from L2 to L1, you must implement this method, to be invoked * when minting token back on L1, during exit */ function setTokenMetadata(uint256 tokenId, bytes memory data) internal virtual { // This function should decode metadata obtained from L2 // and attempt to set it for this `tokenId` // // Following is just a default implementation, feel // free to define your own encoding/ decoding scheme // for L2 -> L1 token metadata transfer (Artvatar memory _artvatar, string memory uri) = abi.decode(data, (Artvatar, string)); Artvatar storage artvatar = tokenToArtvatar[tokenId]; Attribute[] memory _attributes = _artvatar.attributes; artvatar.id = _artvatar.id; artvatar.series = _artvatar.series; artvatar.title = _artvatar.title; artvatar.description = _artvatar.description; artvatar.image = _artvatar.image; for (uint256 i = 0; i < _attributes.length; i++) { Attribute memory attribute = _attributes[i]; artvatar.attributes.push(attribute); } artvatar.metadataChanged = true; _setTokenURI(tokenId, uri); } function getArtvatarByTokenId(uint256 _tokenId) public view returns (Artvatar memory artvatar) { return tokenToArtvatar[_tokenId]; } /** * @dev See {IMintableERC721-mint}. * * If you're attempting to bring metadata associated with token * from L2 to L1, you must implement this method */ function mint(address user, uint256 tokenId, bytes calldata metaData) external override only(PREDICATE_ROLE) { _mint(user, tokenId); setTokenMetadata(tokenId, metaData); } /** * @dev See {IMintableERC721-exists}. */ function exists(uint256 tokenId) external view override returns (bool) { return _exists(tokenId); } }
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)); }
1,139,809
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "./ZestyVault_V2.sol"; import "../interfaces/IZestyMarket_ERC20_V1_1.sol"; import "../interfaces/IERC20.sol"; import "../utils/ReentrancyGuard.sol"; import "../utils/ERC1155.sol"; contract ZestyCommissions_ERC20_V1_1 is ZestyVault_V2, ERC1155, ReentrancyGuard { IZestyMarket_ERC20_V1_1 public immutable _zestyMarket; IERC20 public immutable _txToken; constructor( address txToken_, address zestyNFT_, address zestyMarket_ ) ZestyVault_V2(zestyNFT_) ERC1155("") { _zestyMarket = IZestyMarket_ERC20_V1_1(zestyMarket_); _txToken = IERC20(txToken_); } struct Share { uint256 blockNumber; uint256 share; } // deposit id to value mapping (uint256 => uint256) public _value; // deposit id to totalShares mapping (uint256 => uint256) public _totalShares; // deposit id to address to shares mapping (uint256 => mapping(address => Share[])) public _shares; // deposit id to block num where contractwithdrawn to sum mapping (uint256 => mapping(uint256 => uint256)) public _sums; function uri(uint256 depositId) external view override returns (string memory) { // get tokenId from deposit return _zestyNFT.tokenURI(getTokenId(depositId)); } function sellerNFTDeposit( uint256 _tokenId, uint256 shares, uint256 buybackPerShare, uint8 _autoApprove ) public nonReentrant returns (uint256 depositId) { uint256 depositId = _depositZestyNFT(_tokenId); _zestyNFT.approve(address(_zestyMarket), _tokenId); _zestyMarket.sellerNFTDeposit(_tokenId, _autoApprove); _mint(msg.sender, depositId, shares, ""); return depositId; } function sellerNFTWithdraw(uint256 _depositId) public nonReentrant { uint256 tokenId = getTokenId(_depositId); _zestyMarket.sellerNFTWithdraw(tokenId); _withdrawZestyNFT(tokenId); } function sellerNFTUpdate( uint256 _depositId, uint8 _autoApprove ) public onlyDepositorOrOperator(_depositId) { _zestyMarket.sellerNFTUpdate(_depositId, _autoApprove); } function sellerAuctionCreateBatch( uint256 _depositId, uint256[] memory _auctionTimeStart, uint256[] memory _auctionTimeEnd, uint256[] memory _contractTimeStart, uint256[] memory _contractTimeEnd, uint256[] memory _priceStart ) public onlyDepositorOrOperator(_depositId) { uint256 _tokenId = getTokenId(_depositId); _zestyMarket.sellerAuctionCreateBatch( _tokenId, _auctionTimeStart, _auctionTimeEnd, _contractTimeStart, _contractTimeEnd, _priceStart ); } function sellerAuctionApproveBatch( uint256 _depositId, uint256[] memory _sellerAuctionId ) external nonReentrant onlyDepositorOrOperator(_depositId) { _zestyMarket.sellerAuctionApproveBatch(_sellerAuctionId); } function sellerAuctionRejectBatch( uint256 _depositId, uint256[] memory _sellerAuctionId ) external nonReentrant onlyDepositorOrOperator(_depositId) { _zestyMarket.sellerAuctionRejectBatch(_sellerAuctionId); } function contractWithdrawBatch( uint256 _depositId, uint256[] memory _contractId ) external nonReentrant onlyDepositorOrOperator(_depositId) { _zestyMarket.contractWithdrawBatch(_contractId); // TODO get block number and append erc20 to balances. } function withdraw( uint256 _depositId, uint256 startBlock, uint256 endBlock ) public { // TODO } }
get tokenId from deposit
function uri(uint256 depositId) external view override returns (string memory) { return _zestyNFT.tokenURI(getTokenId(depositId)); }
6,396,299
pragma solidity ^0.4.23; // produced by the Solididy File Flattener (c) David Appleton 2018 // contact : [email protected] // released under Apache 2.0 licence contract Token { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public constant returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } library ECTools { // @dev Recovers the address which has signed a message // @thanks https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d function recoverSigner(bytes32 _hashedMsg, string _sig) public pure returns (address) { require(_hashedMsg != 0x00); // need this for test RPC bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, _hashedMsg)); if (bytes(_sig).length != 132) { return 0x0; } bytes32 r; bytes32 s; uint8 v; bytes memory sig = hexstrToBytes(substring(_sig, 2, 132)); assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } if (v < 27) { v += 27; } if (v < 27 || v > 28) { return 0x0; } return ecrecover(prefixedHash, v, r, s); } // @dev Verifies if the message is signed by an address function isSignedBy(bytes32 _hashedMsg, string _sig, address _addr) public pure returns (bool) { require(_addr != 0x0); return _addr == recoverSigner(_hashedMsg, _sig); } // @dev Converts an hexstring to bytes function hexstrToBytes(string _hexstr) public pure returns (bytes) { uint len = bytes(_hexstr).length; require(len % 2 == 0); bytes memory bstr = bytes(new string(len / 2)); uint k = 0; string memory s; string memory r; for (uint i = 0; i < len; i += 2) { s = substring(_hexstr, i, i + 1); r = substring(_hexstr, i + 1, i + 2); uint p = parseInt16Char(s) * 16 + parseInt16Char(r); bstr[k++] = uintToBytes32(p)[31]; } return bstr; } // @dev Parses a hexchar, like 'a', and returns its hex value, in this case 10 function parseInt16Char(string _char) public pure returns (uint) { bytes memory bresult = bytes(_char); // bool decimals = false; if ((bresult[0] >= 48) && (bresult[0] <= 57)) { return uint(bresult[0]) - 48; } else if ((bresult[0] >= 65) && (bresult[0] <= 70)) { return uint(bresult[0]) - 55; } else if ((bresult[0] >= 97) && (bresult[0] <= 102)) { return uint(bresult[0]) - 87; } else { revert(); } } // @dev Converts a uint to a bytes32 // @thanks https://ethereum.stackexchange.com/questions/4170/how-to-convert-a-uint-to-bytes-in-solidity function uintToBytes32(uint _uint) public pure returns (bytes b) { b = new bytes(32); assembly {mstore(add(b, 32), _uint)} } // @dev Hashes the signed message // @ref https://github.com/ethereum/go-ethereum/issues/3731#issuecomment-293866868 function toEthereumSignedMessage(string _msg) public pure returns (bytes32) { uint len = bytes(_msg).length; require(len > 0); bytes memory prefix = "\x19Ethereum Signed Message:\n"; return keccak256(abi.encodePacked(prefix, uintToString(len), _msg)); } // @dev Converts a uint in a string function uintToString(uint _uint) public pure returns (string str) { uint len = 0; uint m = _uint + 0; while (m != 0) { len++; m /= 10; } bytes memory b = new bytes(len); uint i = len - 1; while (_uint != 0) { uint remainder = _uint % 10; _uint = _uint / 10; b[i--] = byte(48 + remainder); } str = string(b); } // @dev extract a substring // @thanks https://ethereum.stackexchange.com/questions/31457/substring-in-solidity function substring(string _str, uint _startIndex, uint _endIndex) public pure returns (string) { bytes memory strBytes = bytes(_str); require(_startIndex <= _endIndex); require(_startIndex >= 0); require(_endIndex <= strBytes.length); bytes memory result = new bytes(_endIndex - _startIndex); for (uint i = _startIndex; i < _endIndex; i++) { result[i - _startIndex] = strBytes[i]; } return string(result); } } contract StandardToken is Token { function transfer(address _to, uint256 _value) public returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract HumanStandardToken is StandardToken { /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H0.1'; //human 0.1 standard. Just an arbitrary versioning scheme. constructor( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)); return true; } } contract LedgerChannel { string public constant NAME = "Ledger Channel"; string public constant VERSION = "0.0.1"; uint256 public numChannels = 0; event DidLCOpen ( bytes32 indexed channelId, address indexed partyA, address indexed partyI, uint256 ethBalanceA, address token, uint256 tokenBalanceA, uint256 LCopenTimeout ); event DidLCJoin ( bytes32 indexed channelId, uint256 ethBalanceI, uint256 tokenBalanceI ); event DidLCDeposit ( bytes32 indexed channelId, address indexed recipient, uint256 deposit, bool isToken ); event DidLCUpdateState ( bytes32 indexed channelId, uint256 sequence, uint256 numOpenVc, uint256 ethBalanceA, uint256 tokenBalanceA, uint256 ethBalanceI, uint256 tokenBalanceI, bytes32 vcRoot, uint256 updateLCtimeout ); event DidLCClose ( bytes32 indexed channelId, uint256 sequence, uint256 ethBalanceA, uint256 tokenBalanceA, uint256 ethBalanceI, uint256 tokenBalanceI ); event DidVCInit ( bytes32 indexed lcId, bytes32 indexed vcId, bytes proof, uint256 sequence, address partyA, address partyB, uint256 balanceA, uint256 balanceB ); event DidVCSettle ( bytes32 indexed lcId, bytes32 indexed vcId, uint256 updateSeq, uint256 updateBalA, uint256 updateBalB, address challenger, uint256 updateVCtimeout ); event DidVCClose( bytes32 indexed lcId, bytes32 indexed vcId, uint256 balanceA, uint256 balanceB ); struct Channel { //TODO: figure out if it's better just to split arrays by balances/deposits instead of eth/erc20 address[2] partyAddresses; // 0: partyA 1: partyI uint256[4] ethBalances; // 0: balanceA 1:balanceI 2:depositedA 3:depositedI uint256[4] erc20Balances; // 0: balanceA 1:balanceI 2:depositedA 3:depositedI uint256[2] initialDeposit; // 0: eth 1: tokens uint256 sequence; uint256 confirmTime; bytes32 VCrootHash; uint256 LCopenTimeout; uint256 updateLCtimeout; // when update LC times out bool isOpen; // true when both parties have joined bool isUpdateLCSettling; uint256 numOpenVC; HumanStandardToken token; } // virtual-channel state struct VirtualChannel { bool isClose; bool isInSettlementState; uint256 sequence; address challenger; // Initiator of challenge uint256 updateVCtimeout; // when update VC times out // channel state address partyA; // VC participant A address partyB; // VC participant B address partyI; // LC hub uint256[2] ethBalances; uint256[2] erc20Balances; uint256[2] bond; HumanStandardToken token; } mapping(bytes32 => VirtualChannel) public virtualChannels; mapping(bytes32 => Channel) public Channels; function createChannel( bytes32 _lcID, address _partyI, uint256 _confirmTime, address _token, uint256[2] _balances // [eth, token] ) public payable { require(Channels[_lcID].partyAddresses[0] == address(0), "Channel has already been created."); require(_partyI != 0x0, "No partyI address provided to LC creation"); require(_balances[0] >= 0 && _balances[1] >= 0, "Balances cannot be negative"); // Set initial ledger channel state // Alice must execute this and we assume the initial state // to be signed from this requirement // Alternative is to check a sig as in joinChannel Channels[_lcID].partyAddresses[0] = msg.sender; Channels[_lcID].partyAddresses[1] = _partyI; if(_balances[0] != 0) { require(msg.value == _balances[0], "Eth balance does not match sent value"); Channels[_lcID].ethBalances[0] = msg.value; } if(_balances[1] != 0) { Channels[_lcID].token = HumanStandardToken(_token); require(Channels[_lcID].token.transferFrom(msg.sender, this, _balances[1]),"CreateChannel: token transfer failure"); Channels[_lcID].erc20Balances[0] = _balances[1]; } Channels[_lcID].sequence = 0; Channels[_lcID].confirmTime = _confirmTime; // is close flag, lc state sequence, number open vc, vc root hash, partyA... //Channels[_lcID].stateHash = keccak256(uint256(0), uint256(0), uint256(0), bytes32(0x0), bytes32(msg.sender), bytes32(_partyI), balanceA, balanceI); Channels[_lcID].LCopenTimeout = now + _confirmTime; Channels[_lcID].initialDeposit = _balances; emit DidLCOpen(_lcID, msg.sender, _partyI, _balances[0], _token, _balances[1], Channels[_lcID].LCopenTimeout); } function LCOpenTimeout(bytes32 _lcID) public { require(msg.sender == Channels[_lcID].partyAddresses[0] && Channels[_lcID].isOpen == false); require(now > Channels[_lcID].LCopenTimeout); if(Channels[_lcID].initialDeposit[0] != 0) { Channels[_lcID].partyAddresses[0].transfer(Channels[_lcID].ethBalances[0]); } if(Channels[_lcID].initialDeposit[1] != 0) { require(Channels[_lcID].token.transfer(Channels[_lcID].partyAddresses[0], Channels[_lcID].erc20Balances[0]),"CreateChannel: token transfer failure"); } emit DidLCClose(_lcID, 0, Channels[_lcID].ethBalances[0], Channels[_lcID].erc20Balances[0], 0, 0); // only safe to delete since no action was taken on this channel delete Channels[_lcID]; } function joinChannel(bytes32 _lcID, uint256[2] _balances) public payable { // require the channel is not open yet require(Channels[_lcID].isOpen == false); require(msg.sender == Channels[_lcID].partyAddresses[1]); if(_balances[0] != 0) { require(msg.value == _balances[0], "state balance does not match sent value"); Channels[_lcID].ethBalances[1] = msg.value; } if(_balances[1] != 0) { require(Channels[_lcID].token.transferFrom(msg.sender, this, _balances[1]),"joinChannel: token transfer failure"); Channels[_lcID].erc20Balances[1] = _balances[1]; } Channels[_lcID].initialDeposit[0]+=_balances[0]; Channels[_lcID].initialDeposit[1]+=_balances[1]; // no longer allow joining functions to be called Channels[_lcID].isOpen = true; numChannels++; emit DidLCJoin(_lcID, _balances[0], _balances[1]); } // additive updates of monetary state // TODO check this for attack vectors function deposit(bytes32 _lcID, address recipient, uint256 _balance, bool isToken) public payable { require(Channels[_lcID].isOpen == true, "Tried adding funds to a closed channel"); require(recipient == Channels[_lcID].partyAddresses[0] || recipient == Channels[_lcID].partyAddresses[1]); //if(Channels[_lcID].token) if (Channels[_lcID].partyAddresses[0] == recipient) { if(isToken) { require(Channels[_lcID].token.transferFrom(msg.sender, this, _balance),"deposit: token transfer failure"); Channels[_lcID].erc20Balances[2] += _balance; } else { require(msg.value == _balance, "state balance does not match sent value"); Channels[_lcID].ethBalances[2] += msg.value; } } if (Channels[_lcID].partyAddresses[1] == recipient) { if(isToken) { require(Channels[_lcID].token.transferFrom(msg.sender, this, _balance),"deposit: token transfer failure"); Channels[_lcID].erc20Balances[3] += _balance; } else { require(msg.value == _balance, "state balance does not match sent value"); Channels[_lcID].ethBalances[3] += msg.value; } } emit DidLCDeposit(_lcID, recipient, _balance, isToken); } // TODO: Check there are no open virtual channels, the client should have cought this before signing a close LC state update function consensusCloseChannel( bytes32 _lcID, uint256 _sequence, uint256[4] _balances, // 0: ethBalanceA 1:ethBalanceI 2:tokenBalanceA 3:tokenBalanceI string _sigA, string _sigI ) public { // assume num open vc is 0 and root hash is 0x0 //require(Channels[_lcID].sequence < _sequence); require(Channels[_lcID].isOpen == true); uint256 totalEthDeposit = Channels[_lcID].initialDeposit[0] + Channels[_lcID].ethBalances[2] + Channels[_lcID].ethBalances[3]; uint256 totalTokenDeposit = Channels[_lcID].initialDeposit[1] + Channels[_lcID].erc20Balances[2] + Channels[_lcID].erc20Balances[3]; require(totalEthDeposit == _balances[0] + _balances[1]); require(totalTokenDeposit == _balances[2] + _balances[3]); bytes32 _state = keccak256( abi.encodePacked( _lcID, true, _sequence, uint256(0), bytes32(0x0), Channels[_lcID].partyAddresses[0], Channels[_lcID].partyAddresses[1], _balances[0], _balances[1], _balances[2], _balances[3] ) ); require(Channels[_lcID].partyAddresses[0] == ECTools.recoverSigner(_state, _sigA)); require(Channels[_lcID].partyAddresses[1] == ECTools.recoverSigner(_state, _sigI)); Channels[_lcID].isOpen = false; if(_balances[0] != 0 || _balances[1] != 0) { Channels[_lcID].partyAddresses[0].transfer(_balances[0]); Channels[_lcID].partyAddresses[1].transfer(_balances[1]); } if(_balances[2] != 0 || _balances[3] != 0) { require(Channels[_lcID].token.transfer(Channels[_lcID].partyAddresses[0], _balances[2]),"happyCloseChannel: token transfer failure"); require(Channels[_lcID].token.transfer(Channels[_lcID].partyAddresses[1], _balances[3]),"happyCloseChannel: token transfer failure"); } numChannels--; emit DidLCClose(_lcID, _sequence, _balances[0], _balances[1], _balances[2], _balances[3]); } // Byzantine functions function updateLCstate( bytes32 _lcID, uint256[6] updateParams, // [sequence, numOpenVc, ethbalanceA, ethbalanceI, tokenbalanceA, tokenbalanceI] bytes32 _VCroot, string _sigA, string _sigI ) public { Channel storage channel = Channels[_lcID]; require(channel.isOpen); require(channel.sequence < updateParams[0]); // do same as vc sequence check require(channel.ethBalances[0] + channel.ethBalances[1] >= updateParams[2] + updateParams[3]); require(channel.erc20Balances[0] + channel.erc20Balances[1] >= updateParams[4] + updateParams[5]); if(channel.isUpdateLCSettling == true) { require(channel.updateLCtimeout > now); } bytes32 _state = keccak256( abi.encodePacked( _lcID, false, updateParams[0], updateParams[1], _VCroot, channel.partyAddresses[0], channel.partyAddresses[1], updateParams[2], updateParams[3], updateParams[4], updateParams[5] ) ); require(channel.partyAddresses[0] == ECTools.recoverSigner(_state, _sigA)); require(channel.partyAddresses[1] == ECTools.recoverSigner(_state, _sigI)); // update LC state channel.sequence = updateParams[0]; channel.numOpenVC = updateParams[1]; channel.ethBalances[0] = updateParams[2]; channel.ethBalances[1] = updateParams[3]; channel.erc20Balances[0] = updateParams[4]; channel.erc20Balances[1] = updateParams[5]; channel.VCrootHash = _VCroot; channel.isUpdateLCSettling = true; channel.updateLCtimeout = now + channel.confirmTime; // make settlement flag emit DidLCUpdateState ( _lcID, updateParams[0], updateParams[1], updateParams[2], updateParams[3], updateParams[4], updateParams[5], _VCroot, channel.updateLCtimeout ); } // supply initial state of VC to "prime" the force push game function initVCstate( bytes32 _lcID, bytes32 _vcID, bytes _proof, address _partyA, address _partyB, uint256[2] _bond, uint256[4] _balances, // 0: ethBalanceA 1:ethBalanceI 2:tokenBalanceA 3:tokenBalanceI string sigA ) public { require(Channels[_lcID].isOpen, "LC is closed."); // sub-channel must be open require(!virtualChannels[_vcID].isClose, "VC is closed."); // Check time has passed on updateLCtimeout and has not passed the time to store a vc state require(Channels[_lcID].updateLCtimeout < now, "LC timeout not over."); // prevent rentry of initializing vc state require(virtualChannels[_vcID].updateVCtimeout == 0); // partyB is now Ingrid bytes32 _initState = keccak256( abi.encodePacked(_vcID, uint256(0), _partyA, _partyB, _bond[0], _bond[1], _balances[0], _balances[1], _balances[2], _balances[3]) ); // Make sure Alice has signed initial vc state (A/B in oldState) require(_partyA == ECTools.recoverSigner(_initState, sigA)); // Check the oldState is in the root hash require(_isContained(_initState, _proof, Channels[_lcID].VCrootHash) == true); virtualChannels[_vcID].partyA = _partyA; // VC participant A virtualChannels[_vcID].partyB = _partyB; // VC participant B virtualChannels[_vcID].sequence = uint256(0); virtualChannels[_vcID].ethBalances[0] = _balances[0]; virtualChannels[_vcID].ethBalances[1] = _balances[1]; virtualChannels[_vcID].erc20Balances[0] = _balances[2]; virtualChannels[_vcID].erc20Balances[1] = _balances[3]; virtualChannels[_vcID].bond = _bond; virtualChannels[_vcID].updateVCtimeout = now + Channels[_lcID].confirmTime; virtualChannels[_vcID].isInSettlementState = true; emit DidVCInit(_lcID, _vcID, _proof, uint256(0), _partyA, _partyB, _balances[0], _balances[1]); } //TODO: verify state transition since the hub did not agree to this state // make sure the A/B balances are not beyond ingrids bonds // Params: vc init state, vc final balance, vcID function settleVC( bytes32 _lcID, bytes32 _vcID, uint256 updateSeq, address _partyA, address _partyB, uint256[4] updateBal, // [ethupdateBalA, ethupdateBalB, tokenupdateBalA, tokenupdateBalB] string sigA ) public { require(Channels[_lcID].isOpen, "LC is closed."); // sub-channel must be open require(!virtualChannels[_vcID].isClose, "VC is closed."); require(virtualChannels[_vcID].sequence < updateSeq, "VC sequence is higher than update sequence."); require( virtualChannels[_vcID].ethBalances[1] < updateBal[1] && virtualChannels[_vcID].erc20Balances[1] < updateBal[3], "State updates may only increase recipient balance." ); require( virtualChannels[_vcID].bond[0] == updateBal[0] + updateBal[1] && virtualChannels[_vcID].bond[1] == updateBal[2] + updateBal[3], "Incorrect balances for bonded amount"); // Check time has passed on updateLCtimeout and has not passed the time to store a vc state // virtualChannels[_vcID].updateVCtimeout should be 0 on uninitialized vc state, and this should // fail if initVC() isn't called first // require(Channels[_lcID].updateLCtimeout < now && now < virtualChannels[_vcID].updateVCtimeout); require(Channels[_lcID].updateLCtimeout < now); // for testing! bytes32 _updateState = keccak256( abi.encodePacked( _vcID, updateSeq, _partyA, _partyB, virtualChannels[_vcID].bond[0], virtualChannels[_vcID].bond[1], updateBal[0], updateBal[1], updateBal[2], updateBal[3] ) ); // Make sure Alice has signed a higher sequence new state require(virtualChannels[_vcID].partyA == ECTools.recoverSigner(_updateState, sigA)); // store VC data // we may want to record who is initiating on-chain settles virtualChannels[_vcID].challenger = msg.sender; virtualChannels[_vcID].sequence = updateSeq; // channel state virtualChannels[_vcID].ethBalances[0] = updateBal[0]; virtualChannels[_vcID].ethBalances[1] = updateBal[1]; virtualChannels[_vcID].erc20Balances[0] = updateBal[2]; virtualChannels[_vcID].erc20Balances[1] = updateBal[3]; virtualChannels[_vcID].updateVCtimeout = now + Channels[_lcID].confirmTime; emit DidVCSettle(_lcID, _vcID, updateSeq, updateBal[0], updateBal[1], msg.sender, virtualChannels[_vcID].updateVCtimeout); } function closeVirtualChannel(bytes32 _lcID, bytes32 _vcID) public { // require(updateLCtimeout > now) require(Channels[_lcID].isOpen, "LC is closed."); require(virtualChannels[_vcID].isInSettlementState, "VC is not in settlement state."); require(virtualChannels[_vcID].updateVCtimeout < now, "Update vc timeout has not elapsed."); require(!virtualChannels[_vcID].isClose, "VC is already closed"); // reduce the number of open virtual channels stored on LC Channels[_lcID].numOpenVC--; // close vc flags virtualChannels[_vcID].isClose = true; // re-introduce the balances back into the LC state from the settled VC // decide if this lc is alice or bob in the vc if(virtualChannels[_vcID].partyA == Channels[_lcID].partyAddresses[0]) { Channels[_lcID].ethBalances[0] += virtualChannels[_vcID].ethBalances[0]; Channels[_lcID].ethBalances[1] += virtualChannels[_vcID].ethBalances[1]; Channels[_lcID].erc20Balances[0] += virtualChannels[_vcID].erc20Balances[0]; Channels[_lcID].erc20Balances[1] += virtualChannels[_vcID].erc20Balances[1]; } else if (virtualChannels[_vcID].partyB == Channels[_lcID].partyAddresses[0]) { Channels[_lcID].ethBalances[0] += virtualChannels[_vcID].ethBalances[1]; Channels[_lcID].ethBalances[1] += virtualChannels[_vcID].ethBalances[0]; Channels[_lcID].erc20Balances[0] += virtualChannels[_vcID].erc20Balances[1]; Channels[_lcID].erc20Balances[1] += virtualChannels[_vcID].erc20Balances[0]; } emit DidVCClose(_lcID, _vcID, virtualChannels[_vcID].erc20Balances[0], virtualChannels[_vcID].erc20Balances[1]); } // todo: allow ethier lc.end-user to nullify the settled LC state and return to off-chain function byzantineCloseChannel(bytes32 _lcID) public { Channel storage channel = Channels[_lcID]; // check settlement flag require(channel.isOpen, "Channel is not open"); require(channel.isUpdateLCSettling == true); require(channel.numOpenVC == 0); require(channel.updateLCtimeout < now, "LC timeout over."); // if off chain state update didnt reblance deposits, just return to deposit owner uint256 totalEthDeposit = channel.initialDeposit[0] + channel.ethBalances[2] + channel.ethBalances[3]; uint256 totalTokenDeposit = channel.initialDeposit[1] + channel.erc20Balances[2] + channel.erc20Balances[3]; uint256 possibleTotalEthBeforeDeposit = channel.ethBalances[0] + channel.ethBalances[1]; uint256 possibleTotalTokenBeforeDeposit = channel.erc20Balances[0] + channel.erc20Balances[1]; if(possibleTotalEthBeforeDeposit < totalEthDeposit) { channel.ethBalances[0]+=channel.ethBalances[2]; channel.ethBalances[1]+=channel.ethBalances[3]; } else { require(possibleTotalEthBeforeDeposit == totalEthDeposit); } if(possibleTotalTokenBeforeDeposit < totalTokenDeposit) { channel.erc20Balances[0]+=channel.erc20Balances[2]; channel.erc20Balances[1]+=channel.erc20Balances[3]; } else { require(possibleTotalTokenBeforeDeposit == totalTokenDeposit); } // reentrancy uint256 ethbalanceA = channel.ethBalances[0]; uint256 ethbalanceI = channel.ethBalances[1]; uint256 tokenbalanceA = channel.erc20Balances[0]; uint256 tokenbalanceI = channel.erc20Balances[1]; channel.ethBalances[0] = 0; channel.ethBalances[1] = 0; channel.erc20Balances[0] = 0; channel.erc20Balances[1] = 0; if(ethbalanceA != 0 || ethbalanceI != 0) { channel.partyAddresses[0].transfer(ethbalanceA); channel.partyAddresses[1].transfer(ethbalanceI); } if(tokenbalanceA != 0 || tokenbalanceI != 0) { require( channel.token.transfer(channel.partyAddresses[0], tokenbalanceA), "byzantineCloseChannel: token transfer failure" ); require( channel.token.transfer(channel.partyAddresses[1], tokenbalanceI), "byzantineCloseChannel: token transfer failure" ); } channel.isOpen = false; numChannels--; emit DidLCClose(_lcID, channel.sequence, ethbalanceA, ethbalanceI, tokenbalanceA, tokenbalanceI); } function _isContained(bytes32 _hash, bytes _proof, bytes32 _root) internal pure returns (bool) { bytes32 cursor = _hash; bytes32 proofElem; for (uint256 i = 64; i <= _proof.length; i += 32) { assembly { proofElem := mload(add(_proof, i)) } if (cursor < proofElem) { cursor = keccak256(abi.encodePacked(cursor, proofElem)); } else { cursor = keccak256(abi.encodePacked(proofElem, cursor)); } } return cursor == _root; } //Struct Getters function getChannel(bytes32 id) public view returns ( address[2], uint256[4], uint256[4], uint256[2], uint256, uint256, bytes32, uint256, uint256, bool, bool, uint256 ) { Channel memory channel = Channels[id]; return ( channel.partyAddresses, channel.ethBalances, channel.erc20Balances, channel.initialDeposit, channel.sequence, channel.confirmTime, channel.VCrootHash, channel.LCopenTimeout, channel.updateLCtimeout, channel.isOpen, channel.isUpdateLCSettling, channel.numOpenVC ); } function getVirtualChannel(bytes32 id) public view returns( bool, bool, uint256, address, uint256, address, address, address, uint256[2], uint256[2], uint256[2] ) { VirtualChannel memory virtualChannel = virtualChannels[id]; return( virtualChannel.isClose, virtualChannel.isInSettlementState, virtualChannel.sequence, virtualChannel.challenger, virtualChannel.updateVCtimeout, virtualChannel.partyA, virtualChannel.partyB, virtualChannel.partyI, virtualChannel.ethBalances, virtualChannel.erc20Balances, virtualChannel.bond ); } }
Set initial ledger channel state Alice must execute this and we assume the initial state to be signed from this requirement Alternative is to check a sig as in joinChannel
function createChannel( bytes32 _lcID, address _partyI, uint256 _confirmTime, address _token, ) public payable { require(Channels[_lcID].partyAddresses[0] == address(0), "Channel has already been created."); require(_partyI != 0x0, "No partyI address provided to LC creation"); require(_balances[0] >= 0 && _balances[1] >= 0, "Balances cannot be negative"); Channels[_lcID].partyAddresses[0] = msg.sender; Channels[_lcID].partyAddresses[1] = _partyI; if(_balances[0] != 0) { require(msg.value == _balances[0], "Eth balance does not match sent value"); Channels[_lcID].ethBalances[0] = msg.value; } if(_balances[1] != 0) { Channels[_lcID].token = HumanStandardToken(_token); require(Channels[_lcID].token.transferFrom(msg.sender, this, _balances[1]),"CreateChannel: token transfer failure"); Channels[_lcID].erc20Balances[0] = _balances[1]; } Channels[_lcID].sequence = 0; Channels[_lcID].confirmTime = _confirmTime; Channels[_lcID].initialDeposit = _balances; emit DidLCOpen(_lcID, msg.sender, _partyI, _balances[0], _token, _balances[1], Channels[_lcID].LCopenTimeout); }
1,494,065
./full_match/4/0x3b6dB6D2A1200E554e377787d711a6bfC0dbf13e/sources/contracts/external/IERC20.sol
Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); pragma solidity ^0.6.0; }
693,613
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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 Owned contract with safe ownership pass. * * Note: all the non constant functions return false instead of throwing in case if state change * didn't happen yet. */ contract Owned { /** * Contract owner address */ address public contractOwner; /** * Contract owner address */ address public pendingContractOwner; function Owned() { contractOwner = msg.sender; } /** * @dev Owner check modifier */ modifier onlyContractOwner() { if (contractOwner == msg.sender) { _; } } /** * @dev Destroy contract and scrub a data * @notice Only owner can call it */ function destroy() onlyContractOwner { suicide(msg.sender); } /** * Prepares ownership pass. * * Can only be called by current owner. * * @param _to address of the next owner. 0x0 is not allowed. * * @return success. */ function changeContractOwnership(address _to) onlyContractOwner() returns(bool) { if (_to == 0x0) { return false; } pendingContractOwner = _to; return true; } /** * Finalize ownership pass. * * Can only be called by pending owner. * * @return success. */ function claimContractOwnership() returns(bool) { if (pendingContractOwner != msg.sender) { return false; } contractOwner = pendingContractOwner; delete pendingContractOwner; return true; } } contract ERC20Interface { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; function totalSupply() constant returns (uint256 supply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); } /** * @title Generic owned destroyable contract */ contract Object is Owned { /** * Common result code. Means everything is fine. */ uint constant OK = 1; uint constant OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER = 8; function withdrawnTokens(address[] tokens, address _to) onlyContractOwner returns(uint) { for(uint i=0;i<tokens.length;i++) { address token = tokens[i]; uint balance = ERC20Interface(token).balanceOf(this); if(balance != 0) ERC20Interface(token).transfer(_to,balance); } return OK; } function checkOnlyContractOwner() internal constant returns(uint) { if (contractOwner == msg.sender) { return OK; } return OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER; } } contract OracleMethodAdapter is Object { event OracleAdded(bytes4 _sig, address _oracle); event OracleRemoved(bytes4 _sig, address _oracle); mapping(bytes4 => mapping(address => bool)) public oracles; /// @dev Allow access only for oracle modifier onlyOracle { if (oracles[msg.sig][msg.sender]) { _; } } modifier onlyOracleOrOwner { if (oracles[msg.sig][msg.sender] || msg.sender == contractOwner) { _; } } function addOracles(bytes4[] _signatures, address[] _oracles) onlyContractOwner external returns (uint) { require(_signatures.length == _oracles.length); bytes4 _sig; address _oracle; for (uint _idx = 0; _idx < _signatures.length; ++_idx) { (_sig, _oracle) = (_signatures[_idx], _oracles[_idx]); if (!oracles[_sig][_oracle]) { oracles[_sig][_oracle] = true; _emitOracleAdded(_sig, _oracle); } } return OK; } function removeOracles(bytes4[] _signatures, address[] _oracles) onlyContractOwner external returns (uint) { require(_signatures.length == _oracles.length); bytes4 _sig; address _oracle; for (uint _idx = 0; _idx < _signatures.length; ++_idx) { (_sig, _oracle) = (_signatures[_idx], _oracles[_idx]); if (oracles[_sig][_oracle]) { delete oracles[_sig][_oracle]; _emitOracleRemoved(_sig, _oracle); } } return OK; } function _emitOracleAdded(bytes4 _sig, address _oracle) internal { OracleAdded(_sig, _oracle); } function _emitOracleRemoved(bytes4 _sig, address _oracle) internal { OracleRemoved(_sig, _oracle); } } /// @title Provides possibility manage holders? country limits and limits for holders. contract DataControllerInterface { /// @notice Checks user is holder. /// @param _address - checking address. /// @return `true` if _address is registered holder, `false` otherwise. function isHolderAddress(address _address) public view returns (bool); function allowance(address _user) public view returns (uint); function changeAllowance(address _holder, uint _value) public returns (uint); } /// @title ServiceController /// /// Base implementation /// Serves for managing service instances contract ServiceControllerInterface { /// @notice Check target address is service /// @param _address target address /// @return `true` when an address is a service, `false` otherwise function isService(address _address) public view returns (bool); } contract ATxAssetInterface { DataControllerInterface public dataController; ServiceControllerInterface public serviceController; function __transferWithReference(address _to, uint _value, string _reference, address _sender) public returns (bool); function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns (bool); function __approve(address _spender, uint _value, address _sender) public returns (bool); function __process(bytes /*_data*/, address /*_sender*/) payable public { revert(); } } /// @title ServiceAllowance. /// /// Provides a way to delegate operation allowance decision to a service contract contract ServiceAllowance { function isTransferAllowed(address _from, address _to, address _sender, address _token, uint _value) public view returns (bool); } contract ERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; function totalSupply() constant returns (uint256 supply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); } contract Platform { mapping(bytes32 => address) public proxies; function name(bytes32 _symbol) public view returns (string); function setProxy(address _address, bytes32 _symbol) public returns (uint errorCode); function isOwner(address _owner, bytes32 _symbol) public view returns (bool); function totalSupply(bytes32 _symbol) public view returns (uint); function balanceOf(address _holder, bytes32 _symbol) public view returns (uint); function allowance(address _from, address _spender, bytes32 _symbol) public view returns (uint); function baseUnit(bytes32 _symbol) public view returns (uint8); function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns (uint errorCode); function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns (uint errorCode); function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) public returns (uint errorCode); function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) public returns (uint errorCode); function reissueAsset(bytes32 _symbol, uint _value) public returns (uint errorCode); function revokeAsset(bytes32 _symbol, uint _value) public returns (uint errorCode); function isReissuable(bytes32 _symbol) public view returns (bool); function changeOwnership(bytes32 _symbol, address _newOwner) public returns (uint errorCode); } contract ATxAssetProxy is ERC20, Object, ServiceAllowance { // Timespan for users to review the new implementation and make decision. uint constant UPGRADE_FREEZE_TIME = 3 days; using SafeMath for uint; /** * Indicates an upgrade freeze-time start, and the next asset implementation contract. */ event UpgradeProposal(address newVersion); // Current asset implementation contract address. address latestVersion; // Proposed next asset implementation contract address. address pendingVersion; // Upgrade freeze-time start. uint pendingVersionTimestamp; // Assigned platform, immutable. Platform public platform; // Assigned symbol, immutable. bytes32 public smbl; // Assigned name, immutable. string public name; /** * Only platform is allowed to call. */ modifier onlyPlatform() { if (msg.sender == address(platform)) { _; } } /** * Only current asset owner is allowed to call. */ modifier onlyAssetOwner() { if (platform.isOwner(msg.sender, smbl)) { _; } } /** * Only asset implementation contract assigned to sender is allowed to call. */ modifier onlyAccess(address _sender) { if (getLatestVersion() == msg.sender) { _; } } /** * Resolves asset implementation contract for the caller and forwards there transaction data, * along with the value. This allows for proxy interface growth. */ function() public payable { _getAsset().__process.value(msg.value)(msg.data, msg.sender); } /** * Sets platform address, assigns symbol and name. * * Can be set only once. * * @param _platform platform contract address. * @param _symbol assigned symbol. * @param _name assigned name. * * @return success. */ function init(Platform _platform, string _symbol, string _name) public returns (bool) { if (address(platform) != 0x0) { return false; } platform = _platform; symbol = _symbol; smbl = stringToBytes32(_symbol); name = _name; return true; } /** * Returns asset total supply. * * @return asset total supply. */ function totalSupply() public view returns (uint) { return platform.totalSupply(smbl); } /** * Returns asset balance for a particular holder. * * @param _owner holder address. * * @return holder balance. */ function balanceOf(address _owner) public view returns (uint) { return platform.balanceOf(_owner, smbl); } /** * Returns asset allowance from one holder to another. * * @param _from holder that allowed spending. * @param _spender holder that is allowed to spend. * * @return holder to spender allowance. */ function allowance(address _from, address _spender) public view returns (uint) { return platform.allowance(_from, _spender, smbl); } /** * Returns asset decimals. * * @return asset decimals. */ function decimals() public view returns (uint8) { return platform.baseUnit(smbl); } /** * Transfers asset balance from the caller to specified receiver. * * @param _to holder address to give to. * @param _value amount to transfer. * * @return success. */ function transfer(address _to, uint _value) public returns (bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, ""); } else { return false; } } /** * Transfers asset balance from the caller to specified receiver adding specified comment. * * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a platform's Transfer event. * * @return success. */ function transferWithReference(address _to, uint _value, string _reference) public returns (bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, _reference); } else { return false; } } /** * Performs transfer call on the platform by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a platform's Transfer event. * @param _sender initial caller. * * @return success. */ function __transferWithReference(address _to, uint _value, string _reference, address _sender) public onlyAccess(_sender) returns (bool) { return platform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK; } /** * Prforms allowance transfer of asset balance between holders. * * @param _from holder address to take from. * @param _to holder address to give to. * @param _value amount to transfer. * * @return success. */ function transferFrom(address _from, address _to, uint _value) public returns (bool) { if (_to != 0x0) { return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender); } else { return false; } } /** * Performs allowance transfer call on the platform by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _from holder address to take from. * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a platform's Transfer event. * @param _sender initial caller. * * @return success. */ function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public onlyAccess(_sender) returns (bool) { return platform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK; } /** * Sets asset spending allowance for a specified spender. * * @param _spender holder address to set allowance to. * @param _value amount to allow. * * @return success. */ function approve(address _spender, uint _value) public returns (bool) { if (_spender != 0x0) { return _getAsset().__approve(_spender, _value, msg.sender); } else { return false; } } /** * Performs allowance setting call on the platform by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _spender holder address to set allowance to. * @param _value amount to allow. * @param _sender initial caller. * * @return success. */ function __approve(address _spender, uint _value, address _sender) public onlyAccess(_sender) returns (bool) { return platform.proxyApprove(_spender, _value, smbl, _sender) == OK; } /** * Emits ERC20 Transfer event on this contract. * * Can only be, and, called by assigned platform when asset transfer happens. */ function emitTransfer(address _from, address _to, uint _value) public onlyPlatform() { Transfer(_from, _to, _value); } /** * Emits ERC20 Approval event on this contract. * * Can only be, and, called by assigned platform when asset allowance set happens. */ function emitApprove(address _from, address _spender, uint _value) public onlyPlatform() { Approval(_from, _spender, _value); } /** * Returns current asset implementation contract address. * * @return asset implementation contract address. */ function getLatestVersion() public view returns (address) { return latestVersion; } /** * Returns proposed next asset implementation contract address. * * @return asset implementation contract address. */ function getPendingVersion() public view returns (address) { return pendingVersion; } /** * Returns upgrade freeze-time start. * * @return freeze-time start. */ function getPendingVersionTimestamp() public view returns (uint) { return pendingVersionTimestamp; } /** * Propose next asset implementation contract address. * * Can only be called by current asset owner. * * Note: freeze-time should not be applied for the initial setup. * * @param _newVersion asset implementation contract address. * * @return success. */ function proposeUpgrade(address _newVersion) public onlyAssetOwner returns (bool) { // Should not already be in the upgrading process. if (pendingVersion != 0x0) { return false; } // New version address should be other than 0x0. if (_newVersion == 0x0) { return false; } // Don't apply freeze-time for the initial setup. if (latestVersion == 0x0) { latestVersion = _newVersion; return true; } pendingVersion = _newVersion; pendingVersionTimestamp = now; UpgradeProposal(_newVersion); return true; } /** * Cancel the pending upgrade process. * * Can only be called by current asset owner. * * @return success. */ function purgeUpgrade() public onlyAssetOwner returns (bool) { if (pendingVersion == 0x0) { return false; } delete pendingVersion; delete pendingVersionTimestamp; return true; } /** * Finalize an upgrade process setting new asset implementation contract address. * * Can only be called after an upgrade freeze-time. * * @return success. */ function commitUpgrade() public returns (bool) { if (pendingVersion == 0x0) { return false; } if (pendingVersionTimestamp.add(UPGRADE_FREEZE_TIME) > now) { return false; } latestVersion = pendingVersion; delete pendingVersion; delete pendingVersionTimestamp; return true; } function isTransferAllowed(address, address, address, address, uint) public view returns (bool) { return true; } /** * Returns asset implementation contract for current caller. * * @return asset implementation contract. */ function _getAsset() internal view returns (ATxAssetInterface) { return ATxAssetInterface(getLatestVersion()); } /** * Resolves asset implementation contract for the caller and forwards there arguments along with * the caller address. * * @return success. */ function _transferWithReference(address _to, uint _value, string _reference) internal returns (bool) { return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender); } function stringToBytes32(string memory source) private pure returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } } contract DataControllerEmitter { event CountryCodeAdded(uint _countryCode, uint _countryId, uint _maxHolderCount); event CountryCodeChanged(uint _countryCode, uint _countryId, uint _maxHolderCount); event HolderRegistered(bytes32 _externalHolderId, uint _accessIndex, uint _countryCode); event HolderAddressAdded(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex); event HolderAddressRemoved(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex); event HolderOperationalChanged(bytes32 _externalHolderId, bool _operational); event DayLimitChanged(bytes32 _externalHolderId, uint _from, uint _to); event MonthLimitChanged(bytes32 _externalHolderId, uint _from, uint _to); event Error(uint _errorCode); function _emitHolderAddressAdded(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex) internal { HolderAddressAdded(_externalHolderId, _holderPrototype, _accessIndex); } function _emitHolderAddressRemoved(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex) internal { HolderAddressRemoved(_externalHolderId, _holderPrototype, _accessIndex); } function _emitHolderRegistered(bytes32 _externalHolderId, uint _accessIndex, uint _countryCode) internal { HolderRegistered(_externalHolderId, _accessIndex, _countryCode); } function _emitHolderOperationalChanged(bytes32 _externalHolderId, bool _operational) internal { HolderOperationalChanged(_externalHolderId, _operational); } function _emitCountryCodeAdded(uint _countryCode, uint _countryId, uint _maxHolderCount) internal { CountryCodeAdded(_countryCode, _countryId, _maxHolderCount); } function _emitCountryCodeChanged(uint _countryCode, uint _countryId, uint _maxHolderCount) internal { CountryCodeChanged(_countryCode, _countryId, _maxHolderCount); } function _emitDayLimitChanged(bytes32 _externalHolderId, uint _from, uint _to) internal { DayLimitChanged(_externalHolderId, _from, _to); } function _emitMonthLimitChanged(bytes32 _externalHolderId, uint _from, uint _to) internal { MonthLimitChanged(_externalHolderId, _from, _to); } function _emitError(uint _errorCode) internal returns (uint) { Error(_errorCode); return _errorCode; } } contract GroupsAccessManagerEmitter { event UserCreated(address user); event UserDeleted(address user); event GroupCreated(bytes32 groupName); event GroupActivated(bytes32 groupName); event GroupDeactivated(bytes32 groupName); event UserToGroupAdded(address user, bytes32 groupName); event UserFromGroupRemoved(address user, bytes32 groupName); } /// @title Group Access Manager /// /// Base implementation /// This contract serves as group manager contract GroupsAccessManager is Object, GroupsAccessManagerEmitter { uint constant USER_MANAGER_SCOPE = 111000; uint constant USER_MANAGER_MEMBER_ALREADY_EXIST = USER_MANAGER_SCOPE + 1; uint constant USER_MANAGER_GROUP_ALREADY_EXIST = USER_MANAGER_SCOPE + 2; uint constant USER_MANAGER_OBJECT_ALREADY_SECURED = USER_MANAGER_SCOPE + 3; uint constant USER_MANAGER_CONFIRMATION_HAS_COMPLETED = USER_MANAGER_SCOPE + 4; uint constant USER_MANAGER_USER_HAS_CONFIRMED = USER_MANAGER_SCOPE + 5; uint constant USER_MANAGER_NOT_ENOUGH_GAS = USER_MANAGER_SCOPE + 6; uint constant USER_MANAGER_INVALID_INVOCATION = USER_MANAGER_SCOPE + 7; uint constant USER_MANAGER_DONE = USER_MANAGER_SCOPE + 11; uint constant USER_MANAGER_CANCELLED = USER_MANAGER_SCOPE + 12; using SafeMath for uint; struct Member { address addr; uint groupsCount; mapping(bytes32 => uint) groupName2index; mapping(uint => uint) index2globalIndex; } struct Group { bytes32 name; uint priority; uint membersCount; mapping(address => uint) memberAddress2index; mapping(uint => uint) index2globalIndex; } uint public membersCount; mapping(uint => address) index2memberAddress; mapping(address => uint) memberAddress2index; mapping(address => Member) address2member; uint public groupsCount; mapping(uint => bytes32) index2groupName; mapping(bytes32 => uint) groupName2index; mapping(bytes32 => Group) groupName2group; mapping(bytes32 => bool) public groupsBlocked; // if groupName => true, then couldn't be used for confirmation function() payable public { revert(); } /// @notice Register user /// Can be called only by contract owner /// /// @param _user user address /// /// @return code function registerUser(address _user) external onlyContractOwner returns (uint) { require(_user != 0x0); if (isRegisteredUser(_user)) { return USER_MANAGER_MEMBER_ALREADY_EXIST; } uint _membersCount = membersCount.add(1); membersCount = _membersCount; memberAddress2index[_user] = _membersCount; index2memberAddress[_membersCount] = _user; address2member[_user] = Member(_user, 0); UserCreated(_user); return OK; } /// @notice Discard user registration /// Can be called only by contract owner /// /// @param _user user address /// /// @return code function unregisterUser(address _user) external onlyContractOwner returns (uint) { require(_user != 0x0); uint _memberIndex = memberAddress2index[_user]; if (_memberIndex == 0 || address2member[_user].groupsCount != 0) { return USER_MANAGER_INVALID_INVOCATION; } uint _membersCount = membersCount; delete memberAddress2index[_user]; if (_memberIndex != _membersCount) { address _lastUser = index2memberAddress[_membersCount]; index2memberAddress[_memberIndex] = _lastUser; memberAddress2index[_lastUser] = _memberIndex; } delete address2member[_user]; delete index2memberAddress[_membersCount]; delete memberAddress2index[_user]; membersCount = _membersCount.sub(1); UserDeleted(_user); return OK; } /// @notice Create group /// Can be called only by contract owner /// /// @param _groupName group name /// @param _priority group priority /// /// @return code function createGroup(bytes32 _groupName, uint _priority) external onlyContractOwner returns (uint) { require(_groupName != bytes32(0)); if (isGroupExists(_groupName)) { return USER_MANAGER_GROUP_ALREADY_EXIST; } uint _groupsCount = groupsCount.add(1); groupName2index[_groupName] = _groupsCount; index2groupName[_groupsCount] = _groupName; groupName2group[_groupName] = Group(_groupName, _priority, 0); groupsCount = _groupsCount; GroupCreated(_groupName); return OK; } /// @notice Change group status /// Can be called only by contract owner /// /// @param _groupName group name /// @param _blocked block status /// /// @return code function changeGroupActiveStatus(bytes32 _groupName, bool _blocked) external onlyContractOwner returns (uint) { require(isGroupExists(_groupName)); groupsBlocked[_groupName] = _blocked; return OK; } /// @notice Add users in group /// Can be called only by contract owner /// /// @param _groupName group name /// @param _users user array /// /// @return code function addUsersToGroup(bytes32 _groupName, address[] _users) external onlyContractOwner returns (uint) { require(isGroupExists(_groupName)); Group storage _group = groupName2group[_groupName]; uint _groupMembersCount = _group.membersCount; for (uint _userIdx = 0; _userIdx < _users.length; ++_userIdx) { address _user = _users[_userIdx]; uint _memberIndex = memberAddress2index[_user]; require(_memberIndex != 0); if (_group.memberAddress2index[_user] != 0) { continue; } _groupMembersCount = _groupMembersCount.add(1); _group.memberAddress2index[_user] = _groupMembersCount; _group.index2globalIndex[_groupMembersCount] = _memberIndex; _addGroupToMember(_user, _groupName); UserToGroupAdded(_user, _groupName); } _group.membersCount = _groupMembersCount; return OK; } /// @notice Remove users in group /// Can be called only by contract owner /// /// @param _groupName group name /// @param _users user array /// /// @return code function removeUsersFromGroup(bytes32 _groupName, address[] _users) external onlyContractOwner returns (uint) { require(isGroupExists(_groupName)); Group storage _group = groupName2group[_groupName]; uint _groupMembersCount = _group.membersCount; for (uint _userIdx = 0; _userIdx < _users.length; ++_userIdx) { address _user = _users[_userIdx]; uint _memberIndex = memberAddress2index[_user]; uint _groupMemberIndex = _group.memberAddress2index[_user]; if (_memberIndex == 0 || _groupMemberIndex == 0) { continue; } if (_groupMemberIndex != _groupMembersCount) { uint _lastUserGlobalIndex = _group.index2globalIndex[_groupMembersCount]; address _lastUser = index2memberAddress[_lastUserGlobalIndex]; _group.index2globalIndex[_groupMemberIndex] = _lastUserGlobalIndex; _group.memberAddress2index[_lastUser] = _groupMemberIndex; } delete _group.memberAddress2index[_user]; delete _group.index2globalIndex[_groupMembersCount]; _groupMembersCount = _groupMembersCount.sub(1); _removeGroupFromMember(_user, _groupName); UserFromGroupRemoved(_user, _groupName); } _group.membersCount = _groupMembersCount; return OK; } /// @notice Check is user registered /// /// @param _user user address /// /// @return status function isRegisteredUser(address _user) public view returns (bool) { return memberAddress2index[_user] != 0; } /// @notice Check is user in group /// /// @param _groupName user array /// @param _user user array /// /// @return status function isUserInGroup(bytes32 _groupName, address _user) public view returns (bool) { return isRegisteredUser(_user) && address2member[_user].groupName2index[_groupName] != 0; } /// @notice Check is group exist /// /// @param _groupName group name /// /// @return status function isGroupExists(bytes32 _groupName) public view returns (bool) { return groupName2index[_groupName] != 0; } /// @notice Get current group names /// /// @return group names function getGroups() public view returns (bytes32[] _groups) { uint _groupsCount = groupsCount; _groups = new bytes32[](_groupsCount); for (uint _groupIdx = 0; _groupIdx < _groupsCount; ++_groupIdx) { _groups[_groupIdx] = index2groupName[_groupIdx + 1]; } } // PRIVATE function _removeGroupFromMember(address _user, bytes32 _groupName) private { Member storage _member = address2member[_user]; uint _memberGroupsCount = _member.groupsCount; uint _memberGroupIndex = _member.groupName2index[_groupName]; if (_memberGroupIndex != _memberGroupsCount) { uint _lastGroupGlobalIndex = _member.index2globalIndex[_memberGroupsCount]; bytes32 _lastGroupName = index2groupName[_lastGroupGlobalIndex]; _member.index2globalIndex[_memberGroupIndex] = _lastGroupGlobalIndex; _member.groupName2index[_lastGroupName] = _memberGroupIndex; } delete _member.groupName2index[_groupName]; delete _member.index2globalIndex[_memberGroupsCount]; _member.groupsCount = _memberGroupsCount.sub(1); } function _addGroupToMember(address _user, bytes32 _groupName) private { Member storage _member = address2member[_user]; uint _memberGroupsCount = _member.groupsCount.add(1); _member.groupName2index[_groupName] = _memberGroupsCount; _member.index2globalIndex[_memberGroupsCount] = groupName2index[_groupName]; _member.groupsCount = _memberGroupsCount; } } contract PendingManagerEmitter { event PolicyRuleAdded(bytes4 sig, address contractAddress, bytes32 key, bytes32 groupName, uint acceptLimit, uint declinesLimit); event PolicyRuleRemoved(bytes4 sig, address contractAddress, bytes32 key, bytes32 groupName); event ProtectionTxAdded(bytes32 key, bytes32 sig, uint blockNumber); event ProtectionTxAccepted(bytes32 key, address indexed sender, bytes32 groupNameVoted); event ProtectionTxDone(bytes32 key); event ProtectionTxDeclined(bytes32 key, address indexed sender, bytes32 groupNameVoted); event ProtectionTxCancelled(bytes32 key); event ProtectionTxVoteRevoked(bytes32 key, address indexed sender, bytes32 groupNameVoted); event TxDeleted(bytes32 key); event Error(uint errorCode); function _emitError(uint _errorCode) internal returns (uint) { Error(_errorCode); return _errorCode; } } contract PendingManagerInterface { function signIn(address _contract) external returns (uint); function signOut(address _contract) external returns (uint); function addPolicyRule( bytes4 _sig, address _contract, bytes32 _groupName, uint _acceptLimit, uint _declineLimit ) external returns (uint); function removePolicyRule( bytes4 _sig, address _contract, bytes32 _groupName ) external returns (uint); function addTx(bytes32 _key, bytes4 _sig, address _contract) external returns (uint); function deleteTx(bytes32 _key) external returns (uint); function accept(bytes32 _key, bytes32 _votingGroupName) external returns (uint); function decline(bytes32 _key, bytes32 _votingGroupName) external returns (uint); function revoke(bytes32 _key) external returns (uint); function hasConfirmedRecord(bytes32 _key) public view returns (uint); function getPolicyDetails(bytes4 _sig, address _contract) public view returns ( bytes32[] _groupNames, uint[] _acceptLimits, uint[] _declineLimits, uint _totalAcceptedLimit, uint _totalDeclinedLimit ); } /// @title PendingManager /// /// Base implementation /// This contract serves as pending manager for transaction status contract PendingManager is Object, PendingManagerEmitter, PendingManagerInterface { uint constant NO_RECORDS_WERE_FOUND = 4; uint constant PENDING_MANAGER_SCOPE = 4000; uint constant PENDING_MANAGER_INVALID_INVOCATION = PENDING_MANAGER_SCOPE + 1; uint constant PENDING_MANAGER_HASNT_VOTED = PENDING_MANAGER_SCOPE + 2; uint constant PENDING_DUPLICATE_TX = PENDING_MANAGER_SCOPE + 3; uint constant PENDING_MANAGER_CONFIRMED = PENDING_MANAGER_SCOPE + 4; uint constant PENDING_MANAGER_REJECTED = PENDING_MANAGER_SCOPE + 5; uint constant PENDING_MANAGER_IN_PROCESS = PENDING_MANAGER_SCOPE + 6; uint constant PENDING_MANAGER_TX_DOESNT_EXIST = PENDING_MANAGER_SCOPE + 7; uint constant PENDING_MANAGER_TX_WAS_DECLINED = PENDING_MANAGER_SCOPE + 8; uint constant PENDING_MANAGER_TX_WAS_NOT_CONFIRMED = PENDING_MANAGER_SCOPE + 9; uint constant PENDING_MANAGER_INSUFFICIENT_GAS = PENDING_MANAGER_SCOPE + 10; uint constant PENDING_MANAGER_POLICY_NOT_FOUND = PENDING_MANAGER_SCOPE + 11; using SafeMath for uint; enum GuardState { Decline, Confirmed, InProcess } struct Requirements { bytes32 groupName; uint acceptLimit; uint declineLimit; } struct Policy { uint groupsCount; mapping(uint => Requirements) participatedGroups; // index => globalGroupIndex mapping(bytes32 => uint) groupName2index; // groupName => localIndex uint totalAcceptedLimit; uint totalDeclinedLimit; uint securesCount; mapping(uint => uint) index2txIndex; mapping(uint => uint) txIndex2index; } struct Vote { bytes32 groupName; bool accepted; } struct Guard { GuardState state; uint basePolicyIndex; uint alreadyAccepted; uint alreadyDeclined; mapping(address => Vote) votes; // member address => vote mapping(bytes32 => uint) acceptedCount; // groupName => how many from group has already accepted mapping(bytes32 => uint) declinedCount; // groupName => how many from group has already declined } address public accessManager; mapping(address => bool) public authorized; uint public policiesCount; mapping(uint => bytes32) index2PolicyId; // index => policy hash mapping(bytes32 => uint) policyId2Index; // policy hash => index mapping(bytes32 => Policy) policyId2policy; // policy hash => policy struct uint public txCount; mapping(uint => bytes32) index2txKey; mapping(bytes32 => uint) txKey2index; // tx key => index mapping(bytes32 => Guard) txKey2guard; /// @dev Execution is allowed only by authorized contract modifier onlyAuthorized { if (authorized[msg.sender] || address(this) == msg.sender) { _; } } /// @dev Pending Manager's constructor /// /// @param _accessManager access manager's address function PendingManager(address _accessManager) public { require(_accessManager != 0x0); accessManager = _accessManager; } function() payable public { revert(); } /// @notice Update access manager address /// /// @param _accessManager access manager's address function setAccessManager(address _accessManager) external onlyContractOwner returns (uint) { require(_accessManager != 0x0); accessManager = _accessManager; return OK; } /// @notice Sign in contract /// /// @param _contract contract's address function signIn(address _contract) external onlyContractOwner returns (uint) { require(_contract != 0x0); authorized[_contract] = true; return OK; } /// @notice Sign out contract /// /// @param _contract contract's address function signOut(address _contract) external onlyContractOwner returns (uint) { require(_contract != 0x0); delete authorized[_contract]; return OK; } /// @notice Register new policy rule /// Can be called only by contract owner /// /// @param _sig target method signature /// @param _contract target contract address /// @param _groupName group's name /// @param _acceptLimit accepted vote limit /// @param _declineLimit decline vote limit /// /// @return code function addPolicyRule( bytes4 _sig, address _contract, bytes32 _groupName, uint _acceptLimit, uint _declineLimit ) onlyContractOwner external returns (uint) { require(_sig != 0x0); require(_contract != 0x0); require(GroupsAccessManager(accessManager).isGroupExists(_groupName)); require(_acceptLimit != 0); require(_declineLimit != 0); bytes32 _policyHash = keccak256(_sig, _contract); if (policyId2Index[_policyHash] == 0) { uint _policiesCount = policiesCount.add(1); index2PolicyId[_policiesCount] = _policyHash; policyId2Index[_policyHash] = _policiesCount; policiesCount = _policiesCount; } Policy storage _policy = policyId2policy[_policyHash]; uint _policyGroupsCount = _policy.groupsCount; if (_policy.groupName2index[_groupName] == 0) { _policyGroupsCount += 1; _policy.groupName2index[_groupName] = _policyGroupsCount; _policy.participatedGroups[_policyGroupsCount].groupName = _groupName; _policy.groupsCount = _policyGroupsCount; } uint _previousAcceptLimit = _policy.participatedGroups[_policyGroupsCount].acceptLimit; uint _previousDeclineLimit = _policy.participatedGroups[_policyGroupsCount].declineLimit; _policy.participatedGroups[_policyGroupsCount].acceptLimit = _acceptLimit; _policy.participatedGroups[_policyGroupsCount].declineLimit = _declineLimit; _policy.totalAcceptedLimit = _policy.totalAcceptedLimit.sub(_previousAcceptLimit).add(_acceptLimit); _policy.totalDeclinedLimit = _policy.totalDeclinedLimit.sub(_previousDeclineLimit).add(_declineLimit); PolicyRuleAdded(_sig, _contract, _policyHash, _groupName, _acceptLimit, _declineLimit); return OK; } /// @notice Remove policy rule /// Can be called only by contract owner /// /// @param _groupName group's name /// /// @return code function removePolicyRule( bytes4 _sig, address _contract, bytes32 _groupName ) onlyContractOwner external returns (uint) { require(_sig != bytes4(0)); require(_contract != 0x0); require(GroupsAccessManager(accessManager).isGroupExists(_groupName)); bytes32 _policyHash = keccak256(_sig, _contract); Policy storage _policy = policyId2policy[_policyHash]; uint _policyGroupNameIndex = _policy.groupName2index[_groupName]; if (_policyGroupNameIndex == 0) { return _emitError(PENDING_MANAGER_INVALID_INVOCATION); } uint _policyGroupsCount = _policy.groupsCount; if (_policyGroupNameIndex != _policyGroupsCount) { Requirements storage _requirements = _policy.participatedGroups[_policyGroupsCount]; _policy.participatedGroups[_policyGroupNameIndex] = _requirements; _policy.groupName2index[_requirements.groupName] = _policyGroupNameIndex; } _policy.totalAcceptedLimit = _policy.totalAcceptedLimit.sub(_policy.participatedGroups[_policyGroupsCount].acceptLimit); _policy.totalDeclinedLimit = _policy.totalDeclinedLimit.sub(_policy.participatedGroups[_policyGroupsCount].declineLimit); delete _policy.groupName2index[_groupName]; delete _policy.participatedGroups[_policyGroupsCount]; _policy.groupsCount = _policyGroupsCount.sub(1); PolicyRuleRemoved(_sig, _contract, _policyHash, _groupName); return OK; } /// @notice Add transaction /// /// @param _key transaction id /// /// @return code function addTx(bytes32 _key, bytes4 _sig, address _contract) external onlyAuthorized returns (uint) { require(_key != bytes32(0)); require(_sig != bytes4(0)); require(_contract != 0x0); bytes32 _policyHash = keccak256(_sig, _contract); require(isPolicyExist(_policyHash)); if (isTxExist(_key)) { return _emitError(PENDING_DUPLICATE_TX); } if (_policyHash == bytes32(0)) { return _emitError(PENDING_MANAGER_POLICY_NOT_FOUND); } uint _index = txCount.add(1); txCount = _index; index2txKey[_index] = _key; txKey2index[_key] = _index; Guard storage _guard = txKey2guard[_key]; _guard.basePolicyIndex = policyId2Index[_policyHash]; _guard.state = GuardState.InProcess; Policy storage _policy = policyId2policy[_policyHash]; uint _counter = _policy.securesCount.add(1); _policy.securesCount = _counter; _policy.index2txIndex[_counter] = _index; _policy.txIndex2index[_index] = _counter; ProtectionTxAdded(_key, _policyHash, block.number); return OK; } /// @notice Delete transaction /// @param _key transaction id /// @return code function deleteTx(bytes32 _key) external onlyContractOwner returns (uint) { require(_key != bytes32(0)); if (!isTxExist(_key)) { return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST); } uint _txsCount = txCount; uint _txIndex = txKey2index[_key]; if (_txIndex != _txsCount) { bytes32 _last = index2txKey[txCount]; index2txKey[_txIndex] = _last; txKey2index[_last] = _txIndex; } delete txKey2index[_key]; delete index2txKey[_txsCount]; txCount = _txsCount.sub(1); uint _basePolicyIndex = txKey2guard[_key].basePolicyIndex; Policy storage _policy = policyId2policy[index2PolicyId[_basePolicyIndex]]; uint _counter = _policy.securesCount; uint _policyTxIndex = _policy.txIndex2index[_txIndex]; if (_policyTxIndex != _counter) { uint _movedTxIndex = _policy.index2txIndex[_counter]; _policy.index2txIndex[_policyTxIndex] = _movedTxIndex; _policy.txIndex2index[_movedTxIndex] = _policyTxIndex; } delete _policy.index2txIndex[_counter]; delete _policy.txIndex2index[_txIndex]; _policy.securesCount = _counter.sub(1); TxDeleted(_key); return OK; } /// @notice Accept transaction /// Can be called only by registered user in GroupsAccessManager /// /// @param _key transaction id /// /// @return code function accept(bytes32 _key, bytes32 _votingGroupName) external returns (uint) { if (!isTxExist(_key)) { return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST); } if (!GroupsAccessManager(accessManager).isUserInGroup(_votingGroupName, msg.sender)) { return _emitError(PENDING_MANAGER_INVALID_INVOCATION); } Guard storage _guard = txKey2guard[_key]; if (_guard.state != GuardState.InProcess) { return _emitError(PENDING_MANAGER_INVALID_INVOCATION); } if (_guard.votes[msg.sender].groupName != bytes32(0) && _guard.votes[msg.sender].accepted) { return _emitError(PENDING_MANAGER_INVALID_INVOCATION); } Policy storage _policy = policyId2policy[index2PolicyId[_guard.basePolicyIndex]]; uint _policyGroupIndex = _policy.groupName2index[_votingGroupName]; uint _groupAcceptedVotesCount = _guard.acceptedCount[_votingGroupName]; if (_groupAcceptedVotesCount == _policy.participatedGroups[_policyGroupIndex].acceptLimit) { return _emitError(PENDING_MANAGER_INVALID_INVOCATION); } _guard.votes[msg.sender] = Vote(_votingGroupName, true); _guard.acceptedCount[_votingGroupName] = _groupAcceptedVotesCount + 1; uint _alreadyAcceptedCount = _guard.alreadyAccepted + 1; _guard.alreadyAccepted = _alreadyAcceptedCount; ProtectionTxAccepted(_key, msg.sender, _votingGroupName); if (_alreadyAcceptedCount == _policy.totalAcceptedLimit) { _guard.state = GuardState.Confirmed; ProtectionTxDone(_key); } return OK; } /// @notice Decline transaction /// Can be called only by registered user in GroupsAccessManager /// /// @param _key transaction id /// /// @return code function decline(bytes32 _key, bytes32 _votingGroupName) external returns (uint) { if (!isTxExist(_key)) { return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST); } if (!GroupsAccessManager(accessManager).isUserInGroup(_votingGroupName, msg.sender)) { return _emitError(PENDING_MANAGER_INVALID_INVOCATION); } Guard storage _guard = txKey2guard[_key]; if (_guard.state != GuardState.InProcess) { return _emitError(PENDING_MANAGER_INVALID_INVOCATION); } if (_guard.votes[msg.sender].groupName != bytes32(0) && !_guard.votes[msg.sender].accepted) { return _emitError(PENDING_MANAGER_INVALID_INVOCATION); } Policy storage _policy = policyId2policy[index2PolicyId[_guard.basePolicyIndex]]; uint _policyGroupIndex = _policy.groupName2index[_votingGroupName]; uint _groupDeclinedVotesCount = _guard.declinedCount[_votingGroupName]; if (_groupDeclinedVotesCount == _policy.participatedGroups[_policyGroupIndex].declineLimit) { return _emitError(PENDING_MANAGER_INVALID_INVOCATION); } _guard.votes[msg.sender] = Vote(_votingGroupName, false); _guard.declinedCount[_votingGroupName] = _groupDeclinedVotesCount + 1; uint _alreadyDeclinedCount = _guard.alreadyDeclined + 1; _guard.alreadyDeclined = _alreadyDeclinedCount; ProtectionTxDeclined(_key, msg.sender, _votingGroupName); if (_alreadyDeclinedCount == _policy.totalDeclinedLimit) { _guard.state = GuardState.Decline; ProtectionTxCancelled(_key); } return OK; } /// @notice Revoke user votes for transaction /// Can be called only by contract owner /// /// @param _key transaction id /// @param _user target user address /// /// @return code function forceRejectVotes(bytes32 _key, address _user) external onlyContractOwner returns (uint) { return _revoke(_key, _user); } /// @notice Revoke vote for transaction /// Can be called only by authorized user /// @param _key transaction id /// @return code function revoke(bytes32 _key) external returns (uint) { return _revoke(_key, msg.sender); } /// @notice Check transaction status /// @param _key transaction id /// @return code function hasConfirmedRecord(bytes32 _key) public view returns (uint) { require(_key != bytes32(0)); if (!isTxExist(_key)) { return NO_RECORDS_WERE_FOUND; } Guard storage _guard = txKey2guard[_key]; return _guard.state == GuardState.InProcess ? PENDING_MANAGER_IN_PROCESS : _guard.state == GuardState.Confirmed ? OK : PENDING_MANAGER_REJECTED; } /// @notice Check policy details /// /// @return _groupNames group names included in policies /// @return _acceptLimits accept limit for group /// @return _declineLimits decline limit for group function getPolicyDetails(bytes4 _sig, address _contract) public view returns ( bytes32[] _groupNames, uint[] _acceptLimits, uint[] _declineLimits, uint _totalAcceptedLimit, uint _totalDeclinedLimit ) { require(_sig != bytes4(0)); require(_contract != 0x0); bytes32 _policyHash = keccak256(_sig, _contract); uint _policyIdx = policyId2Index[_policyHash]; if (_policyIdx == 0) { return; } Policy storage _policy = policyId2policy[_policyHash]; uint _policyGroupsCount = _policy.groupsCount; _groupNames = new bytes32[](_policyGroupsCount); _acceptLimits = new uint[](_policyGroupsCount); _declineLimits = new uint[](_policyGroupsCount); for (uint _idx = 0; _idx < _policyGroupsCount; ++_idx) { Requirements storage _requirements = _policy.participatedGroups[_idx + 1]; _groupNames[_idx] = _requirements.groupName; _acceptLimits[_idx] = _requirements.acceptLimit; _declineLimits[_idx] = _requirements.declineLimit; } (_totalAcceptedLimit, _totalDeclinedLimit) = (_policy.totalAcceptedLimit, _policy.totalDeclinedLimit); } /// @notice Check policy include target group /// @param _policyHash policy hash (sig, contract address) /// @param _groupName group id /// @return bool function isGroupInPolicy(bytes32 _policyHash, bytes32 _groupName) public view returns (bool) { Policy storage _policy = policyId2policy[_policyHash]; return _policy.groupName2index[_groupName] != 0; } /// @notice Check is policy exist /// @param _policyHash policy hash (sig, contract address) /// @return bool function isPolicyExist(bytes32 _policyHash) public view returns (bool) { return policyId2Index[_policyHash] != 0; } /// @notice Check is transaction exist /// @param _key transaction id /// @return bool function isTxExist(bytes32 _key) public view returns (bool){ return txKey2index[_key] != 0; } function _updateTxState(Policy storage _policy, Guard storage _guard, uint confirmedAmount, uint declineAmount) private { if (declineAmount != 0 && _guard.state != GuardState.Decline) { _guard.state = GuardState.Decline; } else if (confirmedAmount >= _policy.groupsCount && _guard.state != GuardState.Confirmed) { _guard.state = GuardState.Confirmed; } else if (_guard.state != GuardState.InProcess) { _guard.state = GuardState.InProcess; } } function _revoke(bytes32 _key, address _user) private returns (uint) { require(_key != bytes32(0)); require(_user != 0x0); if (!isTxExist(_key)) { return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST); } Guard storage _guard = txKey2guard[_key]; if (_guard.state != GuardState.InProcess) { return _emitError(PENDING_MANAGER_INVALID_INVOCATION); } bytes32 _votedGroupName = _guard.votes[_user].groupName; if (_votedGroupName == bytes32(0)) { return _emitError(PENDING_MANAGER_HASNT_VOTED); } bool isAcceptedVote = _guard.votes[_user].accepted; if (isAcceptedVote) { _guard.acceptedCount[_votedGroupName] = _guard.acceptedCount[_votedGroupName].sub(1); _guard.alreadyAccepted = _guard.alreadyAccepted.sub(1); } else { _guard.declinedCount[_votedGroupName] = _guard.declinedCount[_votedGroupName].sub(1); _guard.alreadyDeclined = _guard.alreadyDeclined.sub(1); } delete _guard.votes[_user]; ProtectionTxVoteRevoked(_key, _user, _votedGroupName); return OK; } } /// @title MultiSigAdapter /// /// Abstract implementation /// This contract serves as transaction signer contract MultiSigAdapter is Object { uint constant MULTISIG_ADDED = 3; uint constant NO_RECORDS_WERE_FOUND = 4; modifier isAuthorized { if (msg.sender == contractOwner || msg.sender == getPendingManager()) { _; } } /// @notice Get pending address /// @dev abstract. Needs child implementation /// /// @return pending address function getPendingManager() public view returns (address); /// @notice Sign current transaction and add it to transaction pending queue /// /// @return code function _multisig(bytes32 _args, uint _block) internal returns (uint _code) { bytes32 _txHash = _getKey(_args, _block); address _manager = getPendingManager(); _code = PendingManager(_manager).hasConfirmedRecord(_txHash); if (_code != NO_RECORDS_WERE_FOUND) { return _code; } if (OK != PendingManager(_manager).addTx(_txHash, msg.sig, address(this))) { revert(); } return MULTISIG_ADDED; } function _isTxExistWithArgs(bytes32 _args, uint _block) internal view returns (bool) { bytes32 _txHash = _getKey(_args, _block); address _manager = getPendingManager(); return PendingManager(_manager).isTxExist(_txHash); } function _getKey(bytes32 _args, uint _block) private view returns (bytes32 _txHash) { _block = _block != 0 ? _block : block.number; _txHash = keccak256(msg.sig, _args, _block); } } /// @title ServiceController /// /// Base implementation /// Serves for managing service instances contract ServiceController is MultiSigAdapter { uint constant SERVICE_CONTROLLER = 350000; uint constant SERVICE_CONTROLLER_EMISSION_EXIST = SERVICE_CONTROLLER + 1; uint constant SERVICE_CONTROLLER_BURNING_MAN_EXIST = SERVICE_CONTROLLER + 2; uint constant SERVICE_CONTROLLER_ALREADY_INITIALIZED = SERVICE_CONTROLLER + 3; uint constant SERVICE_CONTROLLER_SERVICE_EXIST = SERVICE_CONTROLLER + 4; address public profiterole; address public treasury; address public pendingManager; address public proxy; mapping(address => bool) public sideServices; mapping(address => bool) emissionProviders; mapping(address => bool) burningMans; /// @notice Default ServiceController's constructor /// /// @param _pendingManager pending manager address /// @param _proxy ERC20 proxy address /// @param _profiterole profiterole address /// @param _treasury treasury address function ServiceController(address _pendingManager, address _proxy, address _profiterole, address _treasury) public { require(_pendingManager != 0x0); require(_proxy != 0x0); require(_profiterole != 0x0); require(_treasury != 0x0); pendingManager = _pendingManager; proxy = _proxy; profiterole = _profiterole; treasury = _treasury; } /// @notice Return pending manager address /// /// @return code function getPendingManager() public view returns (address) { return pendingManager; } /// @notice Add emission provider /// /// @param _provider emission provider address /// /// @return code function addEmissionProvider(address _provider, uint _block) public returns (uint _code) { if (emissionProviders[_provider]) { return SERVICE_CONTROLLER_EMISSION_EXIST; } _code = _multisig(keccak256(_provider), _block); if (OK != _code) { return _code; } emissionProviders[_provider] = true; return OK; } /// @notice Remove emission provider /// /// @param _provider emission provider address /// /// @return code function removeEmissionProvider(address _provider, uint _block) public returns (uint _code) { _code = _multisig(keccak256(_provider), _block); if (OK != _code) { return _code; } delete emissionProviders[_provider]; return OK; } /// @notice Add burning man /// /// @param _burningMan burning man address /// /// @return code function addBurningMan(address _burningMan, uint _block) public returns (uint _code) { if (burningMans[_burningMan]) { return SERVICE_CONTROLLER_BURNING_MAN_EXIST; } _code = _multisig(keccak256(_burningMan), _block); if (OK != _code) { return _code; } burningMans[_burningMan] = true; return OK; } /// @notice Remove burning man /// /// @param _burningMan burning man address /// /// @return code function removeBurningMan(address _burningMan, uint _block) public returns (uint _code) { _code = _multisig(keccak256(_burningMan), _block); if (OK != _code) { return _code; } delete burningMans[_burningMan]; return OK; } /// @notice Update a profiterole address /// /// @param _profiterole profiterole address /// /// @return result code of an operation function updateProfiterole(address _profiterole, uint _block) public returns (uint _code) { _code = _multisig(keccak256(_profiterole), _block); if (OK != _code) { return _code; } profiterole = _profiterole; return OK; } /// @notice Update a treasury address /// /// @param _treasury treasury address /// /// @return result code of an operation function updateTreasury(address _treasury, uint _block) public returns (uint _code) { _code = _multisig(keccak256(_treasury), _block); if (OK != _code) { return _code; } treasury = _treasury; return OK; } /// @notice Update pending manager address /// /// @param _pendingManager pending manager address /// /// @return result code of an operation function updatePendingManager(address _pendingManager, uint _block) public returns (uint _code) { _code = _multisig(keccak256(_pendingManager), _block); if (OK != _code) { return _code; } pendingManager = _pendingManager; return OK; } function addSideService(address _service, uint _block) public returns (uint _code) { if (sideServices[_service]) { return SERVICE_CONTROLLER_SERVICE_EXIST; } _code = _multisig(keccak256(_service), _block); if (OK != _code) { return _code; } sideServices[_service] = true; return OK; } function removeSideService(address _service, uint _block) public returns (uint _code) { _code = _multisig(keccak256(_service), _block); if (OK != _code) { return _code; } delete sideServices[_service]; return OK; } /// @notice Check target address is service /// /// @param _address target address /// /// @return `true` when an address is a service, `false` otherwise function isService(address _address) public view returns (bool check) { return _address == profiterole || _address == treasury || _address == proxy || _address == pendingManager || emissionProviders[_address] || burningMans[_address] || sideServices[_address]; } } /// @title Provides possibility manage holders? country limits and limits for holders. contract DataController is OracleMethodAdapter, DataControllerEmitter { /* CONSTANTS */ uint constant DATA_CONTROLLER = 109000; uint constant DATA_CONTROLLER_ERROR = DATA_CONTROLLER + 1; uint constant DATA_CONTROLLER_CURRENT_WRONG_LIMIT = DATA_CONTROLLER + 2; uint constant DATA_CONTROLLER_WRONG_ALLOWANCE = DATA_CONTROLLER + 3; uint constant DATA_CONTROLLER_COUNTRY_CODE_ALREADY_EXISTS = DATA_CONTROLLER + 4; uint constant MAX_TOKEN_HOLDER_NUMBER = 2 ** 256 - 1; using SafeMath for uint; /* STRUCTS */ /// @title HoldersData couldn't be public because of internal structures, so needed to provide getters for different parts of _holderData struct HoldersData { uint countryCode; uint sendLimPerDay; uint sendLimPerMonth; bool operational; bytes text; uint holderAddressCount; mapping(uint => address) index2Address; mapping(address => uint) address2Index; } struct CountryLimits { uint countryCode; uint maxTokenHolderNumber; uint currentTokenHolderNumber; } /* FIELDS */ address public withdrawal; address assetAddress; address public serviceController; mapping(address => uint) public allowance; // Iterable mapping pattern is used for holders. /// @dev This is an access address mapping. Many addresses may have access to a single holder. uint public holdersCount; mapping(uint => HoldersData) holders; mapping(address => bytes32) holderAddress2Id; mapping(bytes32 => uint) public holderIndex; // This is an access address mapping. Many addresses may have access to a single holder. uint public countriesCount; mapping(uint => CountryLimits) countryLimitsList; mapping(uint => uint) countryIndex; /* MODIFIERS */ modifier onlyWithdrawal { if (msg.sender != withdrawal) { revert(); } _; } modifier onlyAsset { if (msg.sender == assetAddress) { _; } } modifier onlyContractOwner { if (msg.sender == contractOwner) { _; } } /// @notice Constructor for _holderData controller. /// @param _serviceController service controller function DataController(address _serviceController, address _asset) public { require(_serviceController != 0x0); require(_asset != 0x0); serviceController = _serviceController; assetAddress = _asset; } function() payable public { revert(); } function setWithdraw(address _withdrawal) onlyContractOwner external returns (uint) { require(_withdrawal != 0x0); withdrawal = _withdrawal; return OK; } function getPendingManager() public view returns (address) { return ServiceController(serviceController).getPendingManager(); } function getHolderInfo(bytes32 _externalHolderId) public view returns ( uint _countryCode, uint _limPerDay, uint _limPerMonth, bool _operational, bytes _text ) { HoldersData storage _data = holders[holderIndex[_externalHolderId]]; return (_data.countryCode, _data.sendLimPerDay, _data.sendLimPerMonth, _data.operational, _data.text); } function getHolderAddresses(bytes32 _externalHolderId) public view returns (address[] _addresses) { HoldersData storage _holderData = holders[holderIndex[_externalHolderId]]; uint _addressesCount = _holderData.holderAddressCount; _addresses = new address[](_addressesCount); for (uint _holderAddressIdx = 0; _holderAddressIdx < _addressesCount; ++_holderAddressIdx) { _addresses[_holderAddressIdx] = _holderData.index2Address[_holderAddressIdx + 1]; } } function getHolderCountryCode(bytes32 _externalHolderId) public view returns (uint) { return holders[holderIndex[_externalHolderId]].countryCode; } function getHolderExternalIdByAddress(address _address) public view returns (bytes32) { return holderAddress2Id[_address]; } /// @notice Checks user is holder. /// @param _address checking address. /// @return `true` if _address is registered holder, `false` otherwise. function isRegisteredAddress(address _address) public view returns (bool) { return holderIndex[holderAddress2Id[_address]] != 0; } function isHolderOwnAddress(bytes32 _externalHolderId, address _address) public view returns (bool) { uint _holderIndex = holderIndex[_externalHolderId]; if (_holderIndex == 0) { return false; } return holders[_holderIndex].address2Index[_address] != 0; } function getCountryInfo(uint _countryCode) public view returns (uint _maxHolderNumber, uint _currentHolderCount) { CountryLimits storage _data = countryLimitsList[countryIndex[_countryCode]]; return (_data.maxTokenHolderNumber, _data.currentTokenHolderNumber); } function getCountryLimit(uint _countryCode) public view returns (uint limit) { uint _index = countryIndex[_countryCode]; require(_index != 0); return countryLimitsList[_index].maxTokenHolderNumber; } function addCountryCode(uint _countryCode) onlyContractOwner public returns (uint) { var (,_created) = _createCountryId(_countryCode); if (!_created) { return _emitError(DATA_CONTROLLER_COUNTRY_CODE_ALREADY_EXISTS); } return OK; } /// @notice Returns holder id for the specified address, creates it if needed. /// @param _externalHolderId holder address. /// @param _countryCode country code. /// @return error code. function registerHolder(bytes32 _externalHolderId, address _holderAddress, uint _countryCode) onlyOracleOrOwner external returns (uint) { require(_holderAddress != 0x0); require(holderIndex[_externalHolderId] == 0); uint _holderIndex = holderIndex[holderAddress2Id[_holderAddress]]; require(_holderIndex == 0); _createCountryId(_countryCode); _holderIndex = holdersCount.add(1); holdersCount = _holderIndex; HoldersData storage _holderData = holders[_holderIndex]; _holderData.countryCode = _countryCode; _holderData.operational = true; _holderData.sendLimPerDay = MAX_TOKEN_HOLDER_NUMBER; _holderData.sendLimPerMonth = MAX_TOKEN_HOLDER_NUMBER; uint _firstAddressIndex = 1; _holderData.holderAddressCount = _firstAddressIndex; _holderData.address2Index[_holderAddress] = _firstAddressIndex; _holderData.index2Address[_firstAddressIndex] = _holderAddress; holderIndex[_externalHolderId] = _holderIndex; holderAddress2Id[_holderAddress] = _externalHolderId; _emitHolderRegistered(_externalHolderId, _holderIndex, _countryCode); return OK; } /// @notice Adds new address equivalent to holder. /// @param _externalHolderId external holder identifier. /// @param _newAddress adding address. /// @return error code. function addHolderAddress(bytes32 _externalHolderId, address _newAddress) onlyOracleOrOwner external returns (uint) { uint _holderIndex = holderIndex[_externalHolderId]; require(_holderIndex != 0); uint _newAddressId = holderIndex[holderAddress2Id[_newAddress]]; require(_newAddressId == 0); HoldersData storage _holderData = holders[_holderIndex]; if (_holderData.address2Index[_newAddress] == 0) { _holderData.holderAddressCount = _holderData.holderAddressCount.add(1); _holderData.address2Index[_newAddress] = _holderData.holderAddressCount; _holderData.index2Address[_holderData.holderAddressCount] = _newAddress; } holderAddress2Id[_newAddress] = _externalHolderId; _emitHolderAddressAdded(_externalHolderId, _newAddress, _holderIndex); return OK; } /// @notice Remove an address owned by a holder. /// @param _externalHolderId external holder identifier. /// @param _address removing address. /// @return error code. function removeHolderAddress(bytes32 _externalHolderId, address _address) onlyOracleOrOwner external returns (uint) { uint _holderIndex = holderIndex[_externalHolderId]; require(_holderIndex != 0); HoldersData storage _holderData = holders[_holderIndex]; uint _tempIndex = _holderData.address2Index[_address]; require(_tempIndex != 0); address _lastAddress = _holderData.index2Address[_holderData.holderAddressCount]; _holderData.address2Index[_lastAddress] = _tempIndex; _holderData.index2Address[_tempIndex] = _lastAddress; delete _holderData.address2Index[_address]; _holderData.holderAddressCount = _holderData.holderAddressCount.sub(1); delete holderAddress2Id[_address]; _emitHolderAddressRemoved(_externalHolderId, _address, _holderIndex); return OK; } /// @notice Change operational status for holder. /// Can be accessed by contract owner or oracle only. /// /// @param _externalHolderId external holder identifier. /// @param _operational operational status. /// /// @return result code. function changeOperational(bytes32 _externalHolderId, bool _operational) onlyOracleOrOwner external returns (uint) { uint _holderIndex = holderIndex[_externalHolderId]; require(_holderIndex != 0); holders[_holderIndex].operational = _operational; _emitHolderOperationalChanged(_externalHolderId, _operational); return OK; } /// @notice Changes text for holder. /// Can be accessed by contract owner or oracle only. /// /// @param _externalHolderId external holder identifier. /// @param _text changing text. /// /// @return result code. function updateTextForHolder(bytes32 _externalHolderId, bytes _text) onlyOracleOrOwner external returns (uint) { uint _holderIndex = holderIndex[_externalHolderId]; require(_holderIndex != 0); holders[_holderIndex].text = _text; return OK; } /// @notice Updates limit per day for holder. /// /// Can be accessed by contract owner only. /// /// @param _externalHolderId external holder identifier. /// @param _limit limit value. /// /// @return result code. function updateLimitPerDay(bytes32 _externalHolderId, uint _limit) onlyOracleOrOwner external returns (uint) { uint _holderIndex = holderIndex[_externalHolderId]; require(_holderIndex != 0); uint _currentLimit = holders[_holderIndex].sendLimPerDay; holders[_holderIndex].sendLimPerDay = _limit; _emitDayLimitChanged(_externalHolderId, _currentLimit, _limit); return OK; } /// @notice Updates limit per month for holder. /// Can be accessed by contract owner or oracle only. /// /// @param _externalHolderId external holder identifier. /// @param _limit limit value. /// /// @return result code. function updateLimitPerMonth(bytes32 _externalHolderId, uint _limit) onlyOracleOrOwner external returns (uint) { uint _holderIndex = holderIndex[_externalHolderId]; require(_holderIndex != 0); uint _currentLimit = holders[_holderIndex].sendLimPerDay; holders[_holderIndex].sendLimPerMonth = _limit; _emitMonthLimitChanged(_externalHolderId, _currentLimit, _limit); return OK; } /// @notice Change country limits. /// Can be accessed by contract owner or oracle only. /// /// @param _countryCode country code. /// @param _limit limit value. /// /// @return result code. function changeCountryLimit(uint _countryCode, uint _limit) onlyOracleOrOwner external returns (uint) { uint _countryIndex = countryIndex[_countryCode]; require(_countryIndex != 0); uint _currentTokenHolderNumber = countryLimitsList[_countryIndex].currentTokenHolderNumber; if (_currentTokenHolderNumber > _limit) { return DATA_CONTROLLER_CURRENT_WRONG_LIMIT; } countryLimitsList[_countryIndex].maxTokenHolderNumber = _limit; _emitCountryCodeChanged(_countryIndex, _countryCode, _limit); return OK; } function withdrawFrom(address _holderAddress, uint _value) public onlyAsset returns (uint) { bytes32 _externalHolderId = holderAddress2Id[_holderAddress]; HoldersData storage _holderData = holders[holderIndex[_externalHolderId]]; _holderData.sendLimPerDay = _holderData.sendLimPerDay.sub(_value); _holderData.sendLimPerMonth = _holderData.sendLimPerMonth.sub(_value); return OK; } function depositTo(address _holderAddress, uint _value) public onlyAsset returns (uint) { bytes32 _externalHolderId = holderAddress2Id[_holderAddress]; HoldersData storage _holderData = holders[holderIndex[_externalHolderId]]; _holderData.sendLimPerDay = _holderData.sendLimPerDay.add(_value); _holderData.sendLimPerMonth = _holderData.sendLimPerMonth.add(_value); return OK; } function updateCountryHoldersCount(uint _countryCode, uint _updatedHolderCount) public onlyAsset returns (uint) { CountryLimits storage _data = countryLimitsList[countryIndex[_countryCode]]; assert(_data.maxTokenHolderNumber >= _updatedHolderCount); _data.currentTokenHolderNumber = _updatedHolderCount; return OK; } function changeAllowance(address _from, uint _value) public onlyWithdrawal returns (uint) { ServiceController _serviceController = ServiceController(serviceController); ATxAssetProxy token = ATxAssetProxy(_serviceController.proxy()); if (token.balanceOf(_from) < _value) { return DATA_CONTROLLER_WRONG_ALLOWANCE; } allowance[_from] = _value; return OK; } function _createCountryId(uint _countryCode) internal returns (uint, bool _created) { uint countryId = countryIndex[_countryCode]; if (countryId == 0) { uint _countriesCount = countriesCount; countryId = _countriesCount.add(1); countriesCount = countryId; CountryLimits storage limits = countryLimitsList[countryId]; limits.countryCode = _countryCode; limits.maxTokenHolderNumber = MAX_TOKEN_HOLDER_NUMBER; countryIndex[_countryCode] = countryId; _emitCountryCodeAdded(countryIndex[_countryCode], _countryCode, MAX_TOKEN_HOLDER_NUMBER); _created = true; } return (countryId, _created); } }
Propose next asset implementation contract address. Can only be called by current asset owner. Note: freeze-time should not be applied for the initial setup. _newVersion asset implementation contract address. return success./ Should not already be in the upgrading process. New version address should be other than 0x0. Don't apply freeze-time for the initial setup.
function proposeUpgrade(address _newVersion) public onlyAssetOwner returns (bool) { if (pendingVersion != 0x0) { return false; } if (_newVersion == 0x0) { return false; } if (latestVersion == 0x0) { latestVersion = _newVersion; return true; } pendingVersion = _newVersion; pendingVersionTimestamp = now; UpgradeProposal(_newVersion); return true; }
259,158
pragma solidity 0.6.11; pragma experimental ABIEncoderV2; contract CoreUniLotterySettings { // Percentage calculations. // As Solidity doesn't have floats, we have to use integers for // percentage arithmetics. // We set 1 percent to be equal to 1,000,000 - thus, we // simulate 6 decimal points when computing percentages. uint32 public constant PERCENT = 10 ** 6; uint32 constant BASIS_POINT = PERCENT / 100; uint32 constant _100PERCENT = 100 * PERCENT; /** The UniLottery Owner's address. * * In the current version, The Owner has rights to: * - Take up to 10% profit from every lottery. * - Pool liquidity into the pool and remove it. * - Start lotteries in auto or manual mode. */ // Public Testnets: 0xb13CB9BECcB034392F4c9Db44E23C3Fb5fd5dc63 // MainNet: 0x1Ae51bec001a4fA4E3b06A5AF2e0df33A79c01e2 address payable public constant OWNER_ADDRESS = address( uint160( 0x1Ae51bec001a4fA4E3b06A5AF2e0df33A79c01e2 ) ); // Maximum lottery fee the owner can imburse on transfers. uint32 constant MAX_OWNER_LOTTERY_FEE = 1 * PERCENT; // Minimum amout of profit percentage that must be distributed // to lottery winners. uint32 constant MIN_WINNER_PROFIT_SHARE = 40 * PERCENT; // Min & max profits the owner can take from lottery net profit. uint32 constant MIN_OWNER_PROFITS = 3 * PERCENT; uint32 constant MAX_OWNER_PROFITS = 10 * PERCENT; // Min & max amount of lottery profits that the pool must get. uint32 constant MIN_POOL_PROFITS = 10 * PERCENT; uint32 constant MAX_POOL_PROFITS = 60 * PERCENT; // Maximum lifetime of a lottery - 1 month (4 weeks). uint32 constant MAX_LOTTERY_LIFETIME = 4 weeks; // Callback gas requirements for a lottery's ending callback, // and for the Pool's Scheduled Callback. // Must be determined empirically. uint32 constant LOTTERY_RAND_CALLBACK_GAS = 200000; uint32 constant AUTO_MODE_SCHEDULED_CALLBACK_GAS = 3800431; } interface IUniswapRouter { // Get Factory and WETH addresses. function factory() external pure returns (address); function WETH() external pure returns (address); // Create/add to a liquidity pair using ETH. function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns ( uint amountToken, uint amountETH, uint liquidity ); // Remove liquidity pair. function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns ( uint amountETH ); // Get trade output amount, given an input. function getAmountsOut( uint amountIn, address[] memory path ) external view returns ( uint[] memory amounts ); // Get trade input amount, given an output. function getAmountsIn( uint amountOut, address[] memory path ) external view returns ( uint[] memory amounts ); } interface IUniswapFactory { function getPair( address tokenA, address tokenB ) external view returns ( address pair ); } contract UniLotteryConfigGenerator { function getConfig() external pure returns( Lottery.LotteryConfig memory cfg ) { cfg.initialFunds = 10 ether; } } contract UniLotteryLotteryFactory { // Uniswap Router address on this network - passed to Lotteries on // construction. //ddress payable immutable uniRouterAddress; // Delegate Contract for the Lottery, containing all logic code // needed for deploying LotteryStubs. // Deployed only once, on construction. address payable immutable delegateContract; // The Pool Address. address payable poolAddress; // The Lottery Storage Factory address, that the Lottery contracts use. UniLotteryStorageFactory lotteryStorageFactory; // Pool-Only modifier. modifier poolOnly { require( msg.sender == poolAddress ); _; } // Constructor. // Set the Uniswap Address, and deploy&lock the Delegate Code contract. // constructor( /*address payable _uniRouter*/ ) public { //uniRouterAddress = _uniRouter; delegateContract = address( uint160( address( new Lottery() ) ) ); } // Initialization function. // Set the poolAddress as msg.sender, and lock it. // Also, set the Lottery Storage Factory contract instance address. function initialize( address _storageFactoryAddress ) external { require( poolAddress == address( 0 ) ); // Set the Pool's Address. // Lock it. No more calls to this function will be executed. poolAddress = msg.sender; // Set the Storage Factory, and initialize it! lotteryStorageFactory = UniLotteryStorageFactory( _storageFactoryAddress ); lotteryStorageFactory.initialize(); } /** * Deploy a new Lottery Stub from the specified config. * @param config - Lottery Config to be used (passed by the pool). * @return newLottery - the newly deployed lottery stub. */ function createNewLottery( Lottery.LotteryConfig memory config, address randomnessProvider ) public poolOnly returns( address payable newLottery ) { // Create new Lottery Storage, using storage factory. // Populate the stub, by calling the "construct" function. LotteryStub stub = new LotteryStub( delegateContract ); Lottery( address( stub ) ).construct( config, poolAddress, randomnessProvider, lotteryStorageFactory.createNewStorage() ); return address( stub ); } } contract LotteryStub { // ============ ERC20 token contract's storage ============ // // ------- Slot ------- // // Balances of token holders. mapping (address => uint256) private _balances; // ------- Slot ------- // // Allowances of spenders for a specific token owner. mapping (address => mapping (address => uint256)) private _allowances; // ------- Slot ------- // // Total supply of the token. uint256 private _totalSupply; // ============== Lottery contract's storage ============== // // ------- Initial Slots ------- // // The config which is passed to constructor. Lottery.LotteryConfig internal cfg; // ------- Slot ------- // // The Lottery Storage contract, which stores all holder data, // such as scores, referral tree data, etc. LotteryStorage /*public*/ lotStorage; // ------- Slot ------- // // Pool address. Set on constructor from msg.sender. address payable /*public*/ poolAddress; // ------- Slot ------- // // Randomness Provider address. address /*public*/ randomnessProvider; // ------- Slot ------- // // Exchange address. In Uniswap mode, it's the Uniswap liquidity // pair's address, where trades execute. address /*public*/ exchangeAddress; // Start date. uint32 /*public*/ startDate; // Completion (Mining Phase End) date. uint32 /*public*/ completionDate; // The date when Randomness Provider was called, requesting a // random seed for the lottery finish. // Also, when this variable becomes Non-Zero, it indicates that we're // on Ending Stage Part One: waiting for the random seed. uint32 finish_timeRandomSeedRequested; // ------- Slot ------- // // WETH address. Set by calling Router's getter, on constructor. address WETHaddress; // Is the WETH first or second token in our Uniswap Pair? bool uniswap_ethFirst; // If we are, or were before, on finishing stage, this is the // probability of lottery going to Ending Stage on this transaction. uint32 finishProbablity; // Re-Entrancy Lock (Mutex). // We protect for reentrancy in the Fund Transfer functions. bool reEntrancyMutexLocked; // On which stage we are currently. uint8 /*public*/ lotteryStage; // Indicator for whether the lottery fund gains have passed a // minimum fund gain requirement. // After that time point (when this bool is set), the token sells // which could drop the fund value below the requirement, would // be denied. bool fundGainRequirementReached; // The current step of the Mining Stage. uint16 miningStep; // If we're currently on Special Transfer Mode - that is, we allow // direct transfers between parties even in NON-ACTIVE state. bool specialTransferModeEnabled; // ------- Slot ------- // // Per-Transaction Pseudo-Random hash value (transferHashValue). // This value is computed on every token transfer, by keccak'ing // the last (current) transferHashValue, msg.sender, now, and // transaction count. // // This is used on Finishing Stage, as a pseudo-random number, // which is used to check if we should end the lottery (move to // Ending Stage). uint256 transferHashValue; // ------- Slot ------- // // On lottery end, get & store the lottery total ETH return // (including initial funds), and profit amount. uint128 /*public*/ ending_totalReturn; uint128 /*public*/ ending_profitAmount; // ------- Slot ------- // // The mapping that contains TRUE for addresses that already claimed // their lottery winner prizes. // Used only in COMPLETION, on claimWinnerPrize(), to check if // msg.sender has already claimed his prize. mapping( address => bool ) /*public*/ prizeClaimersAddresses; // =================== OUR CONTRACT'S OWN STORAGE =================== // // The address of the delegate contract, containing actual logic. address payable immutable public __delegateContract; // =================== Functions =================== // // Constructor. // Just set the delegate's address. constructor( address payable _delegateAddr ) public { __delegateContract = _delegateAddr; } // Fallback payable function, which delegates any call to our // contract, into the delegate contract. fallback() external payable { // DelegateCall the delegate code contract. ( bool success, bytes memory data ) = __delegateContract.delegatecall( msg.data ); // Use inline assembly to be able to return value from the fallback. // (by default, returning a value from fallback is not possible, // but it's still possible to manually copy data to the // return buffer. assembly { // delegatecall returns 0 (false) on error. // Add 32 bytes to "data" pointer, because first slot (32 bytes) // contains the length, and we use return value's length // from returndatasize() opcode. switch success case 0 { revert( add( data, 32 ), returndatasize() ) } default { return( add( data, 32 ), returndatasize() ) } } } // Receive ether function. receive() external payable { } } contract LotteryStorageStub { // =============== LotteryStorage contract's storage ================ // // --------- Slot --------- // // The Lottery address that this storage belongs to. // Is set by the "initialize()", called by corresponding Lottery. address lottery; // The Random Seed, that was passed to us from Randomness Provider, // or generated alternatively. uint64 randomSeed; // The actual number of winners that there will be. Set after // completing the Winner Selection Algorithm. uint16 numberOfWinners; // Bool indicating if Winner Selection Algorithm has been executed. bool algorithmCompleted; // --------- Slot --------- // // Winner Algorithm config. Specified in Initialization(). LotteryStorage.WinnerAlgorithmConfig algConfig; // --------- Slot --------- // // The Min-Max holder score storage. LotteryStorage.MinMaxHolderScores minMaxScores; // --------- Slot --------- // // Array of holders. address[] /*public*/ holders; // --------- Slot --------- // // Holder array indexes mapping, for O(1) array element access. mapping( address => uint ) holderIndexes; // --------- Slot --------- // // Mapping of holder data. mapping( address => LotteryStorage.HolderData ) /*public*/ holderData; // --------- Slot --------- // // Mapping of referral IDs to addresses of holders who generated // those IDs. mapping( uint256 => address ) referrers; // --------- Slot --------- // // The array of final-sorted winners (set after Winner Selection // Algorithm completes), that contains the winners' indexes // in the "holders" array, to save space. // // Notice that by using uint16, we can fit 16 items into one slot! // So, if there are 160 winners, we only take up 10 slots, so // only 20,000 * 10 = 200,000 gas gets consumed! // LotteryStorage.WinnerIndexStruct[] sortedWinnerIndexes; // =================== OUR CONTRACT'S OWN STORAGE =================== // // The address of the delegate contract, containing actual logic. address immutable public __delegateContract; // =================== Functions =================== // // Constructor. // Just set the delegate's address. constructor( address _delegateAddr ) public { __delegateContract = _delegateAddr; } // Fallback function, which delegates any call to our // contract, into the delegate contract. fallback() external { // DelegateCall the delegate code contract. ( bool success, bytes memory data ) = __delegateContract.delegatecall( msg.data ); // Use inline assembly to be able to return value from the fallback. // (by default, returning a value from fallback is not possible, // but it's still possible to manually copy data to the // return buffer. assembly { // delegatecall returns 0 (false) on error. // Add 32 bytes to "data" pointer, because first slot (32 bytes) // contains the length, and we use return value's length // from returndatasize() opcode. switch success case 0 { revert( add( data, 32 ), returndatasize() ) } default { return( add( data, 32 ), returndatasize() ) } } } } interface IUniLotteryPool { function lotteryFinish( uint totalReturn, uint profitAmount ) external payable; } interface IRandomnessProvider { function requestRandomSeedForLotteryFinish() external; } contract LotteryStorage is CoreUniLotterySettings { // ==================== Structs & Constants ==================== // // Struct of holder data & scores. struct HolderData { // --------- Slot --------- // // If this holder has generated his own referral ID, this is // that ID. If he hasn't generated an ID, this is zero. uint256 referralID; // --------- Slot --------- // // If this holder provided a valid referral ID, this is the // address of a referrer - the user who generated the said // referral ID. address referrer; // --------- Slot --------- // // The intermediate score factor variables. // Ether contributed: ( buys - sells ). Can be negative. int80 etherContributed; // Time x ether factor: (relativeTxTime * etherAmount). int80 timeFactors; // Token balance score factor of this holder - we use int, // for easier computation of player scores in our algorithms. int80 tokenBalance; // Number of all child referrees, including multi-level ones. // Updated by traversing child->parent way, incrementing // every node's counter by one. // Used in Winner Selection Algorithm, to determine how much // to divide the accumulated referree scores by. uint16 referreeCount; // --------- Slot --------- // // Accumulated referree score factors - ether contributed by // all referrees, time factors, and token balances of all // referrees. // Can be negative! int80 referree_etherContributed; int80 referree_timeFactors; int80 referree_tokenBalance; // Bonus score points, which can be given in certain events, // such as when player registers a valid referral ID. int16 bonusScore; } // Final Score (end lottery score * randomValue) structure. struct FinalScore { address addr; // 20 bytes \ uint16 holderIndex; // 2 bytes | = 30 bytes => 1 slot. uint64 score; // 8 bytes / } // Winner Indexes structure - used to efficiently store Winner // indexes in holder's array, after completing the Winner Selection // Algorithm. // To save Space, we store these in a struct, with uint16 array // with 16 items - so this struct takes up excactly 1 slot. struct WinnerIndexStruct { uint16[ 16 ] indexes; } // A structure which is used by Winner Selection algorithm, // which is a subset of the LotteryConfig structure, containing // only items necessary for executing the Winner Selection algorigm. // More detailed member description can be found in LotteryConfig // structure description. // Takes up only one slot! struct WinnerAlgorithmConfig { // --------- Slot --------- // // Individual player max score parts. int16 maxPlayerScore_etherContributed; int16 maxPlayerScore_tokenHoldingAmount; int16 maxPlayerScore_timeFactor; int16 maxPlayerScore_refferalBonus; // Number of lottery winners. uint16 winnerCount; // Score-To-Random ration data (as a rational ratio number). // For example if 1:5, then scorePart = 1, and randPart = 5. uint16 randRatio_scorePart; uint16 randRatio_randPart; // The Ending Algorithm type. uint8 endingAlgoType; } // Structure containing the minimum and maximum values of // holder intermediate scores. // These values get updated on transfers during ACTIVE stage, // when holders buy/sell tokens. // Structure takes up only 2 slots! // struct MinMaxHolderScores { // --------- Slot --------- // // Minimum & maximum values for each score factor. // Updated for holders when they transfer tokens. // Used in winner selection algorithm, to normalize the scores in // a single loop, to avoid looping additional time to find min/max. int80 holderScore_etherContributed_min; int80 holderScore_etherContributed_max; int80 holderScore_timeFactors_min; // --------- Slot --------- // int80 holderScore_timeFactors_max; int80 holderScore_tokenBalance_min; int80 holderScore_tokenBalance_max; } // ROOT_REFERRER constant. // Used to prevent cyclic dependencies on referral tree. address constant ROOT_REFERRER = address( 1 ); // Precision of division operations. int constant PRECISION = 10000; // Random number modulo to use when obtaining random numbers from // the random seed + nonce, using keccak256. // This is the maximum available Score Random Factor, plus one. // By default, 10^9 (one billion). // uint constant RANDOM_MODULO = (10 ** 9); // Maximum number of holders that the MinedWinnerSelection algorithm // can process. Related to block gas limit. uint constant MINEDSELECTION_MAX_NUMBER_OF_HOLDERS = 300; // Maximum number of holders that the WinnerSelfValidation algorithm // can process. Related to block gas limit. uint constant SELFVALIDATION_MAX_NUMBER_OF_HOLDERS = 1200; // ==================== State Variables ==================== // // --------- Slot --------- // // The Lottery address that this storage belongs to. // Is set by the "initialize()", called by corresponding Lottery. address lottery; // The Random Seed, that was passed to us from Randomness Provider, // or generated alternatively. uint64 randomSeed; // The actual number of winners that there will be. Set after // completing the Winner Selection Algorithm. uint16 numberOfWinners; // Bool indicating if Winner Selection Algorithm has been executed. bool algorithmCompleted; // --------- Slot --------- // // Winner Algorithm config. Specified in Initialization(). WinnerAlgorithmConfig algConfig; // --------- Slot --------- // // The Min-Max holder score storage. MinMaxHolderScores public minMaxScores; // --------- Slot --------- // // Array of holders. address[] public holders; // --------- Slot --------- // // Holder array indexes mapping, for O(1) array element access. mapping( address => uint ) holderIndexes; // --------- Slot --------- // // Mapping of holder data. mapping( address => HolderData ) public holderData; // --------- Slot --------- // // Mapping of referral IDs to addresses of holders who generated // those IDs. mapping( uint256 => address ) referrers; // --------- Slot --------- // // The array of final-sorted winners (set after Winner Selection // Algorithm completes), that contains the winners' indexes // in the "holders" array, to save space. // // Notice that by using uint16, we can fit 16 items into one slot! // So, if there are 160 winners, we only take up 10 slots, so // only 20,000 * 10 = 200,000 gas gets consumed! // WinnerIndexStruct[] sortedWinnerIndexes; // ============== Internal (Private) Functions ============== // // Lottery-Only modifier. modifier lotteryOnly { require( msg.sender == address( lottery ) ); _; } // ============== [ BEGIN ] LOTTERY QUICKSORT FUNCTIONS ============== // /** * QuickSort and QuickSelect algorithm functionality code. * * These algorithms are used to find the lottery winners in * an array of final random-factored scores. * As the highest-scorers win, we need to sort an array to * identify them. * * For this task, we use QuickSelect to partition array into * winner part (elements with score larger than X, where X is * n-th largest element, where n is number of winners), * and others (non-winners), who are ignored to save computation * power. * Then we sort the winner part only, using QuickSort, and * distribute prizes to winners accordingly. */ // Swap function used in QuickSort algorithms. // function QSort_swap( FinalScore[] memory list, uint a, uint b ) internal pure { FinalScore memory tmp = list[ a ]; list[ a ] = list[ b ]; list[ b ] = tmp; } // Standard Hoare's partition scheme function, used for both // QuickSort and QuickSelect. // function QSort_partition( FinalScore[] memory list, int lo, int hi ) internal pure returns( int newPivotIndex ) { uint64 pivot = list[ uint( hi + lo ) / 2 ].score; int i = lo - 1; int j = hi + 1; while( true ) { do { i++; } while( list[ uint( i ) ].score > pivot ) ; do { j--; } while( list[ uint( j ) ].score < pivot ) ; if( i >= j ) return j; QSort_swap( list, uint( i ), uint( j ) ); } } // QuickSelect's Lomuto partition scheme. // function QSort_LomutoPartition( FinalScore[] memory list, uint left, uint right, uint pivotIndex ) internal pure returns( uint newPivotIndex ) { uint pivotValue = list[ pivotIndex ].score; QSort_swap( list, pivotIndex, right ); // Move pivot to end uint storeIndex = left; for( uint i = left; i < right; i++ ) { if( list[ i ].score > pivotValue ) { QSort_swap( list, storeIndex, i ); storeIndex++; } } // Move pivot to its final place, and return the pivot's index. QSort_swap( list, right, storeIndex ); return storeIndex; } // QuickSelect algorithm (iterative). // function QSort_QuickSelect( FinalScore[] memory list, int left, int right, int k ) internal pure returns( int indexOfK ) { while( true ) { if( left == right ) return left; int pivotIndex = int( QSort_LomutoPartition( list, uint(left), uint(right), uint(right) ) ); if( k == pivotIndex ) return k; else if( k < pivotIndex ) right = pivotIndex - 1; else left = pivotIndex + 1; } } // Standard QuickSort function. // function QSort_QuickSort( FinalScore[] memory list, int lo, int hi ) internal pure { if( lo < hi ) { int p = QSort_partition( list, lo, hi ); QSort_QuickSort( list, lo, p ); QSort_QuickSort( list, p + 1, hi ); } } // ============== [ END ] LOTTERY QUICKSORT FUNCTIONS ============== // // ------------ Ending Stage - Winner Selection Algorithm ------------ // /** * Compute the individual player score factors for a holder. * Function split from the below one (ending_Stage_2), to avoid * "Stack too Deep" errors. */ function computeHolderIndividualScores( WinnerAlgorithmConfig memory cfg, MinMaxHolderScores memory minMax, HolderData memory hdata ) internal pure returns( int individualScore ) { // Normalize the scores, by subtracting minimum and dividing // by maximum, to get the score values specified in cfg. // Use precision of 100, then round. // // Notice that we're using int arithmetics, so division // truncates. That's why we use PRECISION, to simulate // rounding. // // This formula is better explained in example. // In this example, we use variable abbreviations defined // below, on formula's right side comments. // // Say, values are these in our example: // e = 4, eMin = 1, eMax = 8, MS = 5, P = 10. // // So, let's calculate the score using the formula: // ( ( ( (4 - 1) * 10 * 5 ) / (8 - 1) ) + (10 / 2) ) / 10 = // ( ( ( 3 * 10 * 5 ) / 7 ) + 5 ) / 10 = // ( ( 150 / 7 ) + 5 ) / 10 = // ( ( 150 / 7 ) + 5 ) / 10 = // ( 20 + 5 ) / 10 = // 25 / 10 = // [ 2.5 ] = 2 // // So, with truncation, we see that for e = 4, the score // is 2 out of 5 maximum. // That's because the minimum ether contributed was 1, and // maximum was 8. // So, 4 stays below the middle, and gets a nicely rounded // score of 2. // Compute etherContributed. int score_etherContributed = ( ( ( ( hdata.etherContributed - // e minMax.holderScore_etherContributed_min ) // eMin * PRECISION * cfg.maxPlayerScore_etherContributed ) // P * MS / ( minMax.holderScore_etherContributed_max - // eMax minMax.holderScore_etherContributed_min ) // eMin ) + (PRECISION / 2) ) / PRECISION; // Compute timeFactors. int score_timeFactors = ( ( ( ( hdata.timeFactors - // e minMax.holderScore_timeFactors_min ) // eMin * PRECISION * cfg.maxPlayerScore_timeFactor ) // P * MS / ( minMax.holderScore_timeFactors_max - // eMax minMax.holderScore_timeFactors_min ) // eMin ) + (PRECISION / 2) ) / PRECISION; // Compute tokenBalance. int score_tokenBalance = ( ( ( ( hdata.tokenBalance - // e minMax.holderScore_tokenBalance_min ) // eMin * PRECISION * cfg.maxPlayerScore_tokenHoldingAmount ) / ( minMax.holderScore_tokenBalance_max - // eMax minMax.holderScore_tokenBalance_min ) // eMin ) + (PRECISION / 2) ) / PRECISION; // Return the accumulated individual score (excluding referrees). return score_etherContributed + score_timeFactors + score_tokenBalance; } /** * Split-function, to avoid "Stack-2-Deep" errors. * Computes a single component of a Referree Score. */ /*function priv_computeSingleReferreeComponent( int _referreeScore_, int _maxPlayerScore_, int _holderScore_min_x_refCount, int _holderScore_max_x_refCount ) internal pure returns( int score ) { score = ( ( PRECISION * _maxPlayerScore_ * ( _referreeScore_ - _holderScore_min_x_refCount ) ) / ( _holderScore_max_x_refCount - _holderScore_min_x_refCount ) ); }*/ /** * Compute the unified Referree-Score of a player, who's got * the accumulated factor-scores of all his referrees in his * holderData structure. * * @param individualToReferralRatio - an int value, computed * before starting the winner score computation loop, in * the ending_Stage_2 initial part, to save computation * time later. * This is the ratio of the maximum available referral score, * to the maximum available individual score, as defined in * the config (for example, if max.ref.score is 20, and * max.ind.score is 40, then the ratio is 20/40 = 0.5). * * We use this ratio to transform the computed accumulated * referree individual scores to the standard referrer's * score, by multiplying by that ratio. */ function computeReferreeScoresForHolder( int individualToReferralRatio, WinnerAlgorithmConfig memory cfg, MinMaxHolderScores memory minMax, HolderData memory hdata ) internal pure returns( int unifiedReferreeScore ) { // If number of referrees of this HODLer is Zero, then // his referree score is also zero. if( hdata.referreeCount == 0 ) return 0; // Now, compute the Referree's Accumulated Scores. // // Here we use the same formula as when computing individual // scores (in the function above), but we multiply the // Min & Max known score value by the referree count, because // the "referree_..." scores are accumulated scores of all // referrees that that holder has. // This way, we reach the uniform averaged score of all referrees, // just like we do with individual scores. // // Also, we don't divide them by PRECISION, to accumulate and use // the max-score-options in the main score computing function. int refCount = int( hdata.referreeCount ); // Compute etherContributed. int referreeScore_etherContributed = ( ( ( hdata.referree_etherContributed - minMax.holderScore_etherContributed_min * refCount ) * PRECISION * cfg.maxPlayerScore_etherContributed ) / ( minMax.holderScore_etherContributed_max * refCount - minMax.holderScore_etherContributed_min * refCount ) ); // Compute timeFactors. int referreeScore_timeFactors = ( ( ( hdata.referree_timeFactors - minMax.holderScore_timeFactors_min * refCount ) * PRECISION * cfg.maxPlayerScore_timeFactor ) / ( minMax.holderScore_timeFactors_max * refCount - minMax.holderScore_timeFactors_min * refCount ) ); // Compute tokenBalance. int referreeScore_tokenBalance = ( ( ( hdata.referree_tokenBalance - minMax.holderScore_tokenBalance_min * refCount ) * PRECISION * cfg.maxPlayerScore_tokenHoldingAmount ) / ( minMax.holderScore_tokenBalance_max * refCount - minMax.holderScore_tokenBalance_min * refCount ) ); // Accumulate 'em all ! // Then, multiply it by the ratio of all individual max scores // (maxPlayerScore_etherContributed, timeFactor, tokenBalance), // to the maxPlayerScore_refferalBonus. // Use the same precision. unifiedReferreeScore = int( ( ( ( ( referreeScore_etherContributed + referreeScore_timeFactors + referreeScore_tokenBalance ) + (PRECISION / 2) ) / PRECISION ) * individualToReferralRatio ) / PRECISION ); } // =================== PUBLIC FUNCTIONS =================== // /** * Update current holder's score with given change values, and * Propagate the holder's current transfer's score changes * through the referral chain, updating every parent referrer's * accumulated referree scores, until the ROOT_REFERRER or zero * address referrer is encountered. */ function updateAndPropagateScoreChanges( address holder, int80 etherContributed_change, int80 timeFactors_change, int80 tokenBalance_change ) public lotteryOnly { // Update current holder's score. holderData[ holder ].etherContributed += etherContributed_change; holderData[ holder ].timeFactors += timeFactors_change; holderData[ holder ].tokenBalance += tokenBalance_change; // Check if scores are exceeding current min/max scores, // and if so, update the min/max scores. // etherContributed: if( holderData[ holder ].etherContributed > minMaxScores.holderScore_etherContributed_max ) minMaxScores.holderScore_etherContributed_max = holderData[ holder ].etherContributed; if( holderData[ holder ].etherContributed < minMaxScores.holderScore_etherContributed_min ) minMaxScores.holderScore_etherContributed_min = holderData[ holder ].etherContributed; // timeFactors: if( holderData[ holder ].timeFactors > minMaxScores.holderScore_timeFactors_max ) minMaxScores.holderScore_timeFactors_max = holderData[ holder ].timeFactors; if( holderData[ holder ].timeFactors < minMaxScores.holderScore_timeFactors_min ) minMaxScores.holderScore_timeFactors_min = holderData[ holder ].timeFactors; // tokenBalance: if( holderData[ holder ].tokenBalance > minMaxScores.holderScore_tokenBalance_max ) minMaxScores.holderScore_tokenBalance_max = holderData[ holder ].tokenBalance; if( holderData[ holder ].tokenBalance < minMaxScores.holderScore_tokenBalance_min ) minMaxScores.holderScore_tokenBalance_min = holderData[ holder ].tokenBalance; // Propagate the score through the referral chain. // Dive at maximum to the depth of 10, to avoid "Outta Gas" // errors. uint MAX_REFERRAL_DEPTH = 10; uint depth = 0; address referrerAddr = holderData[ holder ].referrer; while( referrerAddr != ROOT_REFERRER && referrerAddr != address( 0 ) && depth < MAX_REFERRAL_DEPTH ) { // Update this referrer's accumulated referree scores. holderData[ referrerAddr ].referree_etherContributed += etherContributed_change; holderData[ referrerAddr ].referree_timeFactors += timeFactors_change; holderData[ referrerAddr ].referree_tokenBalance += tokenBalance_change; // Move to the higher-level referrer. referrerAddr = holderData[ referrerAddr ].referrer; depth++; } } /** * Function executes the Lottery Winner Selection Algorithm, * and writes the final, sorted array, containing winner rankings. * * This function is called from the Lottery's Mining Stage Step 2, * * This is the final function that lottery performs actively - * and arguably the most important - because it determines * lottery winners through Winner Selection Algorithm. * * The random seed must be already set, before calling this function. */ function executeWinnerSelectionAlgorithm() public lotteryOnly { // Copy the Winner Algo Config into memory, to avoid using // 400-gas costing SLOAD every time we need to load something. WinnerAlgorithmConfig memory cfg = algConfig; // Can only be performed if algorithm is MinedWinnerSelection! require( cfg.endingAlgoType == uint8(Lottery.EndingAlgoType.MinedWinnerSelection) ); // Now, we gotta find the winners using a Randomized Score-Based // Winner Selection Algorithm. // // During transfers, all player intermediate scores // (etherContributed, timeFactors, and tokenBalances) were // already set in every holder's HolderData structure, // during operations of updateHolderData_preTransfer() function. // // Minimum and maximum values are also known, so normalization // will be easy. // All referral tree score data were also properly propagated // during operations of updateAndPropagateScoreChanges() function. // // All we now have to do, is loop through holder array, and // compute randomized final scores for every holder, into // the Final Score array. // Declare the Final Score array - computed for all holders. uint ARRLEN = ( holders.length > MINEDSELECTION_MAX_NUMBER_OF_HOLDERS ? MINEDSELECTION_MAX_NUMBER_OF_HOLDERS : holders.length ); FinalScore[] memory finalScores = new FinalScore[] ( ARRLEN ); // Compute the precision-adjusted constant ratio of // referralBonus max score to the player individual max scores. int individualToReferralRatio = ( PRECISION * cfg.maxPlayerScore_refferalBonus ) / ( int( cfg.maxPlayerScore_etherContributed ) + int( cfg.maxPlayerScore_timeFactor ) + int( cfg.maxPlayerScore_tokenHoldingAmount ) ); // Max available player score. int maxAvailablePlayerScore = int( cfg.maxPlayerScore_etherContributed + cfg.maxPlayerScore_timeFactor + cfg.maxPlayerScore_tokenHoldingAmount + cfg.maxPlayerScore_refferalBonus ); // Random Factor of scores, to maintain random-to-determined // ratio equal to specific value (1:5 for example - // "randPart" == 5, "scorePart" == 1). // // maxAvailablePlayerScore * FACT --- scorePart // RANDOM_MODULO --- randPart // // RANDOM_MODULO * scorePart // maxAvailablePlayerScore * FACT = ------------------------- // randPart // // RANDOM_MODULO * scorePart // FACT = -------------------------------------- // randPart * maxAvailablePlayerScore int SCORE_RAND_FACT = ( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) / ( int(cfg.randRatio_randPart) * maxAvailablePlayerScore ); // Fix Min-Max scores, to avoid division by zero, if min == max. // If min == max, make the difference equal to 1. MinMaxHolderScores memory minMaxCpy = minMaxScores; if( minMaxCpy.holderScore_etherContributed_min == minMaxCpy.holderScore_etherContributed_max ) minMaxCpy.holderScore_etherContributed_max = minMaxCpy.holderScore_etherContributed_min + 1; if( minMaxCpy.holderScore_timeFactors_min == minMaxCpy.holderScore_timeFactors_max ) minMaxCpy.holderScore_timeFactors_max = minMaxCpy.holderScore_timeFactors_min + 1; if( minMaxCpy.holderScore_tokenBalance_min == minMaxCpy.holderScore_tokenBalance_max ) minMaxCpy.holderScore_tokenBalance_max = minMaxCpy.holderScore_tokenBalance_min + 1; // Loop through all the holders. for( uint i = 0; i < ARRLEN; i++ ) { // Fetch the needed holder data to in-memory hdata variable, // to save gas on score part computing functions. HolderData memory hdata; // Slot 1: hdata.etherContributed = holderData[ holders[ i ] ].etherContributed; hdata.timeFactors = holderData[ holders[ i ] ].timeFactors; hdata.tokenBalance = holderData[ holders[ i ] ].tokenBalance; hdata.referreeCount = holderData[ holders[ i ] ].referreeCount; // Slot 2: hdata.referree_etherContributed = holderData[ holders[ i ] ].referree_etherContributed; hdata.referree_timeFactors = holderData[ holders[ i ] ].referree_timeFactors; hdata.referree_tokenBalance = holderData[ holders[ i ] ].referree_tokenBalance; hdata.bonusScore = holderData[ holders[ i ] ].bonusScore; // Now, add bonus score, and compute total player's score: // Bonus part, individual score part, and referree score part. int totalPlayerScore = hdata.bonusScore + computeHolderIndividualScores( cfg, minMaxCpy, hdata ) + computeReferreeScoresForHolder( individualToReferralRatio, cfg, minMaxCpy, hdata ); // Check if total player score <= 0. If so, make it equal // to 1, because otherwise randomization won't be possible. if( totalPlayerScore <= 0 ) totalPlayerScore = 1; // Now, check if it's not more than max! If so, lowerify. // This could have happen'd because of bonus. if( totalPlayerScore > maxAvailablePlayerScore ) totalPlayerScore = maxAvailablePlayerScore; // Multiply the score by the Random Modulo Adjustment // Factor, to get fairer ratio of random-to-determined data. totalPlayerScore = ( totalPlayerScore * SCORE_RAND_FACT ) / ( PRECISION ); // Score is computed! // Now, randomize it, and add to Final Scores Array. // We use keccak to generate a random number from random seed, // using holder's address as a nonce. uint modulizedRandomNumber = uint( keccak256( abi.encodePacked( randomSeed, holders[ i ] ) ) ) % RANDOM_MODULO; // Add the random number, to introduce the random factor. // Ratio of (current) totalPlayerScore to modulizedRandomNumber // is the same as ratio of randRatio_scorePart to // randRatio_randPart. uint endScore = uint( totalPlayerScore ) + modulizedRandomNumber; // Finally, set this holder's final score data. finalScores[ i ].addr = holders[ i ]; finalScores[ i ].holderIndex = uint16( i ); finalScores[ i ].score = uint64( endScore ); } // All final scores are now computed. // Sort the array, to find out the highest scores! // Firstly, partition an array to only work on top K scores, // where K is the number of winners. // There can be a rare case where specified number of winners is // more than lottery token holders. We got that covered. require( finalScores.length > 0 ); uint K = cfg.winnerCount - 1; if( K > finalScores.length-1 ) K = finalScores.length-1; // Must be THE LAST ELEMENT's INDEX. // Use QuickSelect to do this. QSort_QuickSelect( finalScores, 0, int( finalScores.length - 1 ), int( K ) ); // Now, QuickSort only the first K items, because the rest // item scores are not high enough to become winners. QSort_QuickSort( finalScores, 0, int( K ) ); // Now, the winner array is sorted, with the highest scores // sitting at the first positions! // Let's set up the winner indexes array, where we'll store // the winners' indexes in the holders array. // So, if this array is [8, 2, 3], that means that // Winner #1 is holders[8], winner #2 is holders[2], and // winner #3 is holders[3]. // Set the Number Of Winners variable. numberOfWinners = uint16( K + 1 ); // Now, we can loop through the first numberOfWinners elements, to set // the holder indexes! // Loop through 16 elements at a time, to fill the structs. for( uint offset = 0; offset < numberOfWinners; offset += 16 ) { WinnerIndexStruct memory windStruct; uint loopStop = ( offset + 16 > numberOfWinners ? numberOfWinners : offset + 16 ); for( uint i = offset; i < loopStop; i++ ) { windStruct.indexes[ i - offset ] =finalScores[ i ].holderIndex; } // Push this now-filled struct to the storage array! sortedWinnerIndexes.push( windStruct ); } // That's it! We're done! algorithmCompleted = true; } /** * Add a holder to holders array. * @param holder - address of a holder to add. */ function addHolder( address holder ) public lotteryOnly { // Add it to list, and set index in the mapping. holders.push( holder ); holderIndexes[ holder ] = holders.length - 1; } /** * Removes the holder 'sender' from the Holders Array. * However, this holder's HolderData structure persists! * * Notice that no index validity checks are performed, so, if * 'sender' is not present in "holderIndexes" mapping, this * function will remove the 0th holder instead! * This is not a problem for us, because Lottery calls this * function only when it's absolutely certain that 'sender' is * present in the holders array. * * @param sender - address of a holder to remove. * Named 'sender', because when token sender sends away all * his tokens, he must then be removed from holders array. */ function removeHolder( address sender ) public lotteryOnly { // Get index of the sender address in the holders array. uint index = holderIndexes[ sender ]; // Remove the sender from array, by copying last element's // value into the index'th element, where sender was before. holders[ index ] = holders[ holders.length - 1 ]; // Remove the last element of array, which we've just copied. holders.pop(); // Update indexes: remove the sender's index from the mapping, // and change the previoulsy-last element's index to the // one where we copied it - where sender was before. delete holderIndexes[ sender ]; holderIndexes[ holders[ index ] ] = index; } /** * Get holder array length. */ function getHolderCount() public view returns( uint ) { return holders.length; } /** * Generate a referral ID for a token holder. * Referral ID is used to refer other wallets into playing our * lottery. * - Referrer gets bonus points for every wallet that bought * lottery tokens and specified his referral ID. * - Referrees (wallets who got referred by registering a valid * referral ID, corresponding to some referrer), get some * bonus points for specifying (registering) a referral ID. * * Referral ID is a uint256 number, which is generated by * keccak256'ing the holder's address, holder's current * token ballance, and current time. */ function generateReferralID( address holder ) public lotteryOnly returns( uint256 referralID ) { // Check if holder has some tokens, and doesn't // have his own referral ID yet. require( holderData[ holder ].tokenBalance != 0 ); require( holderData[ holder ].referralID == 0 ); // Generate a referral ID with keccak. uint256 refID = uint256( keccak256( abi.encodePacked( holder, holderData[ holder ].tokenBalance, now ) ) ); // Specify the ID as current ID of this holder. holderData[ holder ].referralID = refID; // If this holder wasn't referred by anyone (his referrer is // not set), and he's now generated his own ID, he won't // be able to register as a referree of someone else // from now on. // This is done to prevent circular dependency in referrals. // Do it by setting a referrer to ROOT_REFERRER address, // which is an invalid address (address(1)). if( holderData[ holder ].referrer == address( 0 ) ) holderData[ holder ].referrer = ROOT_REFERRER; // Create a new referrer with this ID. referrers[ refID ] = holder; return refID; } /** * Register a referral for a token holder, using a valid * referral ID got from a referrer. * This function is called by a referree, who obtained a * valid referral ID from some referrer, who previously * generated it using generateReferralID(). * * You can only register a referral once! * When you do so, you get bonus referral points! */ function registerReferral( address holder, int16 referralRegisteringBonus, uint256 referralID ) public lotteryOnly returns( address _referrerAddress ) { // Check if this holder has some tokens, and if he hasn't // registered a referral yet. require( holderData[ holder ].tokenBalance != 0 ); require( holderData[ holder ].referrer == address( 0 ) ); // Get the referrer's address from his ID, and specify // it as a referrer of holder. holderData[ holder ].referrer = referrers[ referralID ]; // Bonus points are added to this holder's score for // registering a referral! holderData[ holder ].bonusScore = referralRegisteringBonus; // Increment number of referrees for every parent referrer, // by traversing a referral tree child->parent way. address referrerAddr = holderData[ holder ].referrer; // Set the return value. _referrerAddress = referrerAddr; // Traverse a tree. while( referrerAddr != ROOT_REFERRER && referrerAddr != address( 0 ) ) { // Increment referree count for this referrrer. holderData[ referrerAddr ].referreeCount++; // Update the Referrer Scores of the referrer, adding this // referree's scores to it's current values. holderData[ referrerAddr ].referree_etherContributed += holderData[ holder ].etherContributed; holderData[ referrerAddr ].referree_timeFactors += holderData[ holder ].timeFactors; holderData[ referrerAddr ].referree_tokenBalance += holderData[ holder ].tokenBalance; // Move to the higher-level referrer. referrerAddr = holderData[ referrerAddr ].referrer; } return _referrerAddress; } /** * Sets our random seed to some value. * Should be called from Lottery, after obtaining random seed from * the Randomness Provider. */ function setRandomSeed( uint _seed ) external lotteryOnly { randomSeed = uint64( _seed ); } /** * Initialization function. * Here, we bind our contract to the Lottery contract that * this Storage belongs to. * The parent lottery must call this function - hence, we set * "lottery" to msg.sender. * * When this function is called, our contract must be not yet * initialized - "lottery" address must be Zero! * * Here, we also set our Winner Algorithm config, which is a * subset of LotteryConfig, fitting into 1 storage slot. */ function initialize( WinnerAlgorithmConfig memory _wcfg ) public { require( address( lottery ) == address( 0 ) ); // Set the Lottery address (msg.sender can't be zero), // and thus, set our contract to initialized! lottery = msg.sender; // Set the Winner-Algo-Config. algConfig = _wcfg; // NOT-NEEDED: Set initial min-max scores: min is INT_MAX. /*minMaxScores.holderScore_etherContributed_min = int80( 2 ** 78 ); minMaxScores.holderScore_timeFactors_min = int80( 2 ** 78 ); minMaxScores.holderScore_tokenBalance_min = int80( 2 ** 78 ); */ } // ==================== Views ==================== // // Returns the current random seed. // If the seed hasn't been set yet (or set to 0), returns 0. // function getRandomSeed() external view returns( uint ) { return randomSeed; } // Check if Winner Selection Algorithm has beed executed. // function minedSelection_algorithmAlreadyExecuted() external view returns( bool ) { return algorithmCompleted; } /** * After lottery has completed, this function returns if "addr" * is one of lottery winners, and the position in winner rankings. * Function is used to obtain the ranking position before * calling claimWinnerPrize() on Lottery. * * This function should be called off-chain, and then using the * retrieved data, one can call claimWinnerPrize(). */ function minedSelection_getWinnerStatus( address addr ) public view returns( bool isWinner, uint32 rankingPosition ) { // Loop through the whole winner indexes array, trying to // find if "addr" is one of the winner addresses. for( uint16 i = 0; i < numberOfWinners; i++ ) { // Check if holder on this winner ranking's index position // is addr, if so, good! uint pos = sortedWinnerIndexes[ i / 16 ].indexes[ i % 16 ]; if( holders[ pos ] == addr ) { return ( true, i ); } } // The "addr" is not a winner. return ( false, 0 ); } /** * Checks if address is on specified winner ranking position. * Used in Lottery, to check if msg.sender is really the * winner #rankingPosition, as he claims to be. */ function minedSelection_isAddressOnWinnerPosition( address addr, uint32 rankingPosition ) external view returns( bool ) { if( rankingPosition >= numberOfWinners ) return false; // Just check if address at "holders" array // index "sortedWinnerIndexes[ position ]" is really the "addr". uint pos = sortedWinnerIndexes[ rankingPosition / 16 ] .indexes[ rankingPosition % 16 ]; return ( holders[ pos ] == addr ); } /** * Returns an array of all winner addresses, sorted by their * ranking position (winner #1 first, #2 second, etc.). */ function minedSelection_getAllWinners() external view returns( address[] memory ) { address[] memory winners = new address[] ( numberOfWinners ); for( uint i = 0; i < numberOfWinners; i++ ) { uint pos = sortedWinnerIndexes[ i / 16 ].indexes[ i % 16 ]; winners[ i ] = holders[ pos ]; } return winners; } /** * Compute the Lottery Active Stage Score of a token holder. * * This function computes the Active Stage (pre-randomization) * player score, and should generally be used to compute player * intermediate scores - while lottery is still active or on * finishing stage, before random random seed is obtained. */ function getPlayerActiveStageScore( address holderAddr ) external view returns( uint playerScore ) { // Copy the Winner Algo Config into memory, to avoid using // 400-gas costing SLOAD every time we need to load something. WinnerAlgorithmConfig memory cfg = algConfig; // Check if holderAddr is a holder at all! if( holders[ holderIndexes[ holderAddr ] ] != holderAddr ) return 0; // Compute the precision-adjusted constant ratio of // referralBonus max score to the player individual max scores. int individualToReferralRatio = ( PRECISION * cfg.maxPlayerScore_refferalBonus ) / ( int( cfg.maxPlayerScore_etherContributed ) + int( cfg.maxPlayerScore_timeFactor ) + int( cfg.maxPlayerScore_tokenHoldingAmount ) ); // Max available player score. int maxAvailablePlayerScore = int( cfg.maxPlayerScore_etherContributed + cfg.maxPlayerScore_timeFactor + cfg.maxPlayerScore_tokenHoldingAmount + cfg.maxPlayerScore_refferalBonus ); // Fix Min-Max scores, to avoid division by zero, if min == max. // If min == max, make the difference equal to 1. MinMaxHolderScores memory minMaxCpy = minMaxScores; if( minMaxCpy.holderScore_etherContributed_min == minMaxCpy.holderScore_etherContributed_max ) minMaxCpy.holderScore_etherContributed_max = minMaxCpy.holderScore_etherContributed_min + 1; if( minMaxCpy.holderScore_timeFactors_min == minMaxCpy.holderScore_timeFactors_max ) minMaxCpy.holderScore_timeFactors_max = minMaxCpy.holderScore_timeFactors_min + 1; if( minMaxCpy.holderScore_tokenBalance_min == minMaxCpy.holderScore_tokenBalance_max ) minMaxCpy.holderScore_tokenBalance_max = minMaxCpy.holderScore_tokenBalance_min + 1; // Now, add bonus score, and compute total player's score: // Bonus part, individual score part, and referree score part. int totalPlayerScore = holderData[ holderAddr ].bonusScore + computeHolderIndividualScores( cfg, minMaxCpy, holderData[ holderAddr ] ) + computeReferreeScoresForHolder( individualToReferralRatio, cfg, minMaxCpy, holderData[ holderAddr ] ); // Check if total player score <= 0. If so, make it equal // to 1, because otherwise randomization won't be possible. if( totalPlayerScore <= 0 ) totalPlayerScore = 1; // Now, check if it's not more than max! If so, lowerify. // This could have happen'd because of bonus. if( totalPlayerScore > maxAvailablePlayerScore ) totalPlayerScore = maxAvailablePlayerScore; // Return the score! return uint( totalPlayerScore ); } /** * Internal sub-procedure of the function below, used to obtain * a final, randomized score of a Single Holder. */ function priv_getSingleHolderScore( address hold3r, int individualToReferralRatio, int maxAvailablePlayerScore, int SCORE_RAND_FACT, WinnerAlgorithmConfig memory cfg, MinMaxHolderScores memory minMaxCpy ) internal view returns( uint endScore ) { // Fetch the needed holder data to in-memory hdata variable, // to save gas on score part computing functions. HolderData memory hdata; // Slot 1: hdata.etherContributed = holderData[ hold3r ].etherContributed; hdata.timeFactors = holderData[ hold3r ].timeFactors; hdata.tokenBalance = holderData[ hold3r ].tokenBalance; hdata.referreeCount = holderData[ hold3r ].referreeCount; // Slot 2: hdata.referree_etherContributed = holderData[ hold3r ].referree_etherContributed; hdata.referree_timeFactors = holderData[ hold3r ].referree_timeFactors; hdata.referree_tokenBalance = holderData[ hold3r ].referree_tokenBalance; hdata.bonusScore = holderData[ hold3r ].bonusScore; // Now, add bonus score, and compute total player's score: // Bonus part, individual score part, and referree score part. int totalPlayerScore = hdata.bonusScore + computeHolderIndividualScores( cfg, minMaxCpy, hdata ) + computeReferreeScoresForHolder( individualToReferralRatio, cfg, minMaxCpy, hdata ); // Check if total player score <= 0. If so, make it equal // to 1, because otherwise randomization won't be possible. if( totalPlayerScore <= 0 ) totalPlayerScore = 1; // Now, check if it's not more than max! If so, lowerify. // This could have happen'd because of bonus. if( totalPlayerScore > maxAvailablePlayerScore ) totalPlayerScore = maxAvailablePlayerScore; // Multiply the score by the Random Modulo Adjustment // Factor, to get fairer ratio of random-to-determined data. totalPlayerScore = ( totalPlayerScore * SCORE_RAND_FACT ) / ( PRECISION ); // Score is computed! // Now, randomize it, and add to Final Scores Array. // We use keccak to generate a random number from random seed, // using holder's address as a nonce. uint modulizedRandomNumber = uint( keccak256( abi.encodePacked( randomSeed, hold3r ) ) ) % RANDOM_MODULO; // Add the random number, to introduce the random factor. // Ratio of (current) totalPlayerScore to modulizedRandomNumber // is the same as ratio of randRatio_scorePart to // randRatio_randPart. return uint( totalPlayerScore ) + modulizedRandomNumber; } /** * Winner Self-Validation algo-type main function. * Here, we compute scores for all lottery holders iteratively * in O(n) time, and thus get the winner ranking position of * the holder in question. * * This function performs essentialy the same steps as the * Mined-variant (executeWinnerSelectionAlgorithm), but doesn't * write anything to blockchain. * * @param holderAddr - address of a holder whose rank we want to find. */ function winnerSelfValidation_getWinnerStatus( address holderAddr ) internal view returns( bool isWinner, uint rankingPosition ) { // Copy the Winner Algo Config into memory, to avoid using // 400-gas costing SLOAD every time we need to load something. WinnerAlgorithmConfig memory cfg = algConfig; // Can only be performed if algorithm is WinnerSelfValidation! require( cfg.endingAlgoType == uint8(Lottery.EndingAlgoType.WinnerSelfValidation) ); // Check if holderAddr is a holder at all! require( holders[ holderIndexes[ holderAddr ] ] == holderAddr ); // Now, we gotta find the winners using a Randomized Score-Based // Winner Selection Algorithm. // // During transfers, all player intermediate scores // (etherContributed, timeFactors, and tokenBalances) were // already set in every holder's HolderData structure, // during operations of updateHolderData_preTransfer() function. // // Minimum and maximum values are also known, so normalization // will be easy. // All referral tree score data were also properly propagated // during operations of updateAndPropagateScoreChanges() function. // // All we now have to do, is loop through holder array, and // compute randomized final scores for every holder. // Compute the precision-adjusted constant ratio of // referralBonus max score to the player individual max scores. int individualToReferralRatio = ( PRECISION * cfg.maxPlayerScore_refferalBonus ) / ( int( cfg.maxPlayerScore_etherContributed ) + int( cfg.maxPlayerScore_timeFactor ) + int( cfg.maxPlayerScore_tokenHoldingAmount ) ); // Max available player score. int maxAvailablePlayerScore = int( cfg.maxPlayerScore_etherContributed + cfg.maxPlayerScore_timeFactor + cfg.maxPlayerScore_tokenHoldingAmount + cfg.maxPlayerScore_refferalBonus ); // Random Factor of scores, to maintain random-to-determined // ratio equal to specific value (1:5 for example - // "randPart" == 5, "scorePart" == 1). // // maxAvailablePlayerScore * FACT --- scorePart // RANDOM_MODULO --- randPart // // RANDOM_MODULO * scorePart // maxAvailablePlayerScore * FACT = ------------------------- // randPart // // RANDOM_MODULO * scorePart // FACT = -------------------------------------- // randPart * maxAvailablePlayerScore int SCORE_RAND_FACT = ( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) / ( int(cfg.randRatio_randPart) * maxAvailablePlayerScore ); // Fix Min-Max scores, to avoid division by zero, if min == max. // If min == max, make the difference equal to 1. MinMaxHolderScores memory minMaxCpy = minMaxScores; if( minMaxCpy.holderScore_etherContributed_min == minMaxCpy.holderScore_etherContributed_max ) minMaxCpy.holderScore_etherContributed_max = minMaxCpy.holderScore_etherContributed_min + 1; if( minMaxCpy.holderScore_timeFactors_min == minMaxCpy.holderScore_timeFactors_max ) minMaxCpy.holderScore_timeFactors_max = minMaxCpy.holderScore_timeFactors_min + 1; if( minMaxCpy.holderScore_tokenBalance_min == minMaxCpy.holderScore_tokenBalance_max ) minMaxCpy.holderScore_tokenBalance_max = minMaxCpy.holderScore_tokenBalance_min + 1; // How many holders had higher scores than "holderAddr". // Used to obtain the final winner rank of "holderAddr". uint numOfHoldersHigherThan = 0; // The final (randomized) score of "holderAddr". uint holderAddrsFinalScore = priv_getSingleHolderScore( holderAddr, individualToReferralRatio, maxAvailablePlayerScore, SCORE_RAND_FACT, cfg, minMaxCpy ); // Index of holderAddr. uint holderAddrIndex = holderIndexes[ holderAddr ]; // Loop through all the allowed holders. for( uint i = 0; i < ( holders.length < SELFVALIDATION_MAX_NUMBER_OF_HOLDERS ? holders.length : SELFVALIDATION_MAX_NUMBER_OF_HOLDERS ); i++ ) { // Skip the holderAddr's index. if( i == holderAddrIndex ) continue; // Compute the score using helper function. uint endScore = priv_getSingleHolderScore( holders[ i ], individualToReferralRatio, maxAvailablePlayerScore, SCORE_RAND_FACT, cfg, minMaxCpy ); // Check if score is higher than HolderAddr's, and if so, check. if( endScore > holderAddrsFinalScore ) numOfHoldersHigherThan++; } // All scores are checked! // Now, we can obtain holderAddr's winner rank based on how // many scores were above holderAddr's score! isWinner = ( numOfHoldersHigherThan < cfg.winnerCount ); rankingPosition = numOfHoldersHigherThan; } /** * Rolled-Randomness algo-type main function. * Here, we only compute the score of the holder in question, * and compare it to maximum-available final score, divided * by no-of-winners. * * @param holderAddr - address of a holder whose rank we want to find. */ function rolledRandomness_getWinnerStatus( address holderAddr ) internal view returns( bool isWinner, uint rankingPosition ) { // Copy the Winner Algo Config into memory, to avoid using // 400-gas costing SLOAD every time we need to load something. WinnerAlgorithmConfig memory cfg = algConfig; // Can only be performed if algorithm is RolledRandomness! require( cfg.endingAlgoType == uint8(Lottery.EndingAlgoType.RolledRandomness) ); // Check if holderAddr is a holder at all! require( holders[ holderIndexes[ holderAddr ] ] == holderAddr ); // Now, we gotta find the winners using a Randomized Score-Based // Winner Selection Algorithm. // // During transfers, all player intermediate scores // (etherContributed, timeFactors, and tokenBalances) were // already set in every holder's HolderData structure, // during operations of updateHolderData_preTransfer() function. // // Minimum and maximum values are also known, so normalization // will be easy. // All referral tree score data were also properly propagated // during operations of updateAndPropagateScoreChanges() function. // // All we now have to do, is loop through holder array, and // compute randomized final scores for every holder. // Compute the precision-adjusted constant ratio of // referralBonus max score to the player individual max scores. int individualToReferralRatio = ( PRECISION * cfg.maxPlayerScore_refferalBonus ) / ( int( cfg.maxPlayerScore_etherContributed ) + int( cfg.maxPlayerScore_timeFactor ) + int( cfg.maxPlayerScore_tokenHoldingAmount ) ); // Max available player score. int maxAvailablePlayerScore = int( cfg.maxPlayerScore_etherContributed + cfg.maxPlayerScore_timeFactor + cfg.maxPlayerScore_tokenHoldingAmount + cfg.maxPlayerScore_refferalBonus ); // Random Factor of scores, to maintain random-to-determined // ratio equal to specific value (1:5 for example - // "randPart" == 5, "scorePart" == 1). // // maxAvailablePlayerScore * FACT --- scorePart // RANDOM_MODULO --- randPart // // RANDOM_MODULO * scorePart // maxAvailablePlayerScore * FACT = ------------------------- // randPart // // RANDOM_MODULO * scorePart // FACT = -------------------------------------- // randPart * maxAvailablePlayerScore int SCORE_RAND_FACT = ( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) / ( int(cfg.randRatio_randPart) * maxAvailablePlayerScore ); // Fix Min-Max scores, to avoid division by zero, if min == max. // If min == max, make the difference equal to 1. MinMaxHolderScores memory minMaxCpy = minMaxScores; if( minMaxCpy.holderScore_etherContributed_min == minMaxCpy.holderScore_etherContributed_max ) minMaxCpy.holderScore_etherContributed_max = minMaxCpy.holderScore_etherContributed_min + 1; if( minMaxCpy.holderScore_timeFactors_min == minMaxCpy.holderScore_timeFactors_max ) minMaxCpy.holderScore_timeFactors_max = minMaxCpy.holderScore_timeFactors_min + 1; if( minMaxCpy.holderScore_tokenBalance_min == minMaxCpy.holderScore_tokenBalance_max ) minMaxCpy.holderScore_tokenBalance_max = minMaxCpy.holderScore_tokenBalance_min + 1; // The final (randomized) score of "holderAddr". uint holderAddrsFinalScore = priv_getSingleHolderScore( holderAddr, individualToReferralRatio, maxAvailablePlayerScore, SCORE_RAND_FACT, cfg, minMaxCpy ); // Now, compute the Max-Final-Random Score, divide it // by the Holder Count, and get the ranking by placing this // holder's score in it's corresponding part. // // In this approach, we assume linear randomness distribution. // In practice, distribution might be a bit different, but this // approach is the most efficient. // // Max-Final-Score (randomized) is the highest available score // that can be achieved, and is made by adding together the // maximum availabe Player Score Part and maximum available // Random Part (equals RANDOM_MODULO). // These parts have a ratio equal to config-specified // randRatio_scorePart to randRatio_randPart. // // So, if player's active stage's score is low (1), but rand-part // in ratio is huge, then the score is mostly random, so // maxFinalScore is close to the RANDOM_MODULO - maximum random // value that can be rolled. // // If, however, we use 1:1 playerScore-to-Random Ratio, then // playerScore and RandomScore make up equal parts of end score, // so the maxFinalScore is actually two times larger than // RANDOM_MODULO, so player needs to score more // player-points to get larger prizes. // // In default configuration, playerScore-to-random ratio is 1:3, // so there's a good randomness factor, so even the low-scoring // players can reasonably hope to get larger prizes, but // the higher is player's active stage score, the more // chances of scoring a high final score a player gets, with // the higher-end of player scores basically guaranteeing // themselves a specific prize amount, if winnerCount is // big enough to overlap. int maxRandomPart = int( RANDOM_MODULO - 1 ); int maxPlayerScorePart = ( SCORE_RAND_FACT * maxAvailablePlayerScore ) / PRECISION; uint maxFinalScore = uint( maxRandomPart + maxPlayerScorePart ); // Compute the amount that single-holder's virtual part // might take up in the max-final score. uint singleHolderPart = maxFinalScore / holders.length; // Now, compute how many single-holder-parts are there in // this holder's score. uint holderAddrScorePartCount = holderAddrsFinalScore / singleHolderPart; // The ranking is that number, minus holders length. // If very high score is scored, default to position 0 (highest). rankingPosition = ( holderAddrScorePartCount < holders.length ? holders.length - holderAddrScorePartCount : 0 ); isWinner = ( rankingPosition < cfg.winnerCount ); } /** * Genericized, algorithm type-dependent getWinnerStatus function. */ function getWinnerStatus( address addr ) external view returns( bool isWinner, uint32 rankingPosition ) { bool _isW; uint _rp; if( algConfig.endingAlgoType == uint8(Lottery.EndingAlgoType.RolledRandomness) ) { (_isW, _rp) = rolledRandomness_getWinnerStatus( addr ); return ( _isW, uint32( _rp ) ); } if( algConfig.endingAlgoType == uint8(Lottery.EndingAlgoType.WinnerSelfValidation) ) { (_isW, _rp) = winnerSelfValidation_getWinnerStatus( addr ); return ( _isW, uint32( _rp ) ); } if( algConfig.endingAlgoType == uint8(Lottery.EndingAlgoType.MinedWinnerSelection) ) { (_isW, _rp) = minedSelection_getWinnerStatus( addr ); return ( _isW, uint32( _rp ) ); } } } contract UniLotteryStorageFactory { // The Pool Address. address payable poolAddress; // The Delegate Logic contract, containing all code for // all LotteryStorage contracts to be deployed. address immutable delegateContract; // Pool-Only modifier. modifier poolOnly { require( msg.sender == poolAddress ); _; } // Constructor. // Deploy the Delegate Contract here. // constructor() public { delegateContract = address( new LotteryStorage() ); } // Initialization function. // Set the poolAddress as msg.sender, and lock it. function initialize() external { require( poolAddress == address( 0 ) ); // Set the Pool's Address. poolAddress = msg.sender; } /** * Deploy a new Lottery Storage Stub, to be used by it's corresponding * Lottery Stub, which will be created later, passing this Storage * we create here. * @return newStorage - the Lottery Storage Stub contract just deployed. */ function createNewStorage() public poolOnly returns( address newStorage ) { return address( new LotteryStorageStub( delegateContract ) ); } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a);//, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0);//, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0);//, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view 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 returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0)); require(recipient != address(0)); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0)); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0)); _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)); require(spender != address(0)); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } interface IUniswapPair is IERC20 { // Addresses of the first and second pool-kens. function token0() external view returns (address); function token1() external view returns (address); // Get the pair's token pool reserves. function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); } contract Lottery is ERC20, CoreUniLotterySettings { // ===================== Events ===================== // // After initialize() function finishes. event LotteryInitialized(); // Emitted when lottery active stage ends (Mining Stage starts), // on Mining Stage Step 1, after transferring profits to their // respective owners (pool and OWNER_ADDRESS). event LotteryEnd( uint128 totalReturn, uint128 profitAmount ); // Emitted when on final finish, we call Randomness Provider // to callback us with random value. event RandomnessProviderCalled(); // Requirements for finishing stage start have been reached - // finishing stage has started. event FinishingStageStarted(); // We were currently on the finishing stage, but some requirement // is no longer met. We must stop the finishing stage. event FinishingStageStopped(); // New Referral ID has been generated. event ReferralIDGenerated( address referrer, uint256 id ); // New referral has been registered with a valid referral ID. event ReferralRegistered( address referree, address referrer, uint256 id ); // Fallback funds received. event FallbackEtherReceiver( address sender, uint value ); // ====================== Structs & Enums ====================== // // Lottery Stages. // Described in more detail above, on contract's main doc. enum STAGE { // Initial stage - before the initialize() function is called. INITIAL, // Active Stage: On this stage, all token trading occurs. ACTIVE, // Finishing stage: // This is when all finishing criteria are met, and for every // transfer, we're rolling a pseudo-random number to determine // if we should end the lottery (move to Ending stage). FINISHING, // Ending - Mining Stage: // This stage starts after we lottery is no longer active, // finishing stage ends. On this stage, Miners perform the // Ending Algorithm and other operations. ENDING_MINING, // Lottery is completed - this is set after the Mining Stage ends. // In this stage, Lottery Winners can claim their prizes. COMPLETION, // DISABLED stage. Used when we want a lottery contract to be // absolutely disabled - so no state-modifying functions could // be called. // This is used in DelegateCall scenarios, where state-contract // delegate-calls code contract, to save on deployment costs. DISABLED } // Ending algorithm types enum. enum EndingAlgoType { // 1. Mined Winner Selection Algorithm. // This algorithm is executed by a Lottery Miner in a single // transaction, on Mining Step 2. // // On that single transaction, all ending scores for all // holders are computed, and a sorted winner array is formed, // which is written onto the LotteryStorage state. // Thus, it's gas expensive, and suitable only for small // holder numbers (up to 300). // // Pros: // + Guaranteed deterministically specifiable winner prize // distribution - for example, if we specify that there // must be 2 winners, of which first gets 60% of prize funds, // and second gets 40% of prize funds, then it's // guarateed that prize funds will be distributed just // like that. // // + Low gas cost of prize claims - only ~ 40,000 gas for // claiming a prize. // // Cons: // - Not scaleable - as the Winner Selection Algorithm is // executed in a single transaction, it's limited by // block gas limit - 12,500,000 on the MainNet. // Thus, the lottery is limited to ~300 holders, and // max. ~200 winners of those holders. // So, it's suitable for only express-lotteries, where // a lottery runs only until ~300 holders are reached. // // - High mining costs - if lottery has 300 holders, // mining transaction takes up whole block gas limit. // MinedWinnerSelection, // 2. Winner Self-Validation Algorithm. // // This algorithm does no operations during the Mining Stage // (except for setting up a Random Seed in Lottery Storage) - // the winner selection (obtaining a winner rank) is done by // the winners themselves, when calling the prize claim // functions. // // This algorithm relies on a fact that by the time that // random seed is obtained, all data needed for winner selection // is already there - the holder scores of the Active Stage // (ether contributed, time factors, token balance), and // the Random Data (random seed + nonce (holder's address)), // so, there is no need to compute and sort the scores for the // whole holder array. // // It's done like this: the holder checks if he's a winner, using // a view-function off-chain, and if so, he calls the // claimWinnerPrize() function, which obtains his winner rank // on O(n) time, and does no writing to contract states, // except for prize transfer-related operations. // // When computing the winner's rank on LotteryStorage, // O(n) time is needed, as we loop through the holders array, // computing ending scores for each holder, using already-known // data. // However that means that for every prize claim, all scores of // all holders must be re-computed. // Computing a score for a single holder takes roughly 1500 gas // (400 for 3 slots SLOAD, and ~300 for arithmetic operations). // // So, this algorithm makes prize claims more expensive for // every lottery holder. // If there's 1000 holders, prize claim takes up 1,500,000 gas, // so, this algorithm is not suitable for small prizes, // because gas fee would be higher than the prize amount won. // // Pros: // + Guaranteed deterministically specifiable winner prize // distribution (same as for algorithm 1). // // + No mining costs for winner selection algorithm. // // + More scalable than algorithm 1. // // Cons: // - High gas costs of prize claiming, rising with the number // of lottery holders - 1500 for every lottery holder. // Thus, suitable for only large prize amounts. // WinnerSelfValidation, // 3. Rolled-Randomness algorithm. // // This algorithm is the most cheapest in terms of gas, but // the winner prize distribution is non-deterministic. // // This algorithm doesn't employ miners (no mining costs), // and doesn't require to compute scores for every holder // prior to getting a winner's rank, thus is the most scalable. // // It works like this: a holder checks his winner status by // computing only his own randomized score (rolling a random // number from the random seed, and multiplying it by holder's // Active Stage score), and computing this randomized-score's // ratio relative to maximum available randomized score. // The higher the ratio, the higher the winner rank is. // // However, many players can roll very high or low scores, and // get the same prizes, so it's difficult to make a fair and // efficient deterministic prize distribution mechanism, so // we have to fallback to specific heuristic workarounds. // // Pros: // + Scalable: O(1) complexity for computing a winner rank, // so there can be an unlimited amount of lottery holders, // and gas costs for winner selection and prize claim would // still be constant & low. // // + Gas-efficient: gas costs for all winner-related operations // are constant and low, because only single holder's score // is computed. // // + Doesn't require mining - even more gas savings. // // Cons: // + Hard to make a deterministic and fair prize distribution // mechanism, because of un-known environment - as only // single holder's score is compared to max-available // random score, not taking into account other holder // scores. // RolledRandomness } /** * Gas-efficient, minimal config, which specifies only basic, * most-important and most-used settings. */ struct LotteryConfig { // ================ Misc Settings =============== // // --------- Slot --------- // // Initial lottery funds (initial market cap). // Specified by pool, and is used to check if initial funds // transferred to fallback are correct - equal to this value. uint initialFunds; // --------- Slot --------- // // The minimum ETH value of lottery funds, that, once // reached on an exchange liquidity pool (Uniswap, or our // contract), must be guaranteed to not shrink below this value. // // This is accomplished in _transfer() function, by denying // all sells that would drop the ETH amount in liquidity pool // below this value. // // But on initial lottery stage, before this minimum requirement // is reached for the first time, all sells are allowed. // // This value is expressed in ETH - total amount of ETH funds // that we own in Uniswap liquidity pair. // // So, if initial funds were 10 ETH, and this is set to 100 ETH, // after liquidity pool's ETH value reaches 100 ETH, all further // sells which could drop the liquidity amount below 100 ETH, // would be denied by require'ing in _transfer() function // (transactions would be reverted). // uint128 fundRequirement_denySells; // ETH value of our funds that we own in Uniswap Liquidity Pair, // that's needed to start the Finishing Stage. uint128 finishCriteria_minFunds; // --------- Slot --------- // // Maximum lifetime of a lottery - maximum amount of time // allowed for lottery to stay active. // By default, it's two weeks. // If lottery is still active (hasn't returned funds) after this // time, lottery will stop on the next token transfer. uint32 maxLifetime; // Maximum prize claiming time - for how long the winners // may be able to claim their prizes after lottery ending. uint32 prizeClaimTime; // Token transfer burn rates for buyers, and a default rate for // sells and non-buy-sell transfers. uint32 burn_buyerRate; uint32 burn_defaultRate; // Maximum amount of tokens (in percentage of initial supply) // to be allowed to own by a single wallet. uint32 maxAmountForWallet_percentageOfSupply; // The required amount of time that must pass after // the request to Randomness Provider has been made, for // external actors to be able to initiate alternative // seed generation algorithm. uint32 REQUIRED_TIME_WAITING_FOR_RANDOM_SEED; // ================ Profit Shares =============== // // "Mined Uniswap Lottery" ending Ether funds, which were obtained // by removing token liquidity from Uniswap, are transfered to // these recipient categories: // // 1. The Main Pool: Initial funds, plus Pool's profit share. // 2. The Owner: Owner's profit share. // // 3. The Miners: Miner rewards for executing the winner // selection algorithm stages. // The more holders there are, the more stages the // winner selection algorithm must undergo. // Each Miner, who successfully completed an algorithm // stage, will get ETH reward equal to: // (minerProfitShare / totalAlgorithmStages). // // 4. The Lottery Winners: All remaining funds are given to // Lottery Winners, which were determined by executing // the Winner Selection Algorithm at the end of the lottery // (Miners executed it). // The Winners can claim their prizes by calling a // dedicated function in our contract. // // The profit shares of #1 and #2 have controlled value ranges // specified in CoreUniLotterySettings. // // All these shares are expressed as percentages of the // lottery profit amount (totalReturn - initialFunds). // Percentages are expressed using the PERCENT constant, // defined in CoreUniLotterySettings. // // Here we specify profit shares of Pool, Owner, and the Miners. // Winner Prize Fund is all that's left (must be more than 50% // of all profits). // uint32 poolProfitShare; uint32 ownerProfitShare; // --------- Slot --------- // uint32 minerProfitShare; // =========== Lottery Finish criteria =========== // // Lottery finish by design is a whole soft stage, that // starts when criteria for holders and fund gains are met. // During this stage, for every token transfer, a pseudo-random // number will be rolled for lottery finish, with increasing // probability. // // There are 2 ways that this probability increase is // implemented: // 1. Increasing on every new holder. // 2. Increasing on every transaction after finish stage // was initiated. // // On every new holder, probability increases more than on // new transactions. // // However, if during this stage some criteria become // no-longer-met, the finish stage is cancelled. // This cancel can be implemented by setting finish probability // to zero, or leaving it as it was, but pausing the finishing // stage. // This is controlled by finish_resetProbabilityOnStop flag - // if not set, probability stays the same, when the finishing // stage is discontinued. // ETH value of our funds that we own in Uniswap Liquidity Pair, // that's needed to start the Finishing Stage. // // LOOK ABOVE - arranged for tight-packing. // Minimum number of token holders required to start the // finishing stage. uint32 finishCriteria_minNumberOfHolders; // Minimum amount of time that lottery must be active. uint32 finishCriteria_minTimeActive; // Initial finish probability, when finishing stage was // just initiated. uint32 finish_initialProbability; // Finishing probability increase steps, for every new // transaction and every new holder. // If holder number decreases, probability decreases. uint32 finish_probabilityIncreaseStep_transaction; uint32 finish_probabilityIncreaseStep_holder; // =========== Winner selection config =========== // // Winner selection algorithm settings. // // Algorithm is based on score, which is calculated for // every holder on lottery finish, and is comprised of // the following parts. // Each part is normalized to range ( 0 - scorePoints ), // from smallest to largest value of each holder; // // After scores are computed, they are multiplied by // holder count factor (holderCount / holderCountDivisor), // and finally, multiplied by safely-generated random values, // to get end winning scores. // The top scorers win prizes. // // By default setting, max score is 40 points, and it's // comprised of the following parts: // // 1. Ether contributed (when buying from Uniswap or contract). // Gets added when buying, and subtracted when selling. // Default: 10 points. // // 2. Amount of lottery tokens holder has on finish. // Default: 5 points. // // 3. Ether contributed, multiplied by the relative factor // of time - that is, "now" minus "lotteryStartTime". // This way, late buyers can get more points even if // they get little tokens and don't spend much ether. // Default: 5 points. // // 4. Refferrer bonus. For every player that joined with // your referral ID, you get (that player's score) / 10 // points! This goes up to specified max score. // Also, every player who provides a valid referral ID, // gets 2 points for free! // Default max bonus: 20 points. // int16 maxPlayerScore_etherContributed; int16 maxPlayerScore_tokenHoldingAmount; int16 maxPlayerScore_timeFactor; int16 maxPlayerScore_refferalBonus; // --------- Slot --------- // // Score-To-Random ration data (as a rational ratio number). // For example if 1:5, then scorePart = 1, and randPart = 5. uint16 randRatio_scorePart; uint16 randRatio_randPart; // Time factor divisor - interval of time, in seconds, after // which time factor is increased by one. uint16 timeFactorDivisor; // Bonus score a player should get when registering a valid // referral code obtained from a referrer. int16 playerScore_referralRegisteringBonus; // Are we resetting finish probability when finishing stage // stops, if some criteria are no longer met? bool finish_resetProbabilityOnStop; // =========== Winner Prize Fund Settings =========== // // There are 2 available modes that we can use to distribute // winnings: a computable sequence (geometrical progression), // or an array of winner prize fund share percentages. // More gas efficient is to use a computable sequence, // where each winner gets a share equal to (factor * fundsLeft). // Factor is in range [0.01 - 1.00] - simulated as [1% - 100%]. // // For example: // Winner prize fund is 100 ethers, Factor is 1/4 (25%), and // there are 5 winners total (winnerCount), and sequenced winner // count is 2 (sequencedWinnerCount). // // So, we pre-compute the upper shares, till we arrive to the // sequenced winner count, in a loop: // - Winner 1: 0.25 * 100 = 25 eth; 100 - 25 = 75 eth left. // - Winner 2: 0.25 * 75 ~= 19 eth; 75 - 19 = 56 eth left. // // Now, we compute the left-over winner shares, which are // winners that get their prizes from the funds left after the // sequence winners. // // So, we just divide the leftover funds (56 eth), by 3, // because winnerCount - sequencedWinnerCount = 3. // - Winner 3 = 56 / 3 = 18 eth; // - Winner 4 = 56 / 3 = 18 eth; // - Winner 5 = 56 / 3 = 18 eth; // // If this value is 0, then we'll assume that array-mode is // to be used. uint32 prizeSequenceFactor; // Maximum number of winners that the prize sequence can yield, // plus the leftover winners, which will get equal shares of // the remainder from the first-prize sequence. uint16 prizeSequence_winnerCount; // How many winners would get sequence-computed prizes. // The left-over winners // This is needed because prizes in sequence tend to zero, so // we need to limit the sequence to avoid very small prizes, // and to avoid the remainder. uint16 prizeSequence_sequencedWinnerCount; // Initial token supply (without decimals). uint48 initialTokenSupply; // Ending Algorithm type. // More about the 3 algorithm types above. uint8 endingAlgoType; // --------- Slot --------- // // Array mode: The winner profit share percentages array. // For example, lottery profits can be distributed this way: // // Winner profit shares (8 winners): // [ 20%, 15%, 10%, 5%, 4%, 3%, 2%, 1% ] = 60% of profits. // Owner profits: 10% // Pool profits: 30% // // Pool profit share is not defined explicitly in the config, so // when we internally validate specified profit shares, we // assume the pool share to be the left amount until 100% , // but we also make sure that this amount is at least equal to // MIN_POOL_PROFITS, defined in CoreSettings. // uint32[] winnerProfitShares; } // ========================= Constants ========================= // // The Miner Profits - max/min values. // These aren't defined in Core Settings, because Miner Profits // are only specific to this lottery type. uint32 constant MIN_MINER_PROFITS = 1 * PERCENT; uint32 constant MAX_MINER_PROFITS = 10 * PERCENT; // Uniswap Router V2 contract instance. // Address is the same for MainNet, and all public testnets. IUniswapRouter constant uniswapRouter = IUniswapRouter( address( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ) ); // Public-accessible ERC20 token specific constants. string constant public name = "UniLottery Token"; string constant public symbol = "ULT"; uint256 constant public decimals = 18; // =================== State Variables =================== // // ------- Initial Slots ------- // // The config which is passed to constructor. LotteryConfig internal cfg; // ------- Slot ------- // // The Lottery Storage contract, which stores all holder data, // such as scores, referral tree data, etc. LotteryStorage public lotStorage; // ------- Slot ------- // // Pool address. Set on constructor from msg.sender. address payable public poolAddress; // ------- Slot ------- // // Randomness Provider address. address public randomnessProvider; // ------- Slot ------- // // Exchange address. In Uniswap mode, it's the Uniswap liquidity // pair's address, where trades execute. address public exchangeAddress; // Start date. uint32 public startDate; // Completion (Mining Phase End) date. uint32 public completionDate; // The date when Randomness Provider was called, requesting a // random seed for the lottery finish. // Also, when this variable becomes Non-Zero, it indicates that we're // on Ending Stage Part One: waiting for the random seed. uint32 finish_timeRandomSeedRequested; // ------- Slot ------- // // WETH address. Set by calling Router's getter, on constructor. address WETHaddress; // Is the WETH first or second token in our Uniswap Pair? bool uniswap_ethFirst; // If we are, or were before, on finishing stage, this is the // probability of lottery going to Ending Stage on this transaction. uint32 finishProbablity; // Re-Entrancy Lock (Mutex). // We protect for reentrancy in the Fund Transfer functions. bool reEntrancyMutexLocked; // On which stage we are currently. uint8 public lotteryStage; // Indicator for whether the lottery fund gains have passed a // minimum fund gain requirement. // After that time point (when this bool is set), the token sells // which could drop the fund value below the requirement, would // be denied. bool fundGainRequirementReached; // The current step of the Mining Stage. uint16 miningStep; // If we're currently on Special Transfer Mode - that is, we allow // direct transfers between parties even in NON-ACTIVE state. bool specialTransferModeEnabled; // ------- Slot ------- // // Per-Transaction Pseudo-Random hash value (transferHashValue). // This value is computed on every token transfer, by keccak'ing // the last (current) transferHashValue, msg.sender, now, and // transaction count. // // This is used on Finishing Stage, as a pseudo-random number, // which is used to check if we should end the lottery (move to // Ending Stage). uint256 transferHashValue; // ------- Slot ------- // // On lottery end, get & store the lottery total ETH return // (including initial funds), and profit amount. uint128 public ending_totalReturn; uint128 public ending_profitAmount; // ------- Slot ------- // // The mapping that contains TRUE for addresses that already claimed // their lottery winner prizes. // Used only in COMPLETION, on claimWinnerPrize(), to check if // msg.sender has already claimed his prize. mapping( address => bool ) public prizeClaimersAddresses; // ============= Private/internal functions ============= // // Pool Only modifier. modifier poolOnly { require( msg.sender == poolAddress ); _; } // Only randomness provider allowed modifier. modifier randomnessProviderOnly { require( msg.sender == randomnessProvider ); _; } // Execute function only on specific lottery stage. modifier onlyOnStage( STAGE _stage ) { require( lotteryStage == uint8( _stage ) ); _; } // Modifier for protecting the function from re-entrant calls, // by using a locked Re-Entrancy Lock (Mutex). modifier mutexLOCKED { require( ! reEntrancyMutexLocked ); reEntrancyMutexLocked = true; _; reEntrancyMutexLocked = false; } // Check if we're currently on a specific stage. function onStage( STAGE _stage ) internal view returns( bool ) { return ( lotteryStage == uint8( _stage ) ); } /** * Check if token transfer to specific wallet won't exceed * maximum token amount allowed to own by a single wallet. * * @return true, if holder's balance with "amount" added, * would exceed the max allowed single holder's balance * (by default, that is 5% of total supply). */ function transferExceedsMaxBalance( address holder, uint amount ) internal view returns( bool ) { uint maxAllowedBalance = ( totalSupply() * cfg.maxAmountForWallet_percentageOfSupply ) / ( _100PERCENT ); return ( ( balanceOf( holder ) + amount ) > maxAllowedBalance ); } /** * Update holder data. * This function is called by _transfer() function, just before * transfering final amount of tokens directly from sender to * receiver. * At this point, all burns/mints have been done, and we're sure * that this transfer is valid and must be successful. * * In all modes, this function is used to update the holder array. * * However, on external exchange modes (e.g. on Uniswap mode), * it is also used to track buy/sell ether value, to update holder * scores, when token buys/sells cannot be tracked directly. * * If, however, we use Standalone mode, we are the exchange, * so on _transfer() we already know the ether value, which is * set to currentBuySellEtherValue variable. * * @param amountSent - the token amount that is deducted from * sender's balance. This includes burn, and owner fee. * * @param amountReceived - the token amount that receiver * actually receives, after burns and fees. * * @return holderCountChanged - indicates whether holder count * changes during this transfer - new holder joins or leaves * (true), or no change occurs (false). */ function updateHolderData_preTransfer( address sender, address receiver, uint256 amountSent, uint256 amountReceived ) internal returns( bool holderCountChanged ) { // Update holder array, if new token holder joined, or if // a holder transfered his whole balance. holderCountChanged = false; // Sender transferred his whole balance - no longer a holder. if( balanceOf( sender ) == amountSent ) { lotStorage.removeHolder( sender ); holderCountChanged = true; } // Receiver didn't have any tokens before - add it to holders. if( balanceOf( receiver ) == 0 && amountReceived > 0 ) { lotStorage.addHolder( receiver ); holderCountChanged = true; } // Update holder score factors: if buy/sell occured, update // etherContributed and timeFactors scores, // and also propagate the scores through the referral chain // to the parent referrers (this is done in Storage contract). // This lottery operates only on external exchange (Uniswap) // mode, so we have to find out the buy/sell Ether value by // calling the external exchange (Uniswap pair) contract. // Temporary variable to store current transfer's buy/sell // value in Ethers. int buySellValue; // Sender is an exchange - buy detected. if( sender == exchangeAddress && receiver != exchangeAddress ) { // Use the Router's functionality. // Set the exchange path to WETH -> ULT // (ULT is Lottery Token, and it's address is our address). address[] memory path = new address[]( 2 ); path[ 0 ] = WETHaddress; path[ 1 ] = address(this); uint[] memory ethAmountIn = uniswapRouter.getAmountsIn( amountSent, // uint amountOut, path // address[] path ); buySellValue = int( ethAmountIn[ 0 ] ); // Compute time factor value for the current ether value. // buySellValue is POSITIVE. // When computing Time Factors, leave only 6 ether decimals. int timeFactorValue = ( buySellValue / (10 ** 12) ) * int( (now - startDate) / cfg.timeFactorDivisor ); // Update and propagate the buyer (receiver) scores. lotStorage.updateAndPropagateScoreChanges( receiver, int80( buySellValue ), int80( timeFactorValue ), int80( amountReceived ) ); } // Receiver is an exchange - sell detected. else if( sender != exchangeAddress && receiver == exchangeAddress ) { // Use the Router's functionality. // Set the exchange path to ULT -> WETH // (ULT is Lottery Token, and it's address is our address). address[] memory path = new address[]( 2 ); path[ 0 ] = address(this); path[ 1 ] = WETHaddress; uint[] memory ethAmountOut = uniswapRouter.getAmountsOut( amountReceived, // uint amountIn path // address[] path ); // It's a sell (ULT -> WETH), so set value to NEGATIVE. buySellValue = int( -1 ) * int( ethAmountOut[ 1 ] ); // Compute time factor value for the current ether value. // buySellValue is NEGATIVE. int timeFactorValue = ( buySellValue / (10 ** 12) ) * int( (now - startDate) / cfg.timeFactorDivisor ); // Update and propagate the seller (sender) scores. lotStorage.updateAndPropagateScoreChanges( sender, int80( buySellValue ), int80( timeFactorValue ), -1 * int80( amountSent ) ); } // Neither Sender nor Receiver are exchanges - default transfer. // Tokens just got transfered between wallets, without // exchanging for ETH - so etherContributed_change = 0. // On this case, update both sender's & receiver's scores. // else { buySellValue = 0; lotStorage.updateAndPropagateScoreChanges( sender, 0, 0, -1 * int80( amountSent ) ); lotStorage.updateAndPropagateScoreChanges( receiver, 0, 0, int80( amountReceived ) ); } // Check if lottery liquidity pool funds have already // reached a minimum required ETH value. uint ethFunds = getCurrentEthFunds(); if( !fundGainRequirementReached && ethFunds >= cfg.fundRequirement_denySells ) { fundGainRequirementReached = true; } // Check whether this token transfer is allowed if it's a sell // (if buySellValue is negative): // // If we've already reached the minimum fund gain requirement, // and this sell would shrink lottery liquidity pool's ETH funds // below this requirement, then deny this sell, causing this // transaction to fail. if( fundGainRequirementReached && buySellValue < 0 && ( uint( -1 * buySellValue ) >= ethFunds || ethFunds - uint( -1 * buySellValue ) < cfg.fundRequirement_denySells ) ) { require( false ); } } /** * Check for finishing stage start conditions. * - If some conditions are met, start finishing stage! * Do it by setting "onFinishingStage" bool. * - If we're currently on finishing stage, and some condition * is no longer met, then stop the finishing stage. */ function checkFinishingStageConditions() internal { // Firstly, check if lottery hasn't exceeded it's maximum lifetime. // If so, don't check anymore, just set finishing stage, and // end the lottery on further call of checkForEnding(). if( (now - startDate) > cfg.maxLifetime ) { lotteryStage = uint8( STAGE.FINISHING ); return; } // Compute & check the finishing criteria. // Notice that we adjust the config-specified fund gain // percentage increase to uint-mode, by adding 100 percents, // because we don't deal with negative percentages, and here // we represent loss as a percentage below 100%, and gains // as percentage above 100%. // So, if in regular gains notation, it's said 10% gain, // in uint mode, it's said 110% relative increase. // // (Also, remember that losses are impossible in our lottery // working scheme). if( lotStorage.getHolderCount() >= cfg.finishCriteria_minNumberOfHolders && getCurrentEthFunds() >= cfg.finishCriteria_minFunds && (now - startDate) >= cfg.finishCriteria_minTimeActive ) { if( onStage( STAGE.ACTIVE ) ) { // All conditions are met - start the finishing stage. lotteryStage = uint8( STAGE.FINISHING ); emit FinishingStageStarted(); } } else if( onStage( STAGE.FINISHING ) ) { // However, what if some condition was not met, but we're // already on the finishing stage? // If so, we must stop the finishing stage. // But what to do with the finishing probability? // Config specifies if it should be reset or maintain it's // value until the next time finishing stage is started. lotteryStage = uint8( STAGE.ACTIVE ); if( cfg.finish_resetProbabilityOnStop ) finishProbablity = cfg.finish_initialProbability; emit FinishingStageStopped(); } } /** * We're currently on finishing stage - so let's check if * we should end the lottery now! * * This function is called from _transfer(), only if we're sure * that we're currently on finishing stage (onFinishingStage * variable is set). * * Here, we compute the pseudo-random number from hash of * current message's sender, now, and other values, * and modulo it to the current finish probability. * If it's equal to 1, then we end the lottery! * * Also, here we update the finish probability according to * probability update criteria - holder count, and tx count. * * @param holderCountChanged - indicates whether Holder Count * has changed during this transfer (new holder joined, or * a holder sold all his tokens). */ function checkForEnding( bool holderCountChanged ) internal { // At first, check if lottery max lifetime is exceeded. // If so, start ending procedures right now. if( (now - startDate) > cfg.maxLifetime ) { startEndingStage(); return; } // Now, we know that lottery lifetime is still OK, and we're // currently on Finishing Stage (because this function is // called only when onFinishingStage is set). // // Now, check if we should End the lottery, by computing // a modulo on a pseudo-random number, which is a transfer // hash, computed for every transfer on _transfer() function. // // Get the modulo amount according to current finish // probability. // We use precision of 0.01% - notice the "10000 *" before // 100 PERCENT. // Later, when modulo'ing, we'll check if value is below 10000. // uint prec = 10000; uint modAmount = (prec * _100PERCENT) / finishProbablity; if( ( transferHashValue % modAmount ) <= prec ) { // Finish probability is met! Commence lottery end - // start Ending Stage. startEndingStage(); return; } // Finish probability wasn't met. // Update the finish probability, by increasing it! // Transaction count criteria. // As we know that this function is called on every new // transfer (transaction), we don't check if transactionCount // increased or not - we just perform probability update. finishProbablity += cfg.finish_probabilityIncreaseStep_transaction; // Now, perform holder count criteria update. // Finish probability increases, no matter if holder count // increases or decreases. if( holderCountChanged ) finishProbablity += cfg.finish_probabilityIncreaseStep_holder; } /** * Start the Ending Stage, by De-Activating the lottery, * to deny all further token transfers (excluding the one when * removing liquidity from Uniswap), and transition into the * Mining Phase - set the lotteryStage to MINING. */ function startEndingStage() internal { lotteryStage = uint8( STAGE.ENDING_MINING ); } /** * Execute the first step of the Mining Stage - request a * Random Seed from the Randomness Provider. * * Here, we call the Randomness Provider, asking for a true random seed * to be passed to us into our callback, named * "finish_randomnessProviderCallback()". * * When that callback will be called, our storage's random seed will * be set, and we'll be able to start the Ending Algorithm on * further mining steps. * * Notice that Randomness Provider must already be funded, to * have enough Ether for Provable fee and the gas costs of our * callback function, which are quite high, because of winner * selection algorithm, which is computationally expensive. * * The Randomness Provider is always funded by the Pool, * right before the Pool deploys and starts a new lottery, so * as every lottery calls the Randomness Provider only once, * the one-call-fund method for every lottery is sufficient. * * Also notice, that Randomness Provider might fail to call * our callback due to some unknown reasons! * Then, the lottery profits could stay locked in this * lottery contract forever ?!! * * No! We've thought about that - we've implemented the * Alternative Ending mechanism, where, if specific time passes * after we've made a request to Randomness Provider, and * callback hasn't been called yet, we allow external actor to * execute the Alternative ending, which basically does the * same things as the default ending, just that the Random Seed * will be computed locally in our contract, using the * Pseudo-Random mechanism, which could compute a reasonably * fair and safe value using data from holder array, and other * values, described in more detail on corresponding function's * description. */ function mine_requestRandomSeed() internal { // We're sure that the Randomness Provider has enough funds. // Execute the random request, and get ready for Ending Algorithm. IRandomnessProvider( randomnessProvider ) .requestRandomSeedForLotteryFinish(); // Store the time when random seed has been requested, to // be able to alternatively handle the lottery finish, if // randomness provider doesn't call our callback for some // reason. finish_timeRandomSeedRequested = uint32( now ); // Emit appropriate events. emit RandomnessProviderCalled(); } /** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> * * Transfer the Owner & Pool profit shares, when lottery ends. * This function is the first one that's executed on the Mining * Stage. * This is the first step of Mining. So, the Miner who executes this * function gets the mining reward. * * This function's job is to Gather the Profits & Initial Funds, * and Transfer them to Profiters - that is, to The Pool, and * to The Owner. * * The Miners' profit share and Winner Prize Fund stay in this * contract. * * On this function, we (in this order): * * 1. Remove all liquidity from Uniswap (if using Uniswap Mode), * pulling it to our contract's wallet. * * 2. Transfer the Owner and the Pool ETH profit shares to * Owner and Pool addresses. * * * This function transfers Ether out of our contract: * - We transfer the Profits to Pool and Owner addresses. */ function mine_removeUniswapLiquidityAndTransferProfits() internal mutexLOCKED { // We've already approved our token allowance to Router. // Now, approve Uniswap liquidity token's Router allowance. ERC20( exchangeAddress ).approve( address(uniswapRouter), uint(-1) ); // Enable the SPECIAL-TRANSFER mode, to allow Uniswap to transfer // the tokens from Pair to Router, and then from Router to us. specialTransferModeEnabled = true; // Remove liquidity! uint amountETH = uniswapRouter .removeLiquidityETHSupportingFeeOnTransferTokens( address(this), // address token, ERC20( exchangeAddress ).balanceOf( address(this) ), 0, // uint amountTokenMin, 0, // uint amountETHMin, address(this), // address to, (now + 10000000) // uint deadline ); // Tokens are transfered. Disable the special transfer mode. specialTransferModeEnabled = false; // Check that we've got a correct amount of ETH. require( address(this).balance >= amountETH && address(this).balance >= cfg.initialFunds ); // Compute the Profit Amount (current balance - initial funds). ending_totalReturn = uint128( address(this).balance ); ending_profitAmount = ending_totalReturn - uint128( cfg.initialFunds ); // Compute, and Transfer Owner's profit share and // Pool's profit share to their respective addresses. uint poolShare = ( ending_profitAmount * cfg.poolProfitShare ) / ( _100PERCENT ); uint ownerShare = ( ending_profitAmount * cfg.ownerProfitShare ) / ( _100PERCENT ); // To pool, transfer it's profit share plus initial funds. IUniLotteryPool( poolAddress ).lotteryFinish { value: poolShare + cfg.initialFunds } ( ending_totalReturn, ending_profitAmount ); // Transfer Owner's profit share. OWNER_ADDRESS.transfer( ownerShare ); // Emit ending event. emit LotteryEnd( ending_totalReturn, ending_profitAmount ); } /** * Executes a single step of the Winner Selection Algorithm * (the Ending Algorithm). * The algorithm itself is being executed in the Storage contract. * * On current design, whole algorithm is executed in a single step. * * This function is executed only in the Mining stage, and * accounts for most of the gas spent during mining. */ function mine_executeEndingAlgorithmStep() internal { // Launch the winner algorithm, to execute the next step. lotStorage.executeWinnerSelectionAlgorithm(); } // =============== Public functions =============== // /** * Constructor of this delegate code contract. * Here, we set OUR STORAGE's lotteryStage to DISABLED, because * we don't want anybody to call this contract directly. */ constructor() public { lotteryStage = uint8( STAGE.DISABLED ); } /** * Construct the lottery contract which is delegating it's * call to us. * * @param config - LotteryConfig structure to use in this lottery. * * Future approach: ABI-encoded Lottery Config * (different implementations might use different config * structures, which are ABI-decoded inside the implementation). * * Also, this "config" includes the ABI-encoded temporary values, * which are not part of persisted LotteryConfig, but should * be used only in constructor - for example, values to be * assigned to storage variables, such as ERC20 token's * name, symbol, and decimals. * * @param _poolAddress - Address of the Main UniLottery Pool, which * provides initial funds, and receives it's profit share. * * @param _randomProviderAddress - Address of a Randomness Provider, * to use for obtaining random seeds. * * @param _storageAddress - Address of a Lottery Storage. * Storage contract is a separate contract which holds all * lottery token holder data, such as intermediate scores. * */ function construct( LotteryConfig memory config, address payable _poolAddress, address _randomProviderAddress, address _storageAddress ) external { // Check if contract wasn't already constructed! require( poolAddress == address( 0 ) ); // Set the Pool's Address - notice that it's not the // msg.sender, because lotteries aren't created directly // by the Pool, but by the Lottery Factory! poolAddress = _poolAddress; // Set the Randomness Provider address. randomnessProvider = _randomProviderAddress; // Check the minimum & maximum requirements for config // profit & lifetime parameters. require( config.maxLifetime <= MAX_LOTTERY_LIFETIME ); require( config.poolProfitShare >= MIN_POOL_PROFITS && config.poolProfitShare <= MAX_POOL_PROFITS ); require( config.ownerProfitShare >= MIN_OWNER_PROFITS && config.ownerProfitShare <= MAX_OWNER_PROFITS ); require( config.minerProfitShare >= MIN_MINER_PROFITS && config.minerProfitShare <= MAX_MINER_PROFITS ); // Check if winner profit share is good. uint32 totalWinnerShare = (_100PERCENT) - config.poolProfitShare - config.ownerProfitShare - config.minerProfitShare; require( totalWinnerShare >= MIN_WINNER_PROFIT_SHARE ); // Check if ending algorithm params are good. require( config.randRatio_scorePart != 0 && config.randRatio_randPart != 0 && ( config.randRatio_scorePart + config.randRatio_randPart ) < 10000 ); require( config.endingAlgoType == uint8( EndingAlgoType.MinedWinnerSelection ) || config.endingAlgoType == uint8( EndingAlgoType.WinnerSelfValidation ) || config.endingAlgoType == uint8( EndingAlgoType.RolledRandomness ) ); // Set the number of winners (winner count). // If using Computed Sequence winner prize shares, set that // value, and if it's zero, then we're using the Array-Mode // prize share specification. if( config.prizeSequence_winnerCount == 0 && config.winnerProfitShares.length != 0 ) config.prizeSequence_winnerCount = uint16( config.winnerProfitShares.length ); // Setup our Lottery Storage - initialize, and set the // Algorithm Config. LotteryStorage _lotStorage = LotteryStorage( _storageAddress ); // Setup a Winner Score Config for the winner selection algo, // to be used in the Lottery Storage. LotteryStorage.WinnerAlgorithmConfig memory winnerConfig; // Algorithm type. winnerConfig.endingAlgoType = config.endingAlgoType; // Individual player max score parts. winnerConfig.maxPlayerScore_etherContributed = config.maxPlayerScore_etherContributed; winnerConfig.maxPlayerScore_tokenHoldingAmount = config.maxPlayerScore_tokenHoldingAmount; winnerConfig.maxPlayerScore_timeFactor = config.maxPlayerScore_timeFactor; winnerConfig.maxPlayerScore_refferalBonus = config.maxPlayerScore_refferalBonus; // Score-To-Random ratio parts. winnerConfig.randRatio_scorePart = config.randRatio_scorePart; winnerConfig.randRatio_randPart = config.randRatio_randPart; // Set winner count (no.of winners). winnerConfig.winnerCount = config.prizeSequence_winnerCount; // Initialize the storage (bind it to our contract). _lotStorage.initialize( winnerConfig ); // Set our immutable variable. lotStorage = _lotStorage; // Now, set our config to the passed config. cfg = config; // Might be un-needed (can be replaced by Constant on the MainNet): WETHaddress = uniswapRouter.WETH(); } /** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<< * * Fallback Receive Ether function. * Used to receive ETH funds back from Uniswap, on lottery's end, * when removing liquidity. */ receive() external payable { emit FallbackEtherReceiver( msg.sender, msg.value ); } /** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<< * PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>> * * Initialization function. * Here, the most important startup operations are made - * such as minting initial token supply and transfering it to * the Uniswap liquidity pair, in exchange for UNI-v2 tokens. * * This function is called by the pool, when transfering * initial funds to this contract. * * What's payable? * - Pool transfers initial funds to our contract. * - We transfer that initial fund Ether to Uniswap liquidity pair * when creating/providing it. */ function initialize() external payable poolOnly mutexLOCKED onlyOnStage( STAGE.INITIAL ) { // Check if pool transfered correct amount of funds. require( address( this ).balance == cfg.initialFunds ); // Set start date. startDate = uint32( now ); // Set the initial transfer hash value. transferHashValue = uint( keccak256( abi.encodePacked( msg.sender, now ) ) ); // Set initial finish probability, to be used when finishing // stage starts. finishProbablity = cfg.finish_initialProbability; // ===== Active operations - mint & distribute! ===== // // Mint full initial supply of tokens to our contract address! _mint( address(this), uint( cfg.initialTokenSupply ) * (10 ** decimals) ); // Now - prepare to create a new Uniswap Liquidity Pair, // with whole our total token supply and initial funds ETH // as the two liquidity reserves. // Approve Uniswap Router to allow it to spend our tokens. // Set maximum amount available. _approve( address(this), address( uniswapRouter ), uint(-1) ); // Provide liquidity - the Router will automatically // create a new Pair. uniswapRouter.addLiquidityETH { value: address(this).balance } ( address(this), // address token, totalSupply(), // uint amountTokenDesired, totalSupply(), // uint amountTokenMin, address(this).balance, // uint amountETHMin, address(this), // address to, (now + 1000) // uint deadline ); // Get the Pair address - that will be the exchange address. exchangeAddress = IUniswapFactory( uniswapRouter.factory() ) .getPair( WETHaddress, address(this) ); // We assume that the token reserves of the pair are good, // and that we own the full amount of liquidity tokens. // Find out which of the pair tokens is WETH - is it the // first or second one. Use it later, when getting our share. if( IUniswapPair( exchangeAddress ).token0() == WETHaddress ) uniswap_ethFirst = true; else uniswap_ethFirst = false; // Move to ACTIVE lottery stage. // Now, all token transfers will be allowed. lotteryStage = uint8( STAGE.ACTIVE ); // Lottery is initialized. We're ready to emit event. emit LotteryInitialized(); } // Return this lottery's initial funds, as were specified in the config. // function getInitialFunds() external view returns( uint ) { return cfg.initialFunds; } // Return active (still not returned to pool) initial fund value. // If no-longer-active, return 0 (default) - because funds were // already returned back to the pool. // function getActiveInitialFunds() external view returns( uint ) { if( onStage( STAGE.ACTIVE ) ) return cfg.initialFunds; return 0; } /** * Get current Exchange's Token and ETH reserves. * We're on Uniswap mode, so get reserves from Uniswap. */ function getReserves() external view returns( uint _ethReserve, uint _tokenReserve ) { // Use data from Uniswap pair contract. ( uint112 res0, uint112 res1, ) = IUniswapPair( exchangeAddress ).getReserves(); if( uniswap_ethFirst ) return ( res0, res1 ); else return ( res1, res0 ); } /** * Get our share (ETH amount) of the Uniswap Pair ETH reserve, * of our Lottery tokens ULT-WETH liquidity pair. */ function getCurrentEthFunds() public view returns( uint ethAmount ) { IUniswapPair pair = IUniswapPair( exchangeAddress ); ( uint112 res0, uint112 res1, ) = pair.getReserves(); uint resEth = uint( uniswap_ethFirst ? res0 : res1 ); // Compute our amount of the ETH reserve, based on our // percentage of our liquidity token balance to total supply. uint liqTokenPercentage = ( pair.balanceOf( address(this) ) * (_100PERCENT) ) / ( pair.totalSupply() ); // Compute and return the ETH reserve. return ( resEth * liqTokenPercentage ) / (_100PERCENT); } /** * Get current finish probability. * If it's ACTIVE stage, return 0 automatically. */ function getFinishProbability() external view returns( uint32 ) { if( onStage( STAGE.FINISHING ) ) return finishProbablity; return 0; } /** * Generate a referral ID for msg.sender, who must be a token holder. * Referral ID is used to refer other wallets into playing our * lottery. * - Referrer gets bonus points for every wallet that bought * lottery tokens and specified his referral ID. * - Referrees (wallets who got referred by registering a valid * referral ID, corresponding to some referrer), get some * bonus points for specifying (registering) a referral ID. * * Referral ID is a uint256 number, which is generated by * keccak256'ing the holder's address, holder's current * token ballance, and current time. */ function generateReferralID() external onlyOnStage( STAGE.ACTIVE ) { uint256 refID = lotStorage.generateReferralID( msg.sender ); // Emit approppriate events. emit ReferralIDGenerated( msg.sender, refID ); } /** * Register a referral for a msg.sender (must be token holder), * using a valid referral ID got from a referrer. * This function is called by a referree, who obtained a * valid referral ID from some referrer, who previously * generated it using generateReferralID(). * * You can only register a referral once! * When you do so, you get bonus referral points! */ function registerReferral( uint256 referralID ) external onlyOnStage( STAGE.ACTIVE ) { address referrer = lotStorage.registerReferral( msg.sender, cfg.playerScore_referralRegisteringBonus, referralID ); // Emit approppriate events. emit ReferralRegistered( msg.sender, referrer, referralID ); } /** * The most important function of this contract - Transfer Function. * * Here, all token burning, intermediate score tracking, and * finish condition checking is performed, according to the * properties specified in config. */ function _transfer( address sender, address receiver, uint256 amount ) internal override { // Check if transfers are allowed in current state. // On Non-Active stage, transfers are allowed only from/to // our contract. // As we don't have Standalone Mode on this lottery variation, // that means that tokens to/from our contract are travelling // only when we transfer them to Uniswap Pair, and when // Uniswap transfers them back to us, on liquidity remove. // // On this state, we also don't perform any burns nor // holding trackings - just transfer and return. if( !onStage( STAGE.ACTIVE ) && !onStage( STAGE.FINISHING ) && ( sender == address(this) || receiver == address(this) || specialTransferModeEnabled ) ) { super._transfer( sender, receiver, amount ); return; } // Now, we know that we're NOT on special mode. // Perform standard checks & brecks. require( ( onStage( STAGE.ACTIVE ) || onStage( STAGE.FINISHING ) ) ); // Can't transfer zero tokens, or use address(0) as sender. require( amount != 0 && sender != address(0) ); // Compute the Burn Amount - if buying tokens from an exchange, // we use a lower burn rate - to incentivize buying! // Otherwise (if selling or just transfering between wallets), // we use a higher burn rate. uint burnAmount; // It's a buy - sender is an exchange. if( sender == exchangeAddress ) burnAmount = ( amount * cfg.burn_buyerRate ) / (_100PERCENT); else burnAmount = ( amount * cfg.burn_defaultRate ) / (_100PERCENT); // Now, compute the final amount to be gotten by the receiver. uint finalAmount = amount - burnAmount; // Check if receiver's balance won't exceed the max-allowed! // Receiver must not be an exchange. if( receiver != exchangeAddress ) { require( !transferExceedsMaxBalance( receiver, finalAmount ) ); } // Now, update holder data array accordingly. bool holderCountChanged = updateHolderData_preTransfer( sender, receiver, amount, // Amount Sent (Pre-Fees) finalAmount // Amount Received (Post-Fees). ); // All is ok - perform the burn and token transfers now. // Burn token amount from sender's balance. super._burn( sender, burnAmount ); // Finally, transfer the final amount from sender to receiver. super._transfer( sender, receiver, finalAmount ); // Compute new Pseudo-Random transfer hash, which must be // computed for every transfer, and is used in the // Finishing Stage as a pseudo-random unique value for // every transfer, by which we determine whether lottery // should end on this transfer. // // Compute it like this: keccak the last (current) // transferHashValue, msg.sender, sender, receiver, amount. transferHashValue = uint( keccak256( abi.encodePacked( transferHashValue, msg.sender, sender, receiver, amount ) ) ); // Check if we should be starting a finishing stage now. checkFinishingStageConditions(); // If we're on finishing stage, check for ending conditions. // If ending check is satisfied, the checkForEnding() function // starts ending operations. if( onStage( STAGE.FINISHING ) ) checkForEnding( holderCountChanged ); } /** * Callback function, which is called from Randomness Provider, * after it obtains a random seed to be passed to us, after * we have initiated The Ending Stage, on which random seed * is used to generate random factors for Winner Selection * algorithm. */ function finish_randomnessProviderCallback( uint256 randomSeed, uint256 /*callID*/ ) external randomnessProviderOnly { // Set the random seed in the Storage Contract. lotStorage.setRandomSeed( randomSeed ); // If algo-type is not Mined Winner Selection, then by now // we assume lottery as COMPL3T3D. if( cfg.endingAlgoType != uint8(EndingAlgoType.MinedWinnerSelection) ) { lotteryStage = uint8( STAGE.COMPLETION ); completionDate = uint32( now ); } } /** * Function checks if we can initiate Alternative Seed generation. * * Alternative approach to Lottery Random Seed is used only when * Randomness Provider doesn't work, and doesn't call the * above callback. * * This alternative approach can be initiated by Miners, when * these conditions are met: * - Lottery is on Ending (Mining) stage. * - Request to Randomness Provider was made at least X time ago, * and our callback hasn't been called yet. * * If these conditions are met, we can initiate the Alternative * Random Seed generation, which generates a seed based on our * state. */ function alternativeSeedGenerationPossible() internal view returns( bool ) { return ( onStage( STAGE.ENDING_MINING ) && ( (now - finish_timeRandomSeedRequested) > cfg.REQUIRED_TIME_WAITING_FOR_RANDOM_SEED ) ); } /** * Return this lottery's config, using ABIEncoderV2. */ /*function getLotteryConfig() external view returns( LotteryConfig memory ourConfig ) { return cfg; }*/ /** * Checks if Mining is currently available. */ function isMiningAvailable() external view returns( bool ) { return onStage( STAGE.ENDING_MINING ) && ( miningStep == 0 || ( miningStep == 1 && ( lotStorage.getRandomSeed() != 0 || alternativeSeedGenerationPossible() ) ) ); } /** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> * * Mining function, to be executed on Ending (Mining) stage. * * "Mining" approach is used in this lottery, to use external * actors for executing the gas-expensive Ending Algorithm, * and other ending operations, such as profit transfers. * * "Miners" can be any external actors who call this function. * When Miner successfully completes a Mining Step, he gets * a Mining Reward, which is a certain portion of lottery's profit * share, dedicated to Miners. * * NOT-IMPLEMENTED APPROACH: * * All these operations are divided into "mining steps", which are * smaller components, which fit into reasonable gas limits. * All "steps" are designed to take up similar amount of gas. * * For example, if total lottery profits (total ETH got from * pulling liquidity out of Uniswap, minus initial funds), * is 100 ETH, Miner Profit Share is 10%, and there are 5 mining * steps total, then for a singe step executed, miner will get: * * (100 * 0.1) / 5 = 2 ETH. * * --------------------------------- * * CURRENTLY IMPLEMENTED APPROACH: * * As the above-defined approach would consume very much gas for * inter-step intermediate state storage, we have thought that * for now, it's better to have only 2 mining steps, the second of * which performs the whole Winner Selection Algorithm. * * This is because performing the whole algorithm at once would save * us up to 10x more gas in total, than executing it in steps. * * However, this solution is not scalable, because algorithm has * to fit into block gas limit (10,000,000 gas), so we are limited * to a certain safe maximum number of token holders, which is * empirically determined during testing, and defined in the * MAX_SAFE_NUMBER_OF_HOLDERS constant, which is checked against the * config value "finishCriteria_minNumberOfHolders" in constructor. * * So, in this approach, there are only 2 mining steps: * * 1. Remove liquidity from Uniswap, transfer profit shares to * the Pool and the Owner Address, and request Random Seed * from the Randomness Provider. * Reward: 25% of total Mining Rewards. * * 2. Perform the whole Winner Selection Algorithm inside the * Lottery Storage contract. * Reward: 75% of total Mining Rewards. * * * Function transfers Ether out of our contract: * - Transfers the current miner's reward to msg.sender. */ function mine() external onlyOnStage( STAGE.ENDING_MINING ) { uint currentStepReward; // Perform different operations on different mining steps. // Step 0: Remove liquidity from Uniswap, transfer profits to // Pool and Owner addresses. Also, request a Random Seed // from the Randomness Provider. if( miningStep == 0 ) { mine_requestRandomSeed(); mine_removeUniswapLiquidityAndTransferProfits(); // Compute total miner reward amount, then compute this // step's reward later. uint totalMinerRewards = ( ending_profitAmount * cfg.minerProfitShare ) / ( _100PERCENT ); // Step 0 reward is 10% for Algo type 1. if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) ) { currentStepReward = ( totalMinerRewards * (10 * PERCENT) ) / ( _100PERCENT ); } // If other algo-types, second step is not normally needed, // so here we take 80% of miner rewards. // If Randomness Provider won't give us a seed after // specific amount of time, we'll initiate a second step, // with remaining 20% of miner rewords. else { currentStepReward = ( totalMinerRewards * (80 * PERCENT) ) / ( _100PERCENT ); } require( currentStepReward <= totalMinerRewards ); } // Step 1: // If we use MinedWinnerSelection algo-type, then execute the // winner selection algorithm. // Otherwise, check if Random Provider hasn't given us a // random seed long enough, so that we have to generate a // seed locally. else { // Check if we can go into this step when using specific // ending algorithm types. if( cfg.endingAlgoType != uint8(EndingAlgoType.MinedWinnerSelection) ) { require( lotStorage.getRandomSeed() == 0 && alternativeSeedGenerationPossible() ); } // Compute total miner reward amount, then compute this // step's reward later. uint totalMinerRewards = ( ending_profitAmount * cfg.minerProfitShare ) / ( _100PERCENT ); // Firstly, check if random seed is already obtained. // If not, check if we should generate it locally. if( lotStorage.getRandomSeed() == 0 ) { if( alternativeSeedGenerationPossible() ) { // Set random seed inside the Storage Contract, // but using our contract's transferHashValue as the // random seed. // We believe that this hash has enough randomness // to be considered a fairly good random seed, // because it has beed chain-computed for every // token transfer that has occured in ACTIVE stage. // lotStorage.setRandomSeed( transferHashValue ); // If using Non-Mined algorithm types, reward for this // step is 20% of miner funds. if( cfg.endingAlgoType != uint8(EndingAlgoType.MinedWinnerSelection) ) { currentStepReward = ( totalMinerRewards * (20 * PERCENT) ) / ( _100PERCENT ); } } else { // If alternative seed generation is not yet possible // (not enough time passed since the rand.provider // request was made), then mining is not available // currently. require( false ); } } // Now, we know that Random Seed is obtained. // If we use this algo-type, perform the actual // winner selection algorithm. if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) ) { mine_executeEndingAlgorithmStep(); // Set the prize amount to SECOND STEP prize amount (90%). currentStepReward = ( totalMinerRewards * (90 * PERCENT) ) / ( _100PERCENT ); } // Now we've completed both Mining Steps, it means MINING stage // is finally completed! // Transition to COMPLETION stage, and set lottery completion // time to NOW. lotteryStage = uint8( STAGE.COMPLETION ); completionDate = uint32( now ); require( currentStepReward <= totalMinerRewards ); } // Now, transfer the reward to miner! // Check for bugs too - if the computed amount doesn't exceed. // Increment the mining step - move to next step (if there is one). miningStep++; // Check & Lock the Re-Entrancy Lock for transfers. require( ! reEntrancyMutexLocked ); reEntrancyMutexLocked = true; // Finally, transfer the reward to message sender! msg.sender.transfer( currentStepReward ); // UnLock ReEntrancy Lock. reEntrancyMutexLocked = false; } /** * Function computes winner prize amount for winner at rank #N. * Prerequisites: Must be called only on STAGE.COMPLETION stage, * because we use the final profits amount here, and that value * (ending_profitAmount) is known only on COMPLETION stage. * * @param rankingPosition - ranking position of a winner. * @return finalPrizeAmount - prize amount, in Wei, of this winner. */ function getWinnerPrizeAmount( uint rankingPosition ) public view returns( uint finalPrizeAmount ) { // Calculate total winner prize fund profit percentage & amount. uint winnerProfitPercentage = (_100PERCENT) - cfg.poolProfitShare - cfg.ownerProfitShare - cfg.minerProfitShare; uint totalPrizeAmount = ( ending_profitAmount * winnerProfitPercentage ) / ( _100PERCENT ); // We compute the prize amounts differently for the algo-type // RolledRandomness, because distribution of these prizes is // non-deterministic - multiple holders could fall onto the // same ranking position, due to randomness of rolled score. // if( cfg.endingAlgoType == uint8(EndingAlgoType.RolledRandomness) ) { // Here, we'll use Prize Sequence Factor approach differently. // We'll use the prizeSequenceFactor value not to compute // a geometric progression, but to compute an arithmetic // progression, where each ranking position will get a // prize equal to // "totalPrizeAmount - rankingPosition * singleWinnerShare" // // singleWinnerShare is computed as a value corresponding // to single-winner's share of total prize amount. // // Using such an approach, winner at rank 0 would get a // prize equal to whole totalPrizeAmount, but, as the // scores are rolled using random factor, it's very unlikely // to get a such high score, so most likely such prize // won't ever be claimed, but it is a possibility. // // Most of the winners in this approach are likely to // roll scores in the middle, so would get prizes equal to // 1-10% of total prize funds. uint singleWinnerShare = totalPrizeAmount / cfg.prizeSequence_winnerCount; return totalPrizeAmount - rankingPosition * singleWinnerShare; } // Now, we know that ending algorithm is normal (deterministic). // So, compute the prizes in a standard way. // If using Computed Sequence: loop for "rankingPosition" // iterations, while computing the prize shares. // If "rankingPosition" is larger than sequencedWinnerCount, // then compute the prize from sequence-leftover amount. if( cfg.prizeSequenceFactor != 0 ) { require( rankingPosition < cfg.prizeSequence_winnerCount ); // Leftover: If prizeSequenceFactor is 25%, it's 75%. uint leftoverPercentage = (_100PERCENT) - cfg.prizeSequenceFactor; // Loop until the needed iteration. uint loopCount = ( rankingPosition >= cfg.prizeSequence_sequencedWinnerCount ? cfg.prizeSequence_sequencedWinnerCount : rankingPosition ); for( uint i = 0; i < loopCount; i++ ) { totalPrizeAmount = ( totalPrizeAmount * leftoverPercentage ) / ( _100PERCENT ); } // Get end prize amount - sequenced, or leftover. // Leftover-mode. if( loopCount == cfg.prizeSequence_sequencedWinnerCount && cfg.prizeSequence_winnerCount > cfg.prizeSequence_sequencedWinnerCount ) { // Now, totalPrizeAmount equals all leftover-group winner // prize funds. // So, just divide it by number of leftover winners. finalPrizeAmount = ( totalPrizeAmount ) / ( cfg.prizeSequence_winnerCount - cfg.prizeSequence_sequencedWinnerCount ); } // Sequenced-mode else { finalPrizeAmount = ( totalPrizeAmount * cfg.prizeSequenceFactor ) / ( _100PERCENT ); } } // Else, if we're using Pre-Specified Array of winner profit // shares, just get the share at the corresponding index. else { require( rankingPosition < cfg.winnerProfitShares.length ); finalPrizeAmount = ( totalPrizeAmount * cfg.winnerProfitShares[ rankingPosition ] ) / ( _100PERCENT ); } } /** * After lottery has completed, this function returns if msg.sender * is one of lottery winners, and the position in winner rankings. * * Function must be used to obtain the ranking position before * calling claimWinnerPrize(). * * @param addr - address whose status to check. */ function getWinnerStatus( address addr ) external view returns( bool isWinner, uint32 rankingPosition, uint prizeAmount ) { if( !onStage( STAGE.COMPLETION ) || balanceOf( addr ) == 0 ) return (false , 0, 0); ( isWinner, rankingPosition ) = lotStorage.getWinnerStatus( addr ); if( isWinner ) { prizeAmount = getWinnerPrizeAmount( rankingPosition ); if( prizeAmount > address(this).balance ) prizeAmount = address(this).balance; } } /** * Compute the intermediate Active Stage player score. * This score is Player Score, not randomized. * @param addr - address to check. */ function getPlayerIntermediateScore( address addr ) external view returns( uint ) { return lotStorage.getPlayerActiveStageScore( addr ); } /** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> * * Claim the winner prize of msg.sender, if he is one of the winners. * * This function must be provided a ranking position of msg.sender, * which must be obtained using the function above. * * The Lottery Storage then just checks if holder address in the * winner array element at position rankingPosition is the same * as msg.sender's. * * If so, then claim request is valid, and we can give the appropriate * prize to that winner. * Prize can be determined by a computed factor-based sequence, or * from the pre-specified winner array. * * * This function transfers Ether out of our contract: * - Sends the corresponding winner prize to the msg.sender. * * @param rankingPosition - the position of Winner Array, that * msg.sender says he is in (obtained using getWinnerStatus). */ function claimWinnerPrize( uint32 rankingPosition ) external onlyOnStage( STAGE.COMPLETION ) mutexLOCKED { // Check if msg.sender hasn't already claimed his prize. require( ! prizeClaimersAddresses[ msg.sender ] ); // msg.sender must have at least some of UniLottery Tokens. require( balanceOf( msg.sender ) != 0 ); // Check if there are any prize funds left yet. require( address(this).balance != 0 ); // If using Mined Selection Algo, check if msg.sender is // really on that ranking position - algo was already executed. if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) ) { require( lotStorage.minedSelection_isAddressOnWinnerPosition( msg.sender, rankingPosition ) ); } // For other algorithms, get ranking position by executing // a specific algorithm of that algo-type. else { bool isWinner; ( isWinner, rankingPosition ) = lotStorage.getWinnerStatus( msg.sender ); require( isWinner ); } // Compute the prize amount, using our internal function. uint finalPrizeAmount = getWinnerPrizeAmount( rankingPosition ); // If prize is small and computation precision errors occured, // leading it to be larger than our balance, fix it. if( finalPrizeAmount > address(this).balance ) finalPrizeAmount = address(this).balance; // Transfer the Winning Prize to msg.sender! msg.sender.transfer( finalPrizeAmount ); // Mark msg.sender as already claimed his prize. prizeClaimersAddresses[ msg.sender ] = true; } /** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> * * Transfer the leftover Winner Prize Funds of this contract to the * Main UniLottery Pool, if prize claim deadline has been exceeded. * * Function can only be called from the Main Pool, and if some * winners haven't managed to claim their prizes on time, their * prizes will go back to UniLottery Pool. * * * Function transfers Ether out of our contract: * - Transfer the leftover funds to the Pool (msg.sender). */ function getUnclaimedPrizes() external poolOnly onlyOnStage( STAGE.COMPLETION ) mutexLOCKED { // Check if prize claim deadline has passed. require( completionDate != 0 && ( now - completionDate ) > cfg.prizeClaimTime ); // Just transfer it all to the Pool. poolAddress.transfer( address(this).balance ); } }
Launch the winner algorithm, to execute the next step.
function mine_executeEndingAlgorithmStep() internal { lotStorage.executeWinnerSelectionAlgorithm(); } constructor() public
7,490,182
pragma solidity ^0.5.0; import "../frontend/SubscriptionFrontEnd.sol"; import "../accounts/AuthorizedTokenTransferer.sol"; /** * @title PublisherFrontEnd * @dev Singleton contract for creating new instances of a SubscriptionFrontEnd, which represents a publisher * or service provider (i.e. the party offering subscriptions). */ contract PublisherFrontEnd { event PublisherCreated( SubscriptionFrontEnd publisher, AuthorizedTokenTransferer authorizedTokenTransferer ); /** * @dev Creates a new publisher with a new AuthorizedTokenTransferer. Wires the two together correctly by * adding the SubscriptionFrontEnd to the AuthorizedTokenTransferer caller whitelist. * @return The newly created SubscriptionFrontEnd. */ function createPublisher() public returns (SubscriptionFrontEnd) { AuthorizedTokenTransferer authorizedTokenTransferer = new AuthorizedTokenTransferer(); SubscriptionFrontEnd subscriptionFrontEnd = createPublisher(authorizedTokenTransferer); authorizedTokenTransferer.addWhitelistAdmin(address(subscriptionFrontEnd)); authorizedTokenTransferer.renounceWhitelistAdmin(); return subscriptionFrontEnd; } /** * @dev Create a publisher using a previously created AuthorizedTokenTransferer. Users will be able to * use the new SubscriptionFrontEnd without having to re-authorize a new AuthorizedTokenTransferer. * @param authorizedTransferer The token transfer proxy used to transfer tokens from subscriber to service provider. * @return The newly created SubscriptionFrontEnd. Make sure to call addWhitelistAdmin on the token transferer * to ensure proper functionality of the SubscriptionFrontEnd. */ function createPublisher( AuthorizedTokenTransferer authorizedTransferer ) public returns (SubscriptionFrontEnd) { SubscriptionFrontEnd frontEnd = new SubscriptionFrontEnd(authorizedTransferer); emit PublisherCreated(frontEnd, authorizedTransferer); return frontEnd; } }
Creates a new publisher with a new AuthorizedTokenTransferer. Wires the two together correctly by adding the SubscriptionFrontEnd to the AuthorizedTokenTransferer caller whitelist. return The newly created SubscriptionFrontEnd./
function createPublisher() public returns (SubscriptionFrontEnd) { AuthorizedTokenTransferer authorizedTokenTransferer = new AuthorizedTokenTransferer(); SubscriptionFrontEnd subscriptionFrontEnd = createPublisher(authorizedTokenTransferer); authorizedTokenTransferer.addWhitelistAdmin(address(subscriptionFrontEnd)); authorizedTokenTransferer.renounceWhitelistAdmin(); return subscriptionFrontEnd; }
12,787,556
./partial_match/1/0xf5e297CF2eAd259D7e71B048D40328CB72105b78/sources/LinearTokenTimelock.sol
the total amount of tokens held by timelock
function totalToken() public view virtual override returns (uint256) { return lockedToken.balanceOf(address(this)); }
9,252,527
// solium-disable linebreak-style pragma solidity ^0.4.23; contract Pedro_ERC20Token { string public name = "Pedro Token"; string public symbol = "PEDRO"; uint public decimals = 2; uint public INITIAL_SUPPLY = 255000000 * 10**uint(decimals); uint256 public totalSupply_; using SafeMath for uint256; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; totalSupply_ = INITIAL_SUPPLY; balances[owner] = INITIAL_SUPPLY; } mapping(address => uint256) balances; /** * @dev We use a single lock for the whole contract. */ bool private reentrancyLock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!reentrancyLock); reentrancyLock = true; _; reentrancyLock = false; } /** * @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) { _transfer(_to, _value); } function _transfer( address _to, uint256 _value ) internal nonReentrant 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); emit Transfer(msg.sender, _to, _value); emit Transfer(msg.sender, msg.sender, _to, _value); return true; } event Transfer( address indexed _from, address indexed _to, uint256 value ); event Transfer( address indexed _spender, address indexed _from, address indexed _to, uint256 _value ); /** * @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) { return balances[_owner]; } 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) { _transferFrom(_from,_to,_value); } function _transferFrom( address _from, address _to, uint256 _value ) public nonReentrant returns(bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); emit Transfer(msg.sender,_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve( address _spender, uint256 _currentValue, uint256 _value ) public returns(bool) { require(_currentValue == allowed[msg.sender][_spender]); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); emit Approval(msg.sender, _spender, _currentValue, _value); return true; } event Approval( address indexed _owner, address indexed _spender, uint256 value ); event Approval( address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value ); /** * @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, uint256 _addedValue ) public returns(bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns(bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } address public owner; event OwnershipRenounced( address indexed previousOwner ); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership( address _newOwner ) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership( address _newOwner ) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @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 ) public hasMintPermission canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn( uint256 _value ) public { _burn(msg.sender, _value); } function _burn( address _who, uint256 _value ) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } /** * @title Math * @dev Assorted math operations */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul( uint256 a, uint256 b ) internal pure returns(uint256 c) { // Gas optimization: this is cheaper than asserting &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div( uint256 a, uint256 b ) internal pure returns(uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub( uint256 a, uint256 b ) internal pure returns(uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add( uint256 a, uint256 b ) internal pure returns(uint256 c) { c = a + b; assert(c >= a); return c; } }
Function to mint tokens _to The address that will receive the minted tokens. _amount The amount of tokens to mint. return A boolean that indicates if the operation was successful./
function mint( address _to, uint256 _amount ) public hasMintPermission canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; }
14,980,872
./full_match/1/0xf8fFD1Caad73cff5cf5416834d45C5AC289Ecf2c/sources/contracts/BattlePassStorage.sol
Returns the signer address used for the mintSignature method./
function signerAddress() external view returns (address) { return _signerAddress; }
3,122,908
./partial_match/1/0x5309ceC6C67eC23f9E71EAaA8C7E4A37E0e1Aebd/sources/NyanV2.sol
make sure to set final LP amountget users staked LP amounttake LP and remove liquidity from Uniswap pool andsend LP ETH and Nyan-2 to user get user's percentage of ETH in Nyan fund call function in connector to send ETH to the user reduce the user's stake to 0 update NIP contract add user to exited list, they cannot move Nyan until isExitingPeriod is false
function claimAndExit() public { require(isExitPeriod); require(!hasExited[msg.sender]); require(userStake[msg.sender].blockStaked < block.number); uint256 userLPStake = userStake[msg.sender].stakedNyanV2LP; IERC20(nyanV2LP).approve(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, IERC20(nyanV2LP).totalSupply()); IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D).removeLiquidityETH( address(this), userLPStake, 0, 0, msg.sender, now + 3 days ); uint256 fundETH = fundAddress.balance; uint256 userFundETH = fundETH.mul(userLPStake).div(finalLPAmount); Connector(0x60d70dF1c783b1E5489721c443465684e2756555).exitClaim(msg.sender, userFundETH); userStake[msg.sender].stakedNyanV2LP = 0; CatnipV2(catnipV2).nyanV2LPUnstaked(msg.sender, userLPStake); NyanVoting(votingContract).nyanV2LPUnstaked(userStake[msg.sender].stakedNyanV2LP, msg.sender); hasExited[msg.sender] = true; }
15,551,464
// SPDX-License-Identifier: MIT /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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; } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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); } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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); } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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; } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; ////import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [////IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * ////IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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); } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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); } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "@openzeppelin/contracts/access/Ownable.sol"; ////import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; /** * @title Divinity Cell DivinityCellWhitelist Contract * @notice Part of the DivinityCellMinter * @author Apriorit */ contract DivinityCellWhitelist is Ownable { using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet _whitelisted_users; /** * @notice Add toWhitelist address to the whitelist * @param toWhitelist The address of account to whitelist * @return Whether or not the transaction succeeded */ function whitelist(address toWhitelist) external onlyOwner returns(bool) { require(!_whitelisted_users.contains(toWhitelist), "Address is already in whitelist"); _whitelisted_users.add(toWhitelist); return true; } function getWhitelist() external view returns(address[] memory) { return _whitelisted_users.values(); } /** * @notice Remove toUnWhitelist address from whitelist * @param toUnWhitelist The address of account to remove from whitelist * @return Whether or not the transaction succeeded */ function unwhitelist(address toUnWhitelist) external onlyOwner returns(bool) { require(_whitelisted_users.contains(toUnWhitelist), "Address is not in whitelist"); _whitelisted_users.remove(toUnWhitelist); return true; } /** * @notice Add toWhitelist list of addresses into whitelist * @param toWhitelist The addresses of accounts to add to the whitelist * @return Whether or not the transaction succeeded */ function whitelistMany(address[] memory toWhitelist) external onlyOwner returns(bool) { for (uint i = 0; i < toWhitelist.length; i++) { _whitelisted_users.add(toWhitelist[i]); } return true; } /** * @notice Remove toUnWhitelist list of addresses from the whitelist * @param toUnWhitelist The addresses of accounts to remove from the whitelist * @return Whether or not the transaction succeeded */ function unwhitelistMany(address[] memory toUnWhitelist) external onlyOwner returns(bool) { for (uint i = 0; i < toUnWhitelist.length; i++) { _whitelisted_users.remove(toUnWhitelist[i]); } return true; } /** * @notice Check if account whitelisted or not * @param account Account that we want to check * @return Whether or not the account in the whitelist */ function is_whitelisted(address account) public view returns(bool) { return _whitelisted_users.contains(account); } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; ////import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; ////import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; ////import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; ////import "@openzeppelin/contracts/utils/Address.sol"; ////import "@openzeppelin/contracts/utils/Context.sol"; ////import "@openzeppelin/contracts/utils/Strings.sol"; ////import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, 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; event Premint(address indexed _to, uint256 indexed start_id, uint256 indexed count); /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } function _mint_many(address to, uint256 first_tokenId, uint256 count) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(first_tokenId), "ERC721: token already minted"); uint256 last_id = first_tokenId + count; for (uint256 i = first_tokenId; i < last_id; i++) { _mint(to, i); } } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "@openzeppelin/contracts/utils/math/SafeMath.sol"; ////import "@openzeppelin/contracts/utils/Counters.sol"; ////import "./utility/ERC721.sol"; ////import "./DivinityCellWhitelist.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title Divinity Cell DivinityCellNFT Contract * @author Apriorit */ contract DivinityCellNFT is ERC721, Ownable { using SafeMath for uint256; using Counters for Counters.Counter; string base_url; address burner; address _minter; address proxyRegistryAddress; Counters.Counter _nextTokenId; /** * @notice Ensures that sender has burn rights */ modifier onlyBurner { require(msg.sender == burner, "DivinityCellNFT: Sender must have burner role"); _; } /** * @notice Ensures that sender has mint rights */ modifier onlyMinter { require(msg.sender == _minter, "DivinityCellNFT: Sender is not auction"); _; } /** * @param _name Token name * @param _symbol Token syumbol * @param token_url Token base URI * @param _proxyRegistryAddress OpenSea existring proxy registry. On Mainnet it is 0xa5409ec958c83c3f309868babaca7c86dcb077c1 */ constructor( string memory _name, string memory _symbol, string memory token_url, address _proxyRegistryAddress ) ERC721(_name, _symbol) { base_url = token_url; proxyRegistryAddress = _proxyRegistryAddress; } /** * @notice Check if account is owner of tokenId * @param account The address of account that we want to check * @param tokenId ID that we are checking * @return Whether or not the account is owner of tokenId */ function isTokenOwner(uint256 tokenId, address account) external view returns(bool) { return ERC721.ownerOf(tokenId) == account; } /** * @notice Mint token for recipient. Can be called only by _minter * @param recipient The address of account that will recieve token * @return Minted token ID */ function mintTo(address recipient) external onlyMinter returns(uint256) { uint256 currentTokenId = _nextTokenId.current(); _nextTokenId.increment(); _safeMint(recipient, currentTokenId); return currentTokenId; } /** * @notice Mint count tokens for account. Can be called only by contract owner * @param account The address of account that will recieve tokens * @param count Count of tokens to mint * @return Whether or not the transaction succeeded */ function premint(address account, uint256 count) external onlyMinter returns(bool) { uint256 currentTokenId = _nextTokenId.current(); ERC721._mint_many(account, currentTokenId, count); _nextTokenId._value += count; return true; } /** * @notice Set new _minter. Only owner can call this. Can be called only by contract owner * @param minter The address of new minter * @return Whether or not the transaction succeeded */ function registerMinterContract(address minter) external onlyOwner returns(bool){ _minter = minter; return true; } /** * @notice Get current last token ID + 1.(total amount) * @return Current amount of tokens */ function totalSupply() external view returns (uint256) { return _nextTokenId.current(); } /** * @notice Set new token URI. Can be called only by contract owner * @param baseUrl New token URL * @return Whether or not the transaction succeeded */ function setURI(string memory baseUrl) external onlyOwner returns (bool) { base_url = baseUrl; return true; } /** * @notice Get token URI * @return Current token URI */ function URI() public view returns (string memory) { return base_url; } /** * @notice Get _tokenId URI * @param _tokenId Token for which we want to get URI * @return Token URI */ function tokenURI(uint256 _tokenId) override public view returns (string memory) { return string(abi.encodePacked(URI(), Strings.toString(_tokenId))); } /** * @notice Set new token burner. Can be called only by contract owner * @param newBurner New burner account * @return Whether or not the transaction succeeded */ function setBurner(address newBurner) external onlyOwner returns(bool) { burner = newBurner; return true; } /** * @notice Set new token burner. Can be called only by contract burner * @param tokenId Token to be burned * @return Whether or not the transaction succeeded */ function burn(uint256 tokenId) external onlyBurner returns(bool) { _burn(tokenId); return true; } /** * @notice Checks if token with given id exists * @param tokenId Checked token * @return Whether or not the token exists */ function exists(uint256 tokenId) external view returns(bool) { return ERC721._exists(tokenId); } /** * @notice Checks if operator can perform actions for owner * @param owner Tokens owner * @param operator Account that want perform actions for owner * @return Whether or not the transaction succeeded */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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); } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (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; } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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()); } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "@openzeppelin/contracts/access/Ownable.sol"; ////import "@openzeppelin/contracts/security/Pausable.sol"; ////import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; ////import "@openzeppelin/contracts/utils/math/SafeMath.sol"; ////import "@openzeppelin/contracts/utils/math/Math.sol"; ////import "./DivinityCellNFT.sol"; /** * @title Divinity Cell DivinityCellMinter Contract * @notice Used for token presales * @author Apriorit */ contract DivinityCellMinter is ReentrancyGuard, Ownable, Pausable, DivinityCellWhitelist { using SafeMath for uint256; uint256 public tokens_limit; uint256 public tokens_this_sale = 0; uint32 public buy_limit; uint32 current_sale_id = 0; uint256 public mint_price; uint256 public sale_end_timestamp = 0; uint256 public sale_start_timestamp = 0; bool public is_sell_private = true; mapping(uint => mapping(address => uint)) bought_current_sell; address nft_contract; address whitelist_contract; /** * @notice Return bought count for the current sale * @param account Account that we want to check * @return Count of bought tokens for the current sale */ function boughtCurrentSale(address account) public view returns(uint) { return bought_current_sell[current_sale_id][account]; } /** * @notice If current sale is private, ensures that it still continues and sender is whitelisted */ modifier minterAllowed { if (is_sell_private) { require(block.timestamp < sale_end_timestamp, "DivinityCellAuction: Sale ended"); if (mint_price == 0) { require(DivinityCellWhitelist(whitelist_contract).is_whitelisted(msg.sender), "DivinityCellAuction: Account is not whitelisted"); } else { require(is_whitelisted(msg.sender), "DivinityCellAuction: Account is not whitelisted"); } } _; } /** * @notice Ensures that there is no other sale. If last sale was public, ensures that all tokens sold */ modifier onlyIfNoSale { require(sale_start_timestamp < block.timestamp, "DivinityCellAuction: New sale is about to start"); if (tokens_this_sale != 0) { require(sale_end_timestamp < block.timestamp, "DivinityCellAuction: Private sale still continues"); } _; } /** * @notice Sets new mint price for token mint. Can be called only by contract owner * @param nft address of NFT tokens contract, used for minting * @param nft address of whitelist contract, used for free minting * @param tokens_count Amount of tokens to be minted * @param initial_mint_price Initial minting price */ constructor(address nft, address whitelist, uint32 tokens_count, uint256 initial_mint_price) { tokens_limit = tokens_count; nft_contract = nft; whitelist_contract = whitelist; mint_price = initial_mint_price; } /** * @notice Send all eth collected by contract to _to account. Can be called only by contract owner * @param _to The account that will receive contract ETH * @return Whether or not the transaction succeeded */ function collectETH(address payable _to) external onlyOwner payable returns(bool) { (bool sent,) = _to.call{value: address(this).balance}(""); require(sent, "DivinityCellAuction: Failed to send Ether"); return true; } /** * @notice Sets new mint price for token mint. Can be called only by contract owner * @param new_mint_price New mint price * @return Whether or not the transaction succeeded */ function setPrice(uint256 new_mint_price) external onlyOwner returns(bool) { mint_price = new_mint_price; return true; } /** * @notice Starts private token sale. Can be called only by contract owner and only if other sale is not running * @param per_user_limitation Number of tokens that be bought by accounts this sale * @param tokens_count Number of tokens that will be sold this sale * @param new_sale_end_timestamp Sale start timestamp * @param new_sale_start_timestamp Sale end timestamp * @return Whether or not the transaction succeeded */ function startPrivateSale(uint32 per_user_limitation, uint256 tokens_count, uint256 new_sale_start_timestamp, uint256 new_sale_end_timestamp) external onlyOwner onlyIfNoSale returns(bool) { require(tokens_limit >= tokens_count, "DivinityCellAuction: Cant sell that much tokens"); require(new_sale_end_timestamp > block.timestamp, "DivinityCellAuction: Wrong timestamp passed"); require(new_sale_start_timestamp < new_sale_end_timestamp, "DivinityCellAuction: Start date should be less than end date"); require(per_user_limitation > 0, "DivinityCellAuction: Wrong limitation passed"); require(tokens_count > 0, "DivinityCellAuction: Wrong token count passed"); tokens_this_sale = tokens_count; buy_limit = per_user_limitation; sale_end_timestamp = new_sale_end_timestamp; sale_start_timestamp = new_sale_start_timestamp; current_sale_id += 1; is_sell_private = true; return true; } /** * @notice Changes sale start and end timestamps. * @param new_sale_end_timestamp New sale start timestamp * @param new_sale_start_timestamp New sale end timestamp * @return Whether or not the transaction succeeded */ function reschedulePrivateSale(uint256 new_sale_start_timestamp, uint256 new_sale_end_timestamp) external onlyOwner returns(bool) { require(new_sale_start_timestamp < new_sale_end_timestamp, "DivinityCellAuction: Start date should be less than end date"); require(tokens_this_sale > 0, "DivinityCellAuction: No tokens left"); sale_end_timestamp = new_sale_end_timestamp; sale_start_timestamp = new_sale_start_timestamp; return true; } /** * @notice Starts public token sale. Can be called only by contract owner and only if other sale is not running. * Unlike private one, this will end only after all tokens are bought * @param per_user_limitation Number of tokens that be bought by accounts this sale * @param new_sale_start_timestamp Sale start timestamp * @return Whether or not the transaction succeeded */ function startPublicSale(uint32 per_user_limitation, uint256 tokens_count, uint256 new_sale_start_timestamp) external onlyOwner onlyIfNoSale returns(bool) { require(tokens_limit >= tokens_count, "DivinityCellAuction: Cant sell that much tokens"); require(tokens_limit > 0, "DivinityCellAuction: Cant sell that much tokens"); require(per_user_limitation > 0, "DivinityCellAuction: Wrong limitation passed"); tokens_this_sale = tokens_count; sale_start_timestamp = new_sale_start_timestamp; buy_limit = per_user_limitation; current_sale_id += 1; is_sell_private = false; return true; } /** * @notice Changes sale start timestamp. * @param new_sale_start_timestamp New start end timestamp * @return Whether or not the transaction succeeded */ function reschedulePublicSale(uint256 new_sale_start_timestamp) external onlyOwner returns(bool) { require(sale_end_timestamp < block.timestamp, "DivinityCellAuction: Private sale continues"); require(tokens_this_sale > 0, "DivinityCellAuction: No tokens left"); sale_start_timestamp = new_sale_start_timestamp; return true; } /** * @notice pause current sale. Emits pause event */ function pause() public onlyOwner { Pausable._pause(); } /** * @notice unpause current sale. Emits unpause event */ function unpause() public onlyOwner { Pausable._unpause(); } /** * @notice Mints token for transaction sender. Can't be called if sale is not started * @return ID of minted token */ function mint(uint256 amount) public payable whenNotPaused minterAllowed nonReentrant returns(bool) { uint256 userLimit = getMintLimit(); require(userLimit > 0, "DivinityCellAuction: This recipient cant buy more tokens this sale"); require(amount > 0, "DivinityCellAuction: Invalid amount"); require(block.timestamp >= sale_start_timestamp, "DivinityCellAuction: Sale hasn't started yet"); uint256 count = Math.min(amount, userLimit); require(msg.value == mint_price * count, "DivinityCellAuction: Wrong amount of eth sent"); require(tokens_this_sale >= count, "DivinityCellAuction: Nothing to sell"); require(tokens_limit >= count, "DivinityCellAuction: Nothing to sell"); bool isMinted = DivinityCellNFT(nft_contract).premint(msg.sender, count); require(isMinted, "DivinityCellAuction: mint failed"); bought_current_sell[current_sale_id][msg.sender] += count; tokens_this_sale -= count; tokens_limit -= count; return isMinted; } /** * @notice Mint count tokens for account. Can be called only by contract owner * @param account The address of account that will recieve tokens * @param count Count of tokens to mint * @return Whether or not the transaction succeeded */ function premint(address account, uint256 count) external onlyOwner nonReentrant returns(bool) { require(tokens_limit >= count, "DivinityCellAuction: can't mint that much tokens"); bool is_premnt_successful = DivinityCellNFT(nft_contract).premint(account, count); require(is_premnt_successful, "DivinityCellAuction: premint was unsuccessful"); tokens_limit -= count; return is_premnt_successful; } // Helpers /** * @return amount of tokens available for current mint transaction */ function getMintLimit() internal view returns(uint) { if (is_sell_private) { uint bought = boughtCurrentSale(msg.sender); if (mint_price == 0) { if (bought > 0) { return 0; } uint256 holdings = DivinityCellNFT(nft_contract).balanceOf(msg.sender); if (holdings >= 5) { return 2; } if (holdings >= 3) { return 1; } return 0; } return buy_limit - bought; } return 5; } }
Add toWhitelist address to the whitelist toWhitelist The address of account to whitelist return Whether or not the transaction succeeded/
function whitelist(address toWhitelist) external onlyOwner returns(bool) { require(!_whitelisted_users.contains(toWhitelist), "Address is already in whitelist"); _whitelisted_users.add(toWhitelist); return true; }
76,691
/// @title SafeMath /// @dev Math operations with safety checks that throw on error library SafeMath { /// @dev Multiplies a times b function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } /// @dev Divides a by b function div(uint256 a, uint256 b) internal pure returns (uint256) { // require(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // require(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /// @dev Subtracts a from b function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } /// @dev Adds a to b function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } /// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20 /// @title Abstract token contract - Functions to be implemented by token contracts contract Token { /* * Events */ event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /* * Public functions */ function transfer(address to, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); function balanceOf(address owner) public constant returns (uint256); function allowance(address owner, address spender) public constant returns (uint256); uint256 public totalSupply; } /// @title Standard token contract - Standard token interface implementation contract StandardToken is Token { using SafeMath for uint256; /* * Storage */ mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowances; uint256 public totalSupply; /* * Public functions */ /// @dev Transfers sender's tokens to a given address. Returns success /// @param to Address of token receiver /// @param value Number of tokens to transfer /// @return Returns success of function call 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; } /// @dev Allows allowances third party to transfer tokens from one address to another. Returns success /// @param from Address from where tokens are withdrawn /// @param to Address to where tokens are sent /// @param value Number of tokens to transfer /// @return Returns success of function call function transferFrom(address from, address to, uint256 value) public returns (bool) { // if (balances[from] < value || allowances[from][msg.sender] < value) // // Balance or allowance too low // revert(); require(to != address(0)); require(value <= balances[from]); require(value <= allowances[from][msg.sender]); balances[to] = balances[to].add(value); balances[from] = balances[from].sub(value); allowances[from][msg.sender] = allowances[from][msg.sender].sub(value); Transfer(from, to, value); return true; } /// @dev Sets approved amount of tokens for spender. Returns success /// @param _spender Address of allowances account /// @param value Number of approved tokens /// @return Returns success of function call function approve(address _spender, uint256 value) public returns (bool success) { require((value == 0) || (allowances[msg.sender][_spender] == 0)); allowances[msg.sender][_spender] = value; Approval(msg.sender, _spender, value); return true; } /** * approve should be called when allowances[_spender] == 0. To increment * allowances 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) { allowances[msg.sender][_spender] = allowances[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowances[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowances[msg.sender][_spender] = 0; } else { allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } /// @dev Returns number of allowances tokens for given address /// @param _owner Address of token owner /// @param _spender Address of token spender /// @return Returns remaining allowance for spender function allowance(address _owner, address _spender) public constant returns (uint256) { return allowances[_owner][_spender]; } /// @dev Returns number of tokens owned by given address /// @param _owner Address of token owner /// @return Returns balance of owner function balanceOf(address _owner) public constant returns (uint256) { return balances[_owner]; } } contract Balehubuck is StandardToken { using SafeMath for uint256; /* * Constants */ string public constant name = "balehubuck"; string public constant symbol = "BUX"; uint8 public constant decimals = 18; uint256 public constant TOTAL_SUPPLY = 1000000000 * 10**18; // Presale Allocation = 500 * (5000 + 4500 + 4000 + 3500 + 3250 + 3000) // Main Sale Allocation = 75000 * 2500 // Token Sale Allocation = Presale Allocation + Main Sale Allocation uint256 public constant TOKEN_SALE_ALLOCATION = 199125000 * 10**18; uint256 public constant WALLET_ALLOCATION = 800875000 * 10**18; function Balehubuck(address wallet) public { totalSupply = TOTAL_SUPPLY; balances[msg.sender] = TOKEN_SALE_ALLOCATION; balances[wallet] = WALLET_ALLOCATION; // Sanity check to make sure total allocations match total supply require(TOKEN_SALE_ALLOCATION + WALLET_ALLOCATION == TOTAL_SUPPLY); } } contract TokenSale { using SafeMath for uint256; /* * Events */ event PresaleStart(uint256 indexed presaleStartTime); event AllocatePresale(address indexed receiver, uint256 tokenQuantity); event PresaleEnd(uint256 indexed presaleEndTime); event MainSaleStart(uint256 indexed startMainSaleTime); event AllocateMainSale(address indexed receiver, uint256 etherAmount); event MainSaleEnd(uint256 indexed endMainSaleTime); event TradingStart(uint256 indexed startTradingTime); event Refund(address indexed receiver, uint256 etherAmount); /* * Constants */ // Presale Allocation = 500 * (5000 + 4500 + 4000 + 3500 + 3250 + 3000) * 10**18 uint256 public constant PRESALE_TOKEN_ALLOCATION = 11625000 * 10**18; uint256 public constant PRESALE_MAX_RAISE = 3000 * 10**18; /* * Storage */ mapping (address => uint256) public presaleAllocations; mapping (address => uint256) public mainSaleAllocations; address public wallet; Balehubuck public token; uint256 public presaleEndTime; uint256 public mainSaleEndTime; uint256 public minTradingStartTime; uint256 public maxTradingStartTime; uint256 public totalReceived; uint256 public minimumMainSaleRaise; uint256 public maximumMainSaleRaise; uint256 public maximumAllocationPerParticipant; uint256 public mainSaleExchangeRate; Stages public stage; enum Stages { Deployed, PresaleStarted, PresaleEnded, MainSaleStarted, MainSaleEnded, Refund, Trading } /* * Modifiers */ modifier onlyWallet() { require(wallet == msg.sender); _; } modifier atStage(Stages _stage) { require(stage == _stage); _; } /* * Fallback function */ function () external payable { buy(msg.sender); } /* * Constructor function */ // @dev Constructor function that create the Balehubuck token and sets the initial variables // @param _wallet sets the wallet state variable which will be used to start stages throughout the token sale function TokenSale(address _wallet) public { require(_wallet != 0x0); wallet = _wallet; token = new Balehubuck(wallet); // Sets the default main sale values minimumMainSaleRaise = 23000 * 10**18; maximumMainSaleRaise = 78000 * 10**18; maximumAllocationPerParticipant = 750 * 10**18; mainSaleExchangeRate = 2500; stage = Stages.Deployed; totalReceived = 0; } /* * Public functions */ // @ev Allows buyers to buy tokens, throws if neither the presale or main sale is happening // @param _receiver The address the will receive the tokens function buy(address _receiver) public payable { require(msg.value > 0); address receiver = _receiver; if (receiver == 0x0) receiver = msg.sender; if (stage == Stages.PresaleStarted) { buyPresale(receiver); } else if (stage == Stages.MainSaleStarted) { buyMainSale(receiver); } else { revert(); } } /* * External functions */ // @dev Starts the presale function startPresale() external onlyWallet atStage(Stages.Deployed) { stage = Stages.PresaleStarted; presaleEndTime = now + 8 weeks; PresaleStart(now); } // @dev Sets the maximum and minimum raise amounts prior to the main sale // @dev Use this method with extreme caution! // @param _minimumMainSaleRaise Sets the minimium main sale raise // @param _maximumMainSaleRaise Sets the maximum main sale raise // @param _maximumAllocationPerParticipant sets the maximum main sale allocation per participant function changeSettings(uint256 _minimumMainSaleRaise, uint256 _maximumMainSaleRaise, uint256 _maximumAllocationPerParticipant, uint256 _mainSaleExchangeRate) external onlyWallet atStage(Stages.PresaleEnded) { // Checks the inputs for null values require(_minimumMainSaleRaise > 0 && _maximumMainSaleRaise > 0 && _maximumAllocationPerParticipant > 0 && _mainSaleExchangeRate > 0); // Sanity check that requires the min raise to be less then the max require(_minimumMainSaleRaise < _maximumMainSaleRaise); // This check verifies that the token_sale contract has enough tokens to match the // _maximumMainSaleRaiseAmount * _mainSaleExchangeRate (subtracts presale amounts first) require(_maximumMainSaleRaise.sub(PRESALE_MAX_RAISE).mul(_mainSaleExchangeRate) <= token.balanceOf(this).sub(PRESALE_TOKEN_ALLOCATION)); minimumMainSaleRaise = _minimumMainSaleRaise; maximumMainSaleRaise = _maximumMainSaleRaise; mainSaleExchangeRate = _mainSaleExchangeRate; maximumAllocationPerParticipant = _maximumAllocationPerParticipant; } // @dev Starts the main sale // @dev Make sure the main sale variables are correct before calling function startMainSale() external onlyWallet atStage(Stages.PresaleEnded) { stage = Stages.MainSaleStarted; mainSaleEndTime = now + 8 weeks; MainSaleStart(now); } // @dev Starts the trading stage, allowing buyer to claim their tokens function startTrading() external atStage(Stages.MainSaleEnded) { // Trading starts between two weeks (if called by the wallet) and two months (callable by anyone) // after the main sale has ended require((msg.sender == wallet && now >= minTradingStartTime) || now >= maxTradingStartTime); stage = Stages.Trading; TradingStart(now); } // @dev Allows buyer to be refunded their ETH if the minimum presale raise amount hasn't been met function refund() external atStage(Stages.Refund) { uint256 amount = mainSaleAllocations[msg.sender]; mainSaleAllocations[msg.sender] = 0; msg.sender.transfer(amount); Refund(msg.sender, amount); } // @dev Allows buyers to claim the tokens they've purchased function claimTokens() external atStage(Stages.Trading) { uint256 tokenAllocation = presaleAllocations[msg.sender].add(mainSaleAllocations[msg.sender].mul(mainSaleExchangeRate)); presaleAllocations[msg.sender] = 0; mainSaleAllocations[msg.sender] = 0; token.transfer(msg.sender, tokenAllocation); } /* * Private functions */ // @dev Allocated tokens to the presale buyer at a rate based on the total received // @param receiver The address presale balehubucks will be allocated to function buyPresale(address receiver) private { if (now >= presaleEndTime) { endPresale(); return; } uint256 totalTokenAllocation = 0; uint256 oldTotalReceived = totalReceived; uint256 tokenAllocation = 0; uint256 weiUsing = 0; uint256 weiAmount = msg.value; uint256 maxWeiForPresaleStage = 0; uint256 buyerRefund = 0; // Cycles through the presale phases conditional giving a different exchange rate for // each phase of the presale until tokens have been allocated for all Ether sent or // until the presale cap of 3,000 Ether has been reached while (true) { // The EVM deals with division by rounding down, causing the below statement to // round down to the correct stage // stageAmount = totalReceived.add(500 * 10**18).div(500 * 10**18).mul(500 * 10**18); // maxWeiForPresaleStage = stageAmount - totalReceived maxWeiForPresaleStage = (totalReceived.add(500 * 10**18).div(500 * 10**18).mul(500 * 10**18)).sub(totalReceived); if (weiAmount > maxWeiForPresaleStage) { weiUsing = maxWeiForPresaleStage; } else { weiUsing = weiAmount; } weiAmount = weiAmount.sub(weiUsing); if (totalReceived < 500 * 10**18) { // Stage 1: up to 500 Ether, exchange rate of 1 ETH for 5000 BUX tokenAllocation = calcpresaleAllocations(weiUsing, 5000); } else if (totalReceived < 1000 * 10**18) { // Stage 2: up to 1000 Ether, exchange rate of 1 ETH for 4500 BUX tokenAllocation = calcpresaleAllocations(weiUsing, 4500); } else if (totalReceived < 1500 * 10**18) { // Stage 3: up to 1500 Ether, exchange rate of 1 ETH for 4000 BUX tokenAllocation = calcpresaleAllocations(weiUsing, 4000); } else if (totalReceived < 2000 * 10**18) { // Stage 4: up to 2000 Ether, exchange rate of 1 ETH for 3500 BUX tokenAllocation = calcpresaleAllocations(weiUsing, 3500); } else if (totalReceived < 2500 * 10**18) { // Stage 5: up to 2500 Ether, exchange rate of 1 ETH for 3250 BUX tokenAllocation = calcpresaleAllocations(weiUsing, 3250); } else if (totalReceived < 3000 * 10**18) { // Stage 6: up to 3000 Ether, exchange rate of 1 ETH for 3000 BUX tokenAllocation = calcpresaleAllocations(weiUsing, 3000); } totalTokenAllocation = totalTokenAllocation.add(tokenAllocation); totalReceived = totalReceived.add(weiUsing); if (totalReceived >= PRESALE_MAX_RAISE) { buyerRefund = weiAmount; endPresale(); } // Exits the for loops if the presale cap has been reached (changing the stage) // or all of the wei send to the presale has been allocated if (weiAmount == 0 || stage != Stages.PresaleStarted) break; } presaleAllocations[receiver] = presaleAllocations[receiver].add(totalTokenAllocation); wallet.transfer(totalReceived.sub(oldTotalReceived)); msg.sender.transfer(buyerRefund); AllocatePresale(receiver, totalTokenAllocation); } // @dev Allocated tokens to the presale buyer at a rate based on the total received // @param receiver The address main sale balehubucks will be allocated to function buyMainSale(address receiver) private { if (now >= mainSaleEndTime) { endMainSale(msg.value); msg.sender.transfer(msg.value); return; } uint256 buyerRefund = 0; uint256 weiAllocation = mainSaleAllocations[receiver].add(msg.value); if (weiAllocation >= maximumAllocationPerParticipant) { weiAllocation = maximumAllocationPerParticipant.sub(mainSaleAllocations[receiver]); buyerRefund = msg.value.sub(weiAllocation); } uint256 potentialReceived = totalReceived.add(weiAllocation); if (potentialReceived > maximumMainSaleRaise) { weiAllocation = maximumMainSaleRaise.sub(totalReceived); buyerRefund = buyerRefund.add(potentialReceived.sub(maximumMainSaleRaise)); endMainSale(buyerRefund); } totalReceived = totalReceived.add(weiAllocation); mainSaleAllocations[receiver] = mainSaleAllocations[receiver].add(weiAllocation); msg.sender.transfer(buyerRefund); AllocateMainSale(receiver, weiAllocation); } // @dev Calculates the amount of presale tokens to allocate // @param weiUsing The amount of wei being used to for the given token allocation // @param rate The eth/token exchange rate, this changes based on how much the presale has received so far function calcpresaleAllocations(uint256 weiUsing, uint256 rate) private pure returns (uint256) { return weiUsing.mul(rate); } // @dev Ends the presale function endPresale() private { stage = Stages.PresaleEnded; PresaleEnd(now); } // @dev Ends the main sale triggering a refund if the minimum sale raise has no been met // @dev or passes funds raised to the wallet and starts the trading count down function endMainSale(uint256 buyerRefund) private { if (totalReceived < minimumMainSaleRaise) { stage = Stages.Refund; } else { minTradingStartTime = now + 2 weeks; maxTradingStartTime = now + 8 weeks; stage = Stages.MainSaleEnded; // Transfers all funds raised to the Balehu wallet minus the funds that need to be refunded wallet.transfer(this.balance.sub(buyerRefund)); // All unsold tokens will remain within the token_sale contract // and will be treated as burned } MainSaleEnd(now); } }
Returns number of allowances tokens for given address _owner Address of token owner _spender Address of token spender return Returns remaining allowance for spender
function allowance(address _owner, address _spender) public constant returns (uint256) { return allowances[_owner][_spender]; }
6,421,383
./partial_match/1/0xd1B9aF64Ed5CdcaEb58955d82FB384b3e558Df7B/sources/ConvexStrategy.sol
Pulls out all funds into strategies base asset and stops the strategy from being able to run harvest. reports back any gains/losses from this action to the vault we expect losses, but should account for a situation that produces gainst
function stopLoss() external returns (bool) { if (!keepers[msg.sender]) revert StrategyErrors.NotKeeper(); if (stopLossAttempts == 0) sellAllRewards(); if (divestAll(true) == 0) { stopLossAttempts += 1; return false; } uint256 debt = VAULT.getStrategyDebt(); uint256 balance = ASSET.balanceOf(address(this)); uint256 loss; uint256 profit; if (debt > balance) { loss = debt - balance; profit = balance - debt; } stop = true; stopLossAttempts = 0; return true; } TRIGGERS
9,262,069
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./lib/SafeMath.sol"; import "./lib/SafeERC20.sol"; import "./lib/Address.sol"; import "./lib/OwnableUpgradeSafe.sol"; import "./lib/IERC20.sol"; // Vault distributing fixed per-block reward of ERC20 token equally amongst staked pools contract VaultAdu is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many 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 ADUs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accRewardPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accRewardPerShare` (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 token; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. ADUs to distribute per block. uint256 accRewardPerShare; // Accumulated token underlying units per share, times 1e12. See below. uint256 lastRewardBlock; } // A reward token IERC20 public rewardToken; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; uint256 public rewardPerBlock; // Returns average rewards generated since start of this contract function averageRewardPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge reward in this epoch function averageRewardPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; // Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event LogUpdatePool(uint256 indexed pid, uint256 lastRewardBlock, uint256 lpSupply, uint256 accRewardPerShare); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event MigrationWithdraw(address indexed user, address indexed newVault, uint256 amount); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); function initialize( IERC20 _rewardToken, uint256 _rewardPerBlock ) public initializer { OwnableUpgradeSafe.__Ownable_init(); rewardToken = _rewardToken; contractStartBlock = block.number; epochCalculationStartBlock = block.number; rewardPerBlock = _rewardPerBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing ADU governance consensus function add(uint256 _allocPoint, IERC20 _token) public onlyOwner { uint256 length = poolInfo.length; uint256 lastRewardBlock = block.number; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accRewardPerShare: 0, lastRewardBlock : lastRewardBlock }) ); } // Update the given pool's ADUs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing ADU governance consensus 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 reward tokens on frontend. function pendingToken(uint256 _pid, address _user) public view returns (uint256 pending) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accRewardPerShare = pool.accRewardPerShare; pending = user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt); // return calculated pending reward } // View function to see pending reward tokens on frontend. function pendingTokenActual(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accRewardPerShare = pool.accRewardPerShare; if (block.number > pool.lastRewardBlock) { uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply > 0) { // avoids division by 0 errors uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 aduReward = blocks.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); // eg. 4blocks * 1e20 * 100allocPoint / 100totalAllocPoint //add only diff from last calculation accRewardPerShare = pool.accRewardPerShare.add((aduReward.mul(1e12).div(lpSupply))); } } return user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt); // return calculated pending reward } // Update reward vairables 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 returns (PoolInfo memory pool) { pool = poolInfo[_pid]; if (block.number > pool.lastRewardBlock) { uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply > 0) { // avoids division by 0 errors uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 aduReward = blocks.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); // eg. 4blocks * 1e20 * 100allocPoint / 100totalAllocPoint pool.accRewardPerShare = pool.accRewardPerShare.add((aduReward.mul(1e12).div(lpSupply))); } pool.lastRewardBlock = block.number; poolInfo[_pid] = pool; emit LogUpdatePool(_pid, pool.lastRewardBlock, lpSupply, pool.accRewardPerShare); } } // Deposit LP tokens to Vault for ADU allocation. function deposit(uint256 _pid, uint256 _amount) public { depositFor(_pid, _amount, msg.sender); } // Deposit LP tokens to Vault for ADU allocation. function depositFor(uint256 _pid, uint256 _amount, address _to) public { // requires no allowances PoolInfo memory pool = updatePool(_pid); UserInfo storage user = userInfo[_pid][_to]; massUpdatePools(); updateAndPayOutPending(_pid, _to); if (_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount, _to); } function withdraw(uint256 _pid, uint256 _amount) public { withdrawTo(_pid, _amount, msg.sender); } function withdrawTo(uint256 _pid, uint256 _amount, address _to) public { PoolInfo memory pool = updatePool(_pid); UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); updateAndPayOutPending(_pid, msg.sender); if (_amount > 0) { pool.token.safeTransfer(_to, _amount); user.amount = user.amount.sub(_amount); } user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount, _to); } function updateAndPayOutPending(uint256 _pid, address _to) internal { uint256 pending = pendingToken(_pid, _to); if (pending > 0) { safeRewardTokenTransfer(_to, pending); } } function harvest(uint256 _pid) public returns (bool success) { return harvestTo(_pid, msg.sender); } /// @notice Harvest proceeds for transaction sender to `to`. /// @param _pid The index of the pool. See `poolInfo`. /// @param _to Receiver of ADU rewards. /// @return success Returns bool indicating success of rewarder delegate call. function harvestTo(uint256 _pid, address _to) public returns (bool success) { uint256 _pendingToken = pendingToken(_pid, _to); withdrawTo(_pid, 0, _to); emit Harvest(msg.sender, _pid, _pendingToken); return true; } // Safe ADU transfer function, just in case if there is no more ADU left. function safeRewardTokenTransfer(address _to, uint256 _amount) internal { uint256 aduBalance = rewardToken.balanceOf(address(this)); if (aduBalance > 0){ if (_amount > aduBalance) { rewardToken.transfer(_to, aduBalance); } else { rewardToken.transfer(_to, _amount); } } } function migrateTokensToNewVault(address _newVault) public virtual onlyOwner { require(_newVault != address(0), "Vault: new vault is the zero address"); uint256 rewardTokenBalErc = rewardToken.balanceOf(address(this)); safeRewardTokenTransfer(_newVault, rewardTokenBalErc); emit MigrationWithdraw(msg.sender, _newVault, rewardTokenBalErc); } /// @notice Withdraw without caring about rewards. EMERGENCY ONLY. /// @param _pid The index of the pool. See `poolInfo`. /// @param _to Receiver of the LP tokens. function emergencyWithdraw(uint256 _pid, address _to) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; // Note: transfer can fail or succeed if `amount` is zero. if (amount > 0) { pool.token.safeTransfer(_to, amount); user.amount = 0; user.rewardDebt = 0; } emit EmergencyWithdraw(msg.sender, _pid, amount, _to); } // Function that lets owner/governance contract approve // allowance for any 3rd party token inside this contract. // This means all future UNI like airdrops are covered. // And at the same time allows us to give allowance to strategy contracts. function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlyOwner { require(isContract(contractAddress), "Recipent is not a smart contract"); require(tokenAddress != address(rewardToken), "Vault token allowance not allowed"); uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; pid++) { require(tokenAddress != address(poolInfo[pid].token), "Vault pool token allowance not allowed"); } IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) internal view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } }
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public returns (PoolInfo memory pool) { pool = poolInfo[_pid]; if (block.number > pool.lastRewardBlock) { uint256 lpSupply = pool.token.balanceOf(address(this)); uint256 blocks = block.number.sub(pool.lastRewardBlock); pool.accRewardPerShare = pool.accRewardPerShare.add((aduReward.mul(1e12).div(lpSupply))); } pool.lastRewardBlock = block.number; poolInfo[_pid] = pool; emit LogUpdatePool(_pid, pool.lastRewardBlock, lpSupply, pool.accRewardPerShare); }
2,549,418
pragma solidity >= 0.5.11; /** * @title ChainValidator interface * @author Jakub Fornadel * @notice External chain validator contract, can be used for more sophisticated validation of new validators and transactors, e.g. custom min. required conditions, * concrete users whitelisting, etc... **/ interface ChainValidator { /** * @notice Validation function for new validators * * @param vesting How many tokens new validator wants to vest * @param acc Account address of the validator * @param mining Flag if validator is going to mine. * mining == false in case validateNewValidator is called during vestInChain method * mining == true in case validateNewValidator is called during startMining method * @param actNumOfValidators How many active validators is currently in chain **/ function validateNewValidator(uint256 vesting, address acc, bool mining, uint256 actNumOfValidators) external returns (bool); /** * @notice Validation function for new transactors * * @param deposit How many tokens new transactor wants to deposit * @param acc Account address of the transactor * @param actNumOfTransactors How many whitelisted transactors (their deposit balance >= min. required balance) is currently in chain **/ function validateNewTransactor(uint256 deposit, address acc, uint256 actNumOfTransactors) external returns (bool); } /** * @title EnergyChainValidator for Lition energy chain * @author Jakub Fornadel * @notice External chain validator contract with specific conditions tailored for Lition Energy chain **/ contract EnergyChainValidator is ChainValidator { /**************************************************************************************************************************/ /************************************************** Constants *************************************************************/ /**************************************************************************************************************************/ // Token precision. 1 LIT token = 1*10^18 uint256 constant LIT_PRECISION = 10**18; // Min deposit value uint256 constant MIN_DEPOSIT = 5000*LIT_PRECISION; // Min vesting value uint256 constant MIN_VESTING = 1000*LIT_PRECISION; // Min vesting value uint256 constant MAX_VESTING = 500000*LIT_PRECISION; /**************************************************************************************************************************/ /*********************************** Structs and functions related to the list of users ***********************************/ /**************************************************************************************************************************/ // Iterable map that is used only together with the Users mapping as data holder struct IterableMap { // map of indexes to the list array // indexes are shifted +1 compared to the real indexes of this list, because 0 means non-existing element mapping(address => uint256) listIndex; // list of addresses address[] list; } // Adds acc from the map function insertAcc(IterableMap storage map, address acc) internal { map.list.push(acc); // indexes are stored + 1 map.listIndex[acc] = map.list.length; } // Removes acc from the map function removeAcc(IterableMap storage map, address acc) internal { uint256 index = map.listIndex[acc]; require(index > 0 && index <= map.list.length, "RemoveAcc invalid index"); // Move an last element of array into the vacated key slot. uint256 foundIndex = index - 1; uint256 lastIndex = map.list.length - 1; map.listIndex[map.list[lastIndex]] = foundIndex + 1; map.list[foundIndex] = map.list[lastIndex]; map.list.length--; // Deletes element map.listIndex[acc] = 0; } // Returns true, if acc exists in the iterable map, otherwise false function existAcc(IterableMap storage map, address acc) internal view returns (bool) { return map.listIndex[acc] != 0; } /**************************************************************************************************************************/ /******************************************** Other structs and functions *************************************************/ /**************************************************************************************************************************/ // List of admins - they can add/remove whitelisted validators and users IterableMap private admins; // List of whitelisted users who can deposit IterableMap private whitelistedUsers; constructor() public { insertAcc(admins, msg.sender); } /**************************************************************************************************************************/ /*********************************************** Contract Interface *******************************************************/ /**************************************************************************************************************************/ /** * @notice Validation function for new validators. All validators with vesting in range <1000, 50000> LIT tokens are allowed * * @param vesting How many tokens new validator wants to vest * @param acc Account address of the validator * @param mining Flag if validator is going to mine. * mining == false in case validateNewValidator is called during vestInChain method * mining == true in case validateNewValidator is called during startMining method * @param actNumOfValidators How many active validators is currently in chain **/ function validateNewValidator(uint256 vesting, address acc, bool mining, uint256 actNumOfValidators) external returns (bool) { if (vesting < MIN_VESTING || vesting > MAX_VESTING) { return false; } return true; } /** * @notice Validation function for new transactors. Only whitelisted accounts are allowed * * @param deposit How many tokens new transactor wants to deposit * @param acc Account address of the transactor * @param actNumOfTransactors How many whitelisted transactors (their deposit balance >= min. required balance) is currently in chain **/ function validateNewTransactor(uint256 deposit, address acc, uint256 actNumOfTransactors) external returns (bool) { if (existAcc(whitelistedUsers, acc) == true && deposit >= MIN_DEPOSIT) { return true; } return false; } /** * @notice Adds new whitelisted accounts that are allowed to transact on Lition energy chain * Provided existing accounts are ignored * * @param accounts List of accounts **/ function addWhitelistedUsers(address[] calldata accounts) external { addUsers(whitelistedUsers, accounts); } /** * @notice Removes existing whitelisted accounts that are allowed to transact on Lition energy chain. * Provided non-existing accounts are ignored * * @param accounts List of accounts **/ function removeWhitelistedUsers(address[] calldata accounts) external { require(whitelistedUsers.list.length > 0, "There are no whitelisted users to be removed"); removeUsers(whitelistedUsers, accounts); } /** * @notice Adds new admins that are allowed to add/remove whitelisted users * Provided existing accounts are ignored* * @param accounts List of accounts **/ function addAdmins(address[] calldata accounts) external { addUsers(admins, accounts); } /** * @notice Removes existing admin that is allowed to add/remove whitelisted users. * Provided account must exist as registered admin * * @param account List of accounts **/ function removeAdmin(address account) external { require(admins.list.length > 1, "Cannot remove all admins, at least one must be always present"); require(existAcc(admins, account) == true, "Trying to remove non-existing admin"); removeAcc(admins, account); } /** * @notice Returns list of admins (their accounts) * * @param batch Batch number to be fetched. If the list is too big it cannot return all admins in one call. Instead, users are fetching batches of 100 account at a time * * @return accounts List(batch of 100) of account * @return count How many accounts are returned in specified batch * @return end Flag if there are no more accounts left. To get all accounts, caller should fetch all batches until he sees end == true **/ function getAdmins(uint256 batch) external view returns (address[100] memory accounts, uint256 count, bool end) { return getUsers(admins, batch); } /** * @notice Returns list of whitelisted users (their accounts) * * @param batch Batch number to be fetched. If the list is too big it cannot return all admins in one call. Instead, users are fetching batches of 100 account at a time * * @return accounts List(batch of 100) of account * @return count How many accounts are returned in specified batch * @return end Flag if there are no more accounts left. To get all accounts, caller should fetch all batches until he sees end == true **/ function getWhitelistedUsers(uint256 batch) external view returns (address[100] memory accounts, uint256 count, bool end) { return getUsers(whitelistedUsers, batch); } /*************************************************************************************************************************/ /******************************************** Contract internal functions ************************************************/ /*************************************************************************************************************************/ // Returns list of suers users function getUsers(IterableMap storage internalUsersGroup, uint256 batch) internal view returns (address[100] memory users, uint256 count, bool end) { count = 0; uint256 usersTotalCount = internalUsersGroup.list.length; uint256 i; for(i = batch * 100; i < (batch + 1)*100 && i < usersTotalCount; i++) { users[count] = internalUsersGroup.list[i]; count++; } if (i >= usersTotalCount) { end = true; } else { end = false; } } function addUsers(IterableMap storage internalUsersGroup, address[] memory users) internal { require(existAcc(admins, msg.sender) == true, "Only admins can do internal changes"); require(users.length <= 100, "Max number of processed users is 100"); for (uint256 i = 0; i < users.length; i++) { if (existAcc(internalUsersGroup, users[i]) == false) { insertAcc(internalUsersGroup, users[i]); } } } function removeUsers(IterableMap storage internalUsersGroup, address[] memory users) internal { require(existAcc(admins, msg.sender) == true, "Only admins can remove whitelisted users"); require(users.length <= 100, "Max number of processed users is 100"); for (uint256 i = 0; i < users.length; i++) { if (existAcc(internalUsersGroup, users[i]) == true) { removeAcc(internalUsersGroup, users[i]); } } } }
Adds new whitelisted accounts that are allowed to transact on Lition energy chain Provided existing accounts are ignored accounts List of accounts/
function addWhitelistedUsers(address[] calldata accounts) external { addUsers(whitelistedUsers, accounts); }
2,511,266
./partial_match/97/0xc6B519a3fcfCac7e4adCA8427d42b8aF7d80CF30/sources/InsuranceFund.sol
solhint-disable avoid-low-level-calls
function swapInput( Dir _dir, Decimal.decimal calldata _quoteAssetAmount, Decimal.decimal calldata _baseAssetAmountLimit ) external returns (Decimal.decimal memory); function swapOutput( Dir _dir, Decimal.decimal calldata _baseAssetAmount, Decimal.decimal calldata _quoteAssetAmountLimit, bool _skipFluctuationCheck ) external returns (Decimal.decimal memory); function migrateLiquidity(Decimal.decimal calldata _liquidityMultiplier, Decimal.decimal calldata _priceLimitRatio) external; function shutdown() external; function settleFunding() external returns (SignedDecimal.signedDecimal memory); function calcFee(Decimal.decimal calldata _quoteAssetAmount) external view returns (Decimal.decimal memory); function calcBaseAssetAfterLiquidityMigration( SignedDecimal.signedDecimal memory _baseAssetAmount, Decimal.decimal memory _fromQuoteReserve, Decimal.decimal memory _fromBaseReserve ) external view returns (SignedDecimal.signedDecimal memory); function getInputTwap(Dir _dir, Decimal.decimal calldata _quoteAssetAmount) external view returns (Decimal.decimal memory); function getOutputTwap(Dir _dir, Decimal.decimal calldata _baseAssetAmount) external view returns (Decimal.decimal memory); function getInputPrice(Dir _dir, Decimal.decimal calldata _quoteAssetAmount) external view returns (Decimal.decimal memory); function getOutputPrice(Dir _dir, Decimal.decimal calldata _baseAssetAmount) external view returns (Decimal.decimal memory); function getInputPriceWithReserves( Dir _dir, Decimal.decimal memory _quoteAssetAmount, Decimal.decimal memory _quoteAssetPoolAmount, Decimal.decimal memory _baseAssetPoolAmount ) external pure returns (Decimal.decimal memory); function getOutputPriceWithReserves( Dir _dir, Decimal.decimal memory _baseAssetAmount, Decimal.decimal memory _quoteAssetPoolAmount, Decimal.decimal memory _baseAssetPoolAmount ) external pure returns (Decimal.decimal memory); function getSpotPrice() external view returns (Decimal.decimal memory); function getLiquidityHistoryLength() external view returns (uint256); function quoteAsset() external view returns (IERC20Upgradeable); function open() external view returns (bool); function getSettlementPrice() external view returns (Decimal.decimal memory); function getBaseAssetDeltaThisFundingPeriod() external view returns (SignedDecimal.signedDecimal memory); function getCumulativeNotional() external view returns (SignedDecimal.signedDecimal memory); function getMaxHoldingBaseAsset() external view returns (Decimal.decimal memory); function getOpenInterestNotionalCap() external view returns (Decimal.decimal memory); function getLiquidityChangedSnapshots(uint256 i) external view returns (LiquidityChangedSnapshot memory); function mint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; function getPositionSize() external view returns (Decimal.decimal memory, Decimal.decimal memory); function getMMUnrealizedPNL(Decimal.decimal memory _baseAssetReserve, Decimal.decimal memory _quoteAssetReserve) external view returns (SignedDecimal.signedDecimal memory); function moveAMMPriceToOracle(uint256 _oraclePrice, bytes32 _priceFeedKey) external; function setPriceFeed(address _priceFeed) external; function getReserve() external view returns (Decimal.decimal memory, Decimal.decimal memory); } } ) internal { _updateDecimal(address(_token)); Decimal.decimal memory balanceBefore = _balanceOf(_token, _to); uint256 roundedDownValue = _toUint(_token, _value); (bool success, bytes memory data) = address(_token).call( abi.encodeWithSelector(_token.transfer.selector, _to, roundedDownValue) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "DecimalERC20: transfer failed"); _validateBalance(_token, _to, roundedDownValue, balanceBefore); }
11,482,702
./partial_match/1313161554/0xca9511B610bA5fc7E311FDeF9cE16050eE4449E9/sources/AuETH.sol
Get a snapshot of the account's balances, and the cached exchange rate This is used by comptroller to more efficiently perform liquidity checks. account Address of the account to snapshot return (token balance, borrow balance, exchange rate mantissa)/
function getAccountSnapshot(address account) external view override returns (uint, uint, uint) { uint auTokenBalance = accountTokens[account]; uint borrowBalance = borrowBalanceStoredInternal(account); uint exchangeRateMantissa = exchangeRateStoredInternal(); return (auTokenBalance, borrowBalance, exchangeRateMantissa); }
16,916,124
// Contracts/SupplyChain.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../emeraldaccesscontrol/MinerRole.sol"; import "../emeraldaccesscontrol/LaboratoryRole.sol"; import "../emeraldaccesscontrol/CustodianRole.sol"; import "../emeraldaccesscontrol/ManufacturerRole.sol"; import "../emeraldaccesscontrol/CustomerRole.sol"; import "./EmeraldStates.sol"; import "./Emerald.sol"; // Define a contract 'Supplychain' contract SupplyChain is Ownable, AccessControl, MinerRole, LaboratoryRole, CustodianRole, ManufacturerRole, CustomerRole{ // Define a variable called 'upc' for Universal Product Code (UPC) uint upc; // Define a variable called 'sku' for Stock Keeping Unit (SKU) uint sku; // Define a public mapping 'emeralds' that maps the UPC to an Emerald. mapping (uint => Emerald) emeralds; // Define a public mapping 'emeraldHistory' that maps the UPC to an array of TxHash, // that track its journey through the supply chain -- to be sent from DApp. mapping (uint => string[]) emeraldsHistory; EmeraldStates.State constant defaultState = EmeraldStates.State.Mined; // Define 17 events with the same 17 state values and accept 'upc' as input argument event Mined(uint upc); event Scaled(uint upc); event PackedForLab(uint upc); event ShipedToLab(uint upc); event LabReceived(uint upc); event Certified(uint upc); event ShippedToStore(uint upc); event StorageReceived(uint upc); event Stored(uint upc); event ForSale(uint upc); event Sold(uint upc); event ShipToManufacture(uint upc); event ManufacturerReceived(uint upc); event Manufactured(uint upc); event PackedForSale(uint upc); event Published(uint upc); event Buyed(uint upc); event ShippedToCustomer(uint upc); event Delivered(uint upc); // Define a modifer that verifies the Caller modifier verifyCaller (address _address) { require(msg.sender == _address); _; } // Define a modifier that checks if the paid amount is sufficient to cover the price modifier paidEnough(uint _price) { require(msg.value >= _price,"Not enought paid amount"); _; } // Define a modifier that checks the price and refunds the remaining balance modifier checkValue(uint _upc) { _; uint _price = emeralds[_upc].GetMarketPrice(); uint amountToReturn = msg.value - _price; msg.sender.transfer(amountToReturn); } // Checks if a emerald is Mined modifier mined(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Mined); _; } //Checks if an emerald was escaled modifier scaled(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Scaled); _; } //Checks if an emerald is packed modifier packedForLab(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.PackedForLab); _; } // Checks if an emerald was shipped to the laboratory modifier shipedToLab(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShipedToLab); _; } // Checks if an emerald was received by the Laboratory modifier labReceived(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.LabReceived); _; } // Checks if an emerald was certified by the laboratory modifier certified(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Certified); _; } // Checks if an emerald was shipped to the storage y the laboratory modifier shippedToStore(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShippedToStore); _; } // Checks if an emerald was received by the custodian service modifier storageReceived(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.StorageReceived); _; } // Checks if an emerald was stored by the custodian modifier stored(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Stored); _; } // Checks if a raw emerald is available for sale modifier forSale(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ForSale); _; } // Checks if a raw emerald was sold modifier sold(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Sold); _; } // Checks if a sold emerald was shipped to the buyer modifier shiptoManufacture(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShipToManufacture); _; } // Checks if an emerald was received by the manufacturer modifier manufacturerReceived(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ManufacturerReceived); _; } // Checks if an emerald was proccesed by the manufacturer modifier manufactured(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Manufactured); _; } // Checks if a cut emerald was packed modifier packedForSale(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.PackedForSale); _; } // Checks if an proccesed emerald is ready for sale modifier published(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Published); _; } // Checks if a proccesed emerald was purshased modifier buyed(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Buyed); _; } // Checks if a cut emerald was shipped to the buyer modifier shippedToCustomer(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShippedToCustomer); _; } // Checks if a cut emerald was received by the customer modifier delivered(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Delivered); _; } // In the constructor set 'owner' to the address that instantiated the contract // and set 'sku' to 1 // and set 'upc' to 1 constructor() { //owner = msg.sender; sku = 1; upc = 1; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } // Define a function 'kill' if required function kill() public onlyOwner{ selfdestruct(msg.sender); } // Define a function 'extractItem' that allows a Miner to mark an emerald as 'Mined' function extractEmerald( uint _sku, uint _upc, address payable _originMinerID, string memory _originMineName, string memory _originMineInformation, string memory _originMineLatitude, string memory _originMineLongitude ) public onlyMiner { //add emerald to emeralds list in the contract Emerald emerald = new Emerald(); emerald.SetExtractionInfo( _sku, _upc, _originMinerID, _originMineName, _originMineInformation, _originMineLatitude, _originMineLongitude ); emerald.SetEmeraldState(EmeraldStates.State.Mined); emeralds[_upc] = emerald; //Increment sku sku = sku + 1; // Emit the appropriate event emit Mined(_upc); } // Define a function 'scaleItem' that allows Miner to mark an item as 'Scaled' function scaleEmerald( uint _upc, string memory _scaleInfo ) public // Call modifier to check if upc has passed previous supply chain stage mined(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { // Update the appropriate fields emeralds[_upc].SetScaleInfo( _scaleInfo ); emeralds[_upc].SetEmeraldState(EmeraldStates.State.Scaled); // Emit the appropriate event emit Scaled(_upc); } //Define a function 'packScaledItem' that allows a Miner to mark an item 'Packed' function packScaledEmerald(uint _upc, address _laboratoryID, address _custodianID) public // Call modifier to check if upc has passed previous supply chain stage scaled(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { // Update the appropriate fields emeralds[_upc].AuthorizeLab(_laboratoryID); emeralds[_upc].AuthorizeCustodian(_custodianID); // Update Emerald state emeralds[_upc].SetEmeraldState(EmeraldStates.State.PackedForLab); // Emit the appropriate event emit PackedForLab(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function shipToLaboratory(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage packedForLab(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShipedToLab); // Emit the appropriate event emit ShipedToLab(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function laboratoryReceived(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shipedToLab(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetLaboratoryID()) onlyLaboratory { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.LabReceived); // Emit the appropriate event emit LabReceived(_upc); } // Define a function 'scaleItem' that allows a Miner to mark an item 'Processed' function certifyEmerald( uint _upc, string memory _certifiedProperties ) public // Call modifier to check if upc has passed previous supply chain stage labReceived(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetLaboratoryID()) onlyLaboratory { // Update the appropriate fields emeralds[_upc].SetCertifiedInfo(_certifiedProperties); emeralds[_upc].SetEmeraldState(EmeraldStates.State.Certified); // Emit the appropriate event emit Certified(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function shipToSecureStore(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage certified(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetLaboratoryID()) onlyLaboratory { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShippedToStore); // Emit the appropriate event emit ShippedToStore(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function SecureStorageReceived(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shippedToStore(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetCustodianID()) onlyCustodian { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.StorageReceived); // Emit the appropriate event emit StorageReceived(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function StoreEmerald(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage storageReceived(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetCustodianID()) onlyCustodian { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.Stored); // Emit the appropriate event emit Stored(_upc); } // Define a function 'registerForSale' that allows a Miner to mark an item 'ForSale' function registerForSale(uint _upc, uint _marketPrice) public // Call modifier to check if upc has passed previous supply chain stage stored(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { //Setup market price emeralds[_upc].SetMarketPrice(_marketPrice); // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ForSale); // Emit the appropriate event emit ForSale(_upc); } // Define a function 'buyItem' that allows the Manufacturer to mark an item 'Sold' function buyFromMiner(uint _upc) public payable // Call modifier to check if upc has passed previous supply chain stage forSale(_upc) // Call modifer to check if buyer has paid enough paidEnough(emeralds[_upc].GetMarketPrice()) // Call modifer to send any excess ether back to buyer checkValue(_upc) onlyManufacturer { // Transfer money to Miner (bool success, ) = emeralds[_upc].getOriginMinerID().call{value: emeralds[_upc].GetMarketPrice()}(""); require(success, "Transfer failed"); // Tranfer emerald ownership emeralds[_upc].SetOwnerID(msg.sender); emeralds[_upc].SetManufacturerID(msg.sender); // Update emerald state emeralds[_upc].SetEmeraldState(EmeraldStates.State.Sold); // Emit the appropriate event emit Sold(_upc); } // Define a function 'shipItem' that allows laboratory confirm that the emerald was shipped function shipToManufacturer(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage sold(_upc) // Call modifier to verify caller of this function onlyCustodian { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShipToManufacture); // Emit the appropriate event emit ShipToManufacture(_upc); } // Define a function 'receiveFromStorage' that allows the manufacturer mark an item 'ManufacturerReceived' function receiveFromStorage(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shiptoManufacture(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields - ownerID, retailerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.ManufacturerReceived); // Emit the appropriate event emit ManufacturerReceived(_upc); } // Define a function 'manufactureEmerald' that allows the manufacturer to mark an item 'Manufactured' function manufactureEmerald( uint _upc, string memory _manofactureInfo ) public // Call modifier to check if upc has passed previous supply chain stage manufacturerReceived(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields emeralds[_upc].SetManufacturedInfo(_manofactureInfo); // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Manufactured); // Emit the appropriate event emit Manufactured(_upc); } // Define a function 'packCutEmerald' that allows the manufacturer to mark an emerald 'PackedForSale' function packCutEmerald(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage manufactured(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.PackedForSale); // Emit the appropriate event emit PackedForSale(upc); } // Define a function 'publishEmerald' that allows the manufacturer to mark an item 'Published' function publishEmerald(uint _upc, uint _marketPrice) public // Call modifier to check if upc has passed previous supply chain stage packedForSale(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { //Setup market price emeralds[_upc].SetMarketPrice(_marketPrice); // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Published); // Emit the appropriate event emit Published(_upc); } // Define a function 'buyFromManufacturer' that allows the manufacturer to mark an item 'Buyed' function buyFromManufacturer(uint _upc) public payable // Call modifier to check if upc has passed previous supply chain stage published(_upc) // Call modifer to check if buyer has paid enough paidEnough(emeralds[_upc].GetMarketPrice()) // Call modifer to send any excess ether back to buyer checkValue(_upc) onlyCustomer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Buyed); // Transfer money to Manufacturer (bool success, ) = emeralds[_upc].getManufacturerID().call{value: emeralds[_upc].GetMarketPrice()}(""); require(success, "Transfer failed"); // Set the customerID value emeralds[_upc].SetCustomerID(msg.sender); // Transfer ownership emeralds[_upc].SetOwnerID(msg.sender); // Emit the appropriate event emit Buyed(_upc); } // Define a function 'shipEmeraldToCustomer' that allows the consumer to mark an item 'ShippedToCustomer' function shipEmeraldToCustomer(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage buyed(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShippedToCustomer); // Emit the appropriate event emit ShippedToCustomer(_upc); } // Define a function 'deliverToCustomer' that allows the consumer to mark an item 'Delivered' function deliverToCustomer(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shippedToCustomer(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyCustomer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Delivered); // Emit the appropriate event emit Delivered(_upc); } // Define a function 'fetchItemBufferOne' that fetches the data function fetchItemBufferOne(uint _upc) public view returns (bytes memory) { return (emeralds[_upc].GetBasicInfo()); } // Define a function 'fetchItemBufferTwo' that fetches the data function fetchItemBufferTwo(uint _upc) public view returns (bytes memory) { return (emeralds[_upc].GetDetailedInfo()); } }
Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' Call modifier to check if upc has passed previous supply chain stage Call modifier to verify caller of this function Update the appropriate fields Emit the appropriate event
function StoreEmerald(uint _upc) public storageReceived(_upc) verifyCaller(emeralds[_upc].GetCustodianID()) onlyCustodian { emeralds[_upc].SetEmeraldState(EmeraldStates.State.Stored); emit Stored(_upc); }
5,454,280
pragma solidity >=0.4.24 < 0.6.4; // Import the library 'Roles' import "./Roles.sol"; // Define a contract 'RetailerRole' to manage this role - add, remove, check contract RetailerRole { using Roles for Roles.Role; // Define 2 events, one for Adding, and other for Removing event RetailerAdded(address indexed account, string name); event RetailerRemoved(address indexed account , string name); // Define a struct 'Retailers' by inheriting from 'Roles' library, struct Role Roles.Role private Retailers; // In the constructor make the address that deploys this contract the 1st Retailer constructor(string memory name) public { _addRetailer(msg.sender, name); } // Define a modifier that checks to see if msg.sender has the appropriate role modifier onlyRetailer() { require(isRetailer(msg.sender), "Acción solo permitida para el Retailer"); _; } function getNameRetailer(address account) public view returns (string memory) { return Retailers.getName(account); } /// Function to check caller `msg.sender` if he has Retailer role /// @return boolean for caller address state in `_Retailers` Role function amIRetailer() public view returns (bool) { return Retailers.has(msg.sender); } // Define a function 'isRetailer' to check this role function isRetailer(address account) public view returns (bool) { return Retailers.has(account); } // Define a function 'addRetailer' that adds this role function addRetailer(address account, string memory name) public onlyRetailer { _addRetailer(account, name); } // Define a function 'renounceRetailer' to renounce this role function renounceRetailer() public { _removeRetailer(msg.sender); } // Define an internal function '_addRetailer' to add this role, called by 'addRetailer' function _addRetailer(address account, string memory name) internal { Retailers.add(account,name); emit RetailerAdded(account, name); } // Define an internal function '_removeRetailer' to remove this role, called by 'removeRetailer' function _removeRetailer(address account) internal { Retailers.remove(account); emit RetailerRemoved(account, Retailers.name[account]); } }
Define a function 'isRetailer' to check this role
function isRetailer(address account) public view returns (bool) { return Retailers.has(account); }
12,902,350
./partial_match/1/0x86b8DE78e0200005Bc51FCade04bAbD88Cfc026F/sources/ETHGMELPTokenSharePool.sol
stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public override updateReward(msg.sender) checkStart { require(amount > 0, 'ETHGMELPTokenSharePool: Cannot stake 0'); super.stake(amount); emit Staked(msg.sender, amount); }
3,955,784
pragma solidity ^0.4.24; import "../../Pausable.sol"; import "../Module.sol"; import "../../interfaces/IERC20.sol"; import "../../interfaces/ISTO.sol"; import "./STOStorage.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title Interface to be implemented by all STO modules */ contract STO is ISTO, STOStorage, Module, Pausable { using SafeMath for uint256; enum FundRaiseType { ETH, POLY, SC } // Event event SetFundRaiseTypes(FundRaiseType[] _fundRaiseTypes); /** * @notice Returns funds raised by the STO */ function getRaised(FundRaiseType _fundRaiseType) public view returns (uint256) { return fundsRaised[uint8(_fundRaiseType)]; } /** * @notice Pause (overridden function) */ function pause() public onlyOwner { /*solium-disable-next-line security/no-block-members*/ require(now < endTime, "STO has been finalized"); super._pause(); } /** * @notice Unpause (overridden function) */ function unpause() public onlyOwner { super._unpause(); } function _setFundRaiseType(FundRaiseType[] _fundRaiseTypes) internal { // FundRaiseType[] parameter type ensures only valid values for _fundRaiseTypes require(_fundRaiseTypes.length > 0 && _fundRaiseTypes.length <= 3, "Raise type is not specified"); fundRaiseTypes[uint8(FundRaiseType.ETH)] = false; fundRaiseTypes[uint8(FundRaiseType.POLY)] = false; fundRaiseTypes[uint8(FundRaiseType.SC)] = false; for (uint8 j = 0; j < _fundRaiseTypes.length; j++) { fundRaiseTypes[uint8(_fundRaiseTypes[j])] = true; } emit SetFundRaiseTypes(_fundRaiseTypes); } /** * @notice Reclaims ERC20Basic compatible tokens * @dev We duplicate here due to the overriden owner & onlyOwner * @param _tokenContract The address of the token contract */ function reclaimERC20(address _tokenContract) external onlyOwner { require(_tokenContract != address(0), "Invalid address"); IERC20 token = IERC20(_tokenContract); uint256 balance = token.balanceOf(address(this)); require(token.transfer(msg.sender, balance), "Transfer failed"); } /** * @notice Reclaims ETH * @dev We duplicate here due to the overriden owner & onlyOwner */ function reclaimETH() external onlyOwner { msg.sender.transfer(address(this).balance); } }
Pause (overridden function)/
function pause() public onlyOwner { require(now < endTime, "STO has been finalized"); super._pause();
6,401,395
// SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ============================ CurveAMO_V2 =========================== // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Reviewer(s) / Contributor(s) // Sam Kazemian: https://github.com/samkazemian // github.com/denett import "./IStableSwap3Pool.sol"; import "./IMetaImplementationUSD.sol"; import "./ILiquidityGauge.sol"; import "./IMinter.sol"; import "../ERC20/ERC20.sol"; import "../Frax/Frax.sol"; import "../FXS/FXS.sol"; import "../Math/SafeMath.sol"; import "../Proxy/Initializable.sol"; contract CurveAMO_V2 is AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ IMetaImplementationUSD private frax3crv_metapool; IStableSwap3Pool private three_pool; ILiquidityGauge private gauge_frax3crv; ERC20 private three_pool_erc20; FRAXStablecoin private FRAX; FraxPool private pool; ERC20 private collateral_token; address private three_pool_address; address private three_pool_token_address; address private fxs_contract_address; address private collateral_token_address; address private crv_address; address public frax3crv_metapool_address; address public gauge_frax3crv_address; address public timelock_address; address public owner_address; address public custodian_address; address public pool_address; // Tracks FRAX uint256 public minted_frax_historical; uint256 public burned_frax_historical; // Max amount of FRAX outstanding the contract can mint from the FraxPool uint256 public max_frax_outstanding; // Tracks collateral uint256 public borrowed_collat_historical; uint256 public returned_collat_historical; // Max amount of collateral the contract can borrow from the FraxPool uint256 public collat_borrow_cap; // Minimum collateral ratio needed for new FRAX minting uint256 public min_cr; // Number of decimals under 18, for collateral token uint256 private missing_decimals; // Precision related uint256 private PRICE_PRECISION; // Min ratio of collat <-> 3crv conversions via add_liquidity / remove_liquidity; 1e6 uint256 public liq_slippage_3crv; // Min ratio of (FRAX + 3CRV) <-> FRAX3CRV-f-2 metapool conversions via add_liquidity / remove_liquidity; 1e6 uint256 public add_liq_slippage_metapool; uint256 public rem_liq_slippage_metapool; // Convergence window uint256 public convergence_window; // 1 cent // Default will use global_collateral_ratio() bool public custom_floor; uint256 public frax_floor; // Discount bool public set_discount; uint256 public discount_rate; // Collateral balance related bool public override_collat_balance; uint256 public override_collat_balance_amount; /* ========== CONSTRUCTOR ========== */ constructor( address _frax_contract_address, address _fxs_contract_address, address _collateral_address, address _creator_address, address _custodian_address, address _timelock_address, address _frax3crv_metapool_address, address _three_pool_address, address _three_pool_token_address, address _pool_address, address _gauge_frax3crv_address ) public { FRAX = FRAXStablecoin(_frax_contract_address); fxs_contract_address = _fxs_contract_address; collateral_token_address = _collateral_address; collateral_token = ERC20(_collateral_address); crv_address = 0xD533a949740bb3306d119CC777fa900bA034cd52; missing_decimals = uint(18).sub(collateral_token.decimals()); timelock_address = _timelock_address; owner_address = _creator_address; custodian_address = _custodian_address; frax3crv_metapool_address = _frax3crv_metapool_address; frax3crv_metapool = IMetaImplementationUSD(_frax3crv_metapool_address); three_pool_address = _three_pool_address; three_pool = IStableSwap3Pool(_three_pool_address); three_pool_token_address = _three_pool_token_address; three_pool_erc20 = ERC20(_three_pool_token_address); pool_address = _pool_address; pool = FraxPool(_pool_address); gauge_frax3crv_address = _gauge_frax3crv_address; gauge_frax3crv = ILiquidityGauge(_gauge_frax3crv_address); // Other variable initializations minted_frax_historical = 0; burned_frax_historical = 0; max_frax_outstanding = uint256(2000000e18); borrowed_collat_historical = 0; returned_collat_historical = 0; collat_borrow_cap = uint256(1000000e6); min_cr = 850000; PRICE_PRECISION = 1e6; liq_slippage_3crv = 800000; add_liq_slippage_metapool = 950000; rem_liq_slippage_metapool = 950000; convergence_window = 1e16; custom_floor = false; set_discount = false; override_collat_balance = false; } /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner_address, "Must be owner or timelock"); _; } modifier onlyCustodian() { require(msg.sender == custodian_address, "Must be rewards custodian"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[11] memory return_arr) { // ------------LP Balance------------ // Free LP uint256 lp_owned = frax3crv_metapool.balanceOf(address(this)); // Staked in the gauge uint256 lp_in_gauge = gauge_frax3crv.balanceOf(address(this)); lp_owned = lp_owned.add(lp_in_gauge); // ------------3pool Withdrawable------------ // Uses iterate() to get metapool withdrawable amounts at FRAX floor price (global_collateral_ratio) uint256 frax3crv_supply = frax3crv_metapool.totalSupply(); uint256 frax_withdrawable; uint256 _3pool_withdrawable; (frax_withdrawable, _3pool_withdrawable, ) = iterate(); if (frax3crv_supply > 0) { _3pool_withdrawable = _3pool_withdrawable.mul(lp_owned).div(frax3crv_supply); frax_withdrawable = frax_withdrawable.mul(lp_owned).div(frax3crv_supply); } else _3pool_withdrawable = 0; // ------------Frax Balance------------ // Frax sums uint256 frax_in_contract = FRAX.balanceOf(address(this)); // ------------Collateral Balance------------ // Free Collateral uint256 usdc_in_contract = collateral_token.balanceOf(address(this)); // Returns the dollar value withdrawable of USDC if the contract redeemed its 3CRV from the metapool; assume 1 USDC = $1 uint256 usdc_withdrawable = _3pool_withdrawable.mul(three_pool.get_virtual_price()).div(1e18).div(10 ** missing_decimals); // USDC subtotal assuming FRAX drops to the CR and all reserves are arbed uint256 usdc_subtotal = usdc_in_contract.add(usdc_withdrawable); // USDC total under optimistic conditions // uint256 usdc_total; uint256 usdc_total; { // uint256 frax_bal = fraxBalance(); usdc_total = usdc_subtotal + (frax_in_contract.add(frax_withdrawable)).mul(fraxDiscountRate()).div(1e6 * (10 ** missing_decimals)); } return [ frax_in_contract, // [0] frax_withdrawable, // [1] frax_withdrawable.add(frax_in_contract), // [2] usdc_in_contract, // [3] usdc_withdrawable, // [4] usdc_subtotal, // [5] usdc_total, // [6] lp_owned, // [7] frax3crv_supply, // [8] _3pool_withdrawable, // [9] lp_in_gauge // [10] ]; } function collatDollarBalance() public view returns (uint256) { if(override_collat_balance){ return override_collat_balance_amount; } return (showAllocations()[6] * (10 ** missing_decimals)); } function get_D() public view returns (uint256) { // Setting up constants uint256 A_PRECISION = 100; uint256[2] memory _xp = [three_pool_erc20.balanceOf(frax3crv_metapool_address), FRAX.balanceOf(frax3crv_metapool_address)]; uint256 N_COINS = 2; uint256 S; for(uint i = 0; i < N_COINS; i++){ S += _xp[i]; } if(S == 0){ return 0; } uint256 D = S; uint256 Ann = N_COINS * frax3crv_metapool.A_precise(); uint256 Dprev = 0; uint256 D_P; // Iteratively converge upon D for(uint i = 0; i < 256; i++){ D_P = D; for(uint j = 0; j < N_COINS; j++){ D_P = D * D / (_xp[j] * N_COINS); } Dprev = D; D = (Ann * S / A_PRECISION + D_P * N_COINS) * D / ((Ann - A_PRECISION) * D / A_PRECISION + (N_COINS + 1) * D_P); // Check if iteration has converged if(D > Dprev){ if(D - Dprev <= 1){ return D; } } else { if(Dprev - D <= 1){ return D; } } } // Placeholder, in case it does not converge (should do so within <= 4 rounds) revert("Convergence not reached"); } // Returns hypothetical reserves of metapool if the FRAX price went to the CR, // assuming no removal of liquidity from the metapool. function iterate() public view returns (uint256, uint256, uint256) { uint256 frax_balance = FRAX.balanceOf(frax3crv_metapool_address); uint256 crv3_balance = three_pool_erc20.balanceOf(frax3crv_metapool_address); uint256 floor_price_frax = uint(1e18).mul(fraxFloor()).div(1e6); uint256 crv3_received; uint256 dollar_value; // 3crv is usually slightly above $1 due to collecting 3pool swap fees uint256 virtual_price = three_pool.get_virtual_price(); for(uint i = 0; i < 256; i++){ crv3_received = frax3crv_metapool.get_dy(0, 1, 1e18, [frax_balance, crv3_balance]); dollar_value = crv3_received.mul(1e18).div(virtual_price); if(dollar_value <= floor_price_frax.add(convergence_window)){ return (frax_balance, crv3_balance, i); } uint256 frax_to_swap = frax_balance.div(10); crv3_balance = crv3_balance.sub(frax3crv_metapool.get_dy(0, 1, frax_to_swap, [frax_balance, crv3_balance])); frax_balance = frax_balance.add(frax_to_swap); } revert("No hypothetical point"); // in 256 rounds } function fraxFloor() public view returns (uint256) { if(custom_floor){ return frax_floor; } else { return FRAX.global_collateral_ratio(); } } function fraxDiscountRate() public view returns (uint256) { if(set_discount){ return discount_rate; } else { return FRAX.global_collateral_ratio(); } } // In FRAX function fraxBalance() public view returns (uint256) { if (minted_frax_historical >= burned_frax_historical) return minted_frax_historical.sub(burned_frax_historical); else return 0; } // In collateral function collateralBalance() public view returns (uint256) { if (borrowed_collat_historical >= returned_collat_historical) return borrowed_collat_historical.sub(returned_collat_historical); else return 0; } // REMOVED FOR CONTRACT SIZE CONSIDERATIONS // // Amount of FRAX3CRV deposited in the gauge contract // function metapoolLPInGauge() public view returns (uint256){ // return gauge_frax3crv.balanceOf(address(this)); // } // REMOVED FOR CONTRACT SIZE CONSIDERATIONS // // This function is problematic because it can be either a view or non-view // // The self._checkpoint(addr) call inside of it is mutative... // // Amount of CRV rewards mintable / claimable // function claimableCRV() public view returns (uint256){ // // Have to manually replicate the formula inside of LiquidityGaugeV2.vy // // otherwise, it would just be this: return gauge_frax3crv.claimable_tokens(address(this)); // uint256 integrate_fraction = gauge_frax3crv.integrate_fraction(address(this)); // uint256 other_side = IMinter(gauge_frax3crv.minter()).minted(address(this), gauge_frax3crv_address); // return integrate_fraction.sub(other_side); // } /* ========== RESTRICTED FUNCTIONS ========== */ // This is basically a workaround to transfer USDC from the FraxPool to this investor contract // This contract is essentially marked as a 'pool' so it can call OnlyPools functions like pool_mint and pool_burn_from // on the main FRAX contract // It mints FRAX from nothing, and redeems it on the target pool for collateral and FXS // The burn can be called separately later on function mintRedeemPart1(uint256 frax_amount) public onlyByOwnerOrGovernance { //require(allow_yearn || allow_aave || allow_compound, 'All strategies are currently off'); uint256 redemption_fee = pool.redemption_fee(); uint256 col_price_usd = pool.getCollateralPrice(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 redeem_amount_E6 = (frax_amount.mul(uint256(1e6).sub(redemption_fee))).div(1e6).div(10 ** missing_decimals); uint256 expected_collat_amount = redeem_amount_E6.mul(global_collateral_ratio).div(1e6); expected_collat_amount = expected_collat_amount.mul(1e6).div(col_price_usd); require(collateralBalance().add(expected_collat_amount) <= collat_borrow_cap, "Borrow cap"); borrowed_collat_historical = borrowed_collat_historical.add(expected_collat_amount); // Mint the frax FRAX.pool_mint(address(this), frax_amount); // Redeem the frax FRAX.approve(address(pool), frax_amount); pool.redeemFractionalFRAX(frax_amount, 0, 0); } function mintRedeemPart2() public onlyByOwnerOrGovernance { pool.collectRedemption(); } // Give USDC profits back function giveCollatBack(uint256 amount) public onlyByOwnerOrGovernance { collateral_token.transfer(address(pool), amount); returned_collat_historical = returned_collat_historical.add(amount); } // Burn unneeded or excess FRAX function burnFRAX(uint256 frax_amount) public onlyByOwnerOrGovernance { FRAX.burn(frax_amount); burned_frax_historical = burned_frax_historical.add(frax_amount); } function burnFXS(uint256 amount) public onlyByOwnerOrGovernance { FRAXShares(fxs_contract_address).approve(address(this), amount); FRAXShares(fxs_contract_address).pool_burn_from(address(this), amount); } function metapoolDeposit(uint256 _frax_amount, uint256 _collateral_amount) public onlyByOwnerOrGovernance returns (uint256 metapool_LP_received) { // Mint the FRAX component FRAX.pool_mint(address(this), _frax_amount); minted_frax_historical = minted_frax_historical.add(_frax_amount); require(fraxBalance() <= max_frax_outstanding, "max_frax_outstanding reached"); uint256 threeCRV_received = 0; if (_collateral_amount > 0) { // Approve the collateral to be added to 3pool collateral_token.approve(address(three_pool), _collateral_amount); // Convert collateral into 3pool uint256[3] memory three_pool_collaterals; three_pool_collaterals[uint256(1)] = _collateral_amount; { uint256 min_3pool_out = (_collateral_amount * (10 ** missing_decimals)).mul(liq_slippage_3crv).div(PRICE_PRECISION); three_pool.add_liquidity(three_pool_collaterals, min_3pool_out); } // Approve the 3pool for the metapool threeCRV_received = three_pool_erc20.balanceOf(address(this)); // WEIRD ISSUE: NEED TO DO three_pool_erc20.approve(address(three_pool), 0); first before every time // May be related to https://github.com/vyperlang/vyper/blob/3e1ff1eb327e9017c5758e24db4bdf66bbfae371/examples/tokens/ERC20.vy#L85 three_pool_erc20.approve(frax3crv_metapool_address, 0); three_pool_erc20.approve(frax3crv_metapool_address, threeCRV_received); } // Approve the FRAX for the metapool FRAX.approve(frax3crv_metapool_address, _frax_amount); { // Add the FRAX and the collateral to the metapool uint256 min_lp_out = (_frax_amount.add(threeCRV_received)).mul(add_liq_slippage_metapool).div(PRICE_PRECISION); metapool_LP_received = frax3crv_metapool.add_liquidity([_frax_amount, threeCRV_received], min_lp_out); } // Make sure the collateral ratio did not fall too much uint256 current_collateral_E18 = (FRAX.globalCollateralValue()).mul(10 ** missing_decimals); uint256 cur_frax_supply = FRAX.totalSupply(); uint256 new_cr = (current_collateral_E18.mul(PRICE_PRECISION)).div(cur_frax_supply); require (new_cr >= min_cr, "CR would be too low"); return metapool_LP_received; } function metapoolWithdrawAtCurRatio(uint256 _metapool_lp_in, bool burn_the_frax, uint256 min_frax, uint256 min_3pool) public onlyByOwnerOrGovernance returns (uint256 frax_received) { // Approve the metapool LP tokens for the metapool contract frax3crv_metapool.approve(address(this), _metapool_lp_in); // Withdraw FRAX and 3pool from the metapool at the current balance uint256 three_pool_received; { uint256[2] memory result_arr = frax3crv_metapool.remove_liquidity(_metapool_lp_in, [min_frax, min_3pool]); frax_received = result_arr[0]; three_pool_received = result_arr[1]; } // Convert the 3pool into the collateral three_pool_erc20.approve(address(three_pool), 0); three_pool_erc20.approve(address(three_pool), three_pool_received); { // Add the FRAX and the collateral to the metapool uint256 min_collat_out = three_pool_received.mul(liq_slippage_3crv).div(PRICE_PRECISION * (10 ** missing_decimals)); three_pool.remove_liquidity_one_coin(three_pool_received, 1, min_collat_out); } // Optionally burn the FRAX if (burn_the_frax){ burnFRAX(frax_received); } } function metapoolWithdrawFrax(uint256 _metapool_lp_in, bool burn_the_frax) public onlyByOwnerOrGovernance returns (uint256 frax_received) { // Withdraw FRAX from the metapool uint256 min_frax_out = _metapool_lp_in.mul(rem_liq_slippage_metapool).div(PRICE_PRECISION); frax_received = frax3crv_metapool.remove_liquidity_one_coin(_metapool_lp_in, 0, min_frax_out); // Optionally burn the FRAX if (burn_the_frax){ burnFRAX(frax_received); } } function metapoolWithdraw3pool(uint256 _metapool_lp_in) public onlyByOwnerOrGovernance { // Withdraw 3pool from the metapool uint256 min_3pool_out = _metapool_lp_in.mul(rem_liq_slippage_metapool).div(PRICE_PRECISION); frax3crv_metapool.remove_liquidity_one_coin(_metapool_lp_in, 1, min_3pool_out); } function three_pool_to_collateral(uint256 _3pool_in) public onlyByOwnerOrGovernance { // Convert the 3pool into the collateral // WEIRD ISSUE: NEED TO DO three_pool_erc20.approve(address(three_pool), 0); first before every time // May be related to https://github.com/vyperlang/vyper/blob/3e1ff1eb327e9017c5758e24db4bdf66bbfae371/examples/tokens/ERC20.vy#L85 three_pool_erc20.approve(address(three_pool), 0); three_pool_erc20.approve(address(three_pool), _3pool_in); uint256 min_collat_out = _3pool_in.mul(liq_slippage_3crv).div(PRICE_PRECISION * (10 ** missing_decimals)); three_pool.remove_liquidity_one_coin(_3pool_in, 1, min_collat_out); } function metapoolWithdrawAndConvert3pool(uint256 _metapool_lp_in) public onlyByOwnerOrGovernance { metapoolWithdraw3pool(_metapool_lp_in); three_pool_to_collateral(three_pool_erc20.balanceOf(address(this))); } // Deposit Metapool LP tokens into the Curve DAO for gauge rewards, if any function depositToGauge(uint256 _metapool_lp_in) public onlyByOwnerOrGovernance { // Approve the metapool LP tokens for the gauge contract frax3crv_metapool.approve(address(gauge_frax3crv), _metapool_lp_in); // Deposit the metapool LP into the gauge contract gauge_frax3crv.deposit(_metapool_lp_in); } // Withdraw Metapool LP from Curve DAO back to this contract function withdrawFromGauge(uint256 _metapool_lp_out) public onlyByOwnerOrGovernance { gauge_frax3crv.withdraw(_metapool_lp_out); } // Checkpoint the Gauge for this address function checkpointGauge() public onlyByOwnerOrGovernance { gauge_frax3crv.user_checkpoint(address(this)); } // Retrieve CRV gauge rewards, if any function collectCRVFromGauge() public onlyByOwnerOrGovernance { gauge_frax3crv.claim_rewards(address(this)); IMinter(gauge_frax3crv.minter()).mint(gauge_frax3crv_address); } /* ========== Custodian ========== */ // NOTE: The custodian_address can be set to the governance contract to be used as // a mega-voter or sorts. The CRV here can be converted to veCRV and then used to vote function withdrawCRVRewards() public onlyCustodian { ERC20(crv_address).transfer(custodian_address, ERC20(crv_address).balanceOf(address(this))); } /* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */ function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function setMiscRewardsCustodian(address _custodian_address) external onlyByOwnerOrGovernance { custodian_address = _custodian_address; } function setPool(address _pool_address) external onlyByOwnerOrGovernance { pool_address = _pool_address; pool = FraxPool(_pool_address); } function setThreePool(address _three_pool_address, address _three_pool_token_address) external onlyByOwnerOrGovernance { three_pool_address = _three_pool_address; three_pool = IStableSwap3Pool(_three_pool_address); three_pool_token_address = _three_pool_token_address; three_pool_erc20 = ERC20(_three_pool_token_address); } function setMetapool(address _metapool_address) public onlyByOwnerOrGovernance { frax3crv_metapool_address = _metapool_address; frax3crv_metapool = IMetaImplementationUSD(_metapool_address); } function setGauge(address _gauge_frax3crv_address) public onlyByOwnerOrGovernance { gauge_frax3crv_address = _gauge_frax3crv_address; gauge_frax3crv = ILiquidityGauge(_gauge_frax3crv_address); } function setCollatBorrowCap(uint256 _collat_borrow_cap) external onlyByOwnerOrGovernance { collat_borrow_cap = _collat_borrow_cap; } function setMaxFraxOutstanding(uint256 _max_frax_outstanding) external onlyByOwnerOrGovernance { max_frax_outstanding = _max_frax_outstanding; } function setMinimumCollateralRatio(uint256 _min_cr) external onlyByOwnerOrGovernance { min_cr = _min_cr; } function setConvergenceWindow(uint256 _window) external onlyByOwnerOrGovernance { convergence_window = _window; } function setOverrideCollatBalance(bool _state, uint256 _balance) external onlyByOwnerOrGovernance { override_collat_balance = _state; override_collat_balance_amount = _balance; } // in terms of 1e6 (overriding global_collateral_ratio) function setCustomFloor(bool _state, uint256 _floor_price) external onlyByOwnerOrGovernance { custom_floor = _state; frax_floor = _floor_price; } // in terms of 1e6 (overriding global_collateral_ratio) function setDiscountRate(bool _state, uint256 _discount_rate) external onlyByOwnerOrGovernance { set_discount = _state; discount_rate = _discount_rate; } function setSlippages(uint256 _liq_slippage_3crv, uint256 _add_liq_slippage_metapool, uint256 _rem_liq_slippage_metapool) external onlyByOwnerOrGovernance { liq_slippage_3crv = _liq_slippage_3crv; add_liq_slippage_metapool = _add_liq_slippage_metapool; rem_liq_slippage_metapool = _rem_liq_slippage_metapool; } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard ERC20(tokenAddress).transfer(custodian_address, tokenAmount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; interface IStableSwap3Pool { // Deployment function __init__(address _owner, address[3] memory _coins, address _pool_token, uint256 _A, uint256 _fee, uint256 _admin_fee) external; // ERC20 Standard function decimals() external view returns (uint); function transfer(address _to, uint _value) external returns (uint256); function transferFrom(address _from, address _to, uint _value) external returns (bool); function approve(address _spender, uint _value) external returns (bool); function totalSupply() external view returns (uint); function mint(address _to, uint256 _value) external returns (bool); function burnFrom(address _to, uint256 _value) external returns (bool); function balanceOf(address _owner) external view returns (uint256); // 3Pool function A() external view returns (uint); function get_virtual_price() external view returns (uint); function calc_token_amount(uint[3] memory amounts, bool deposit) external view returns (uint); function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount) external; function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256); function get_dy_underlying(int128 i, int128 j, uint256 dx) external view returns (uint256); function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external; function remove_liquidity(uint256 _amount, uint256[3] memory min_amounts) external; function remove_liquidity_imbalance(uint256[3] memory amounts, uint256 max_burn_amount) external; function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_amount) external; // Admin functions function ramp_A(uint256 _future_A, uint256 _future_time) external; function stop_ramp_A() external; function commit_new_fee(uint256 new_fee, uint256 new_admin_fee) external; function apply_new_fee() external; function commit_transfer_ownership(address _owner) external; function apply_transfer_ownership() external; function revert_transfer_ownership() external; function admin_balances(uint256 i) external returns (uint256); function withdraw_admin_fees() external; function donate_admin_fees() external; function kill_me() external; function unkill_me() external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; interface IMetaImplementationUSD { // Deployment function __init__() external; function initialize(string memory _name, string memory _symbol, address _coin, uint _decimals, uint _A, uint _fee, address _admin) external; // ERC20 Standard function decimals() external view returns (uint); function transfer(address _to, uint _value) external returns (uint256); function transferFrom(address _from, address _to, uint _value) external returns (bool); function approve(address _spender, uint _value) external returns (bool); function balanceOf(address _owner) external view returns (uint256); function totalSupply() external view returns (uint256); // StableSwap Functionality function get_previous_balances() external view returns (uint[2] memory); function get_twap_balances(uint[2] memory _first_balances, uint[2] memory _last_balances, uint _time_elapsed) external view returns (uint[2] memory); function get_price_cumulative_last() external view returns (uint[2] memory); function admin_fee() external view returns (uint); function A() external view returns (uint); function A_precise() external view returns (uint); function get_virtual_price() external view returns (uint); function calc_token_amount(uint[2] memory _amounts, bool _is_deposit) external view returns (uint); function calc_token_amount(uint[2] memory _amounts, bool _is_deposit, bool _previous) external view returns (uint); function add_liquidity(uint[2] memory _amounts, uint _min_mint_amount) external returns (uint); function add_liquidity(uint[2] memory _amounts, uint _min_mint_amount, address _receiver) external returns (uint); function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256); function get_dy(int128 i, int128 j, uint256 dx, uint256[2] memory _balances) external view returns (uint256); function get_dy_underlying(int128 i, int128 j, uint256 dx) external view returns (uint256); function get_dy_underlying(int128 i, int128 j, uint256 dx, uint256[2] memory _balances) external view returns (uint256); function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256); function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy, address _receiver) external returns (uint256); function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256); function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address _receiver) external returns (uint256); function remove_liquidity(uint256 _burn_amount, uint256[2] memory _min_amounts) external returns (uint256[2] memory); function remove_liquidity(uint256 _burn_amount, uint256[2] memory _min_amounts, address _receiver) external returns (uint256[2] memory); function remove_liquidity_imbalance(uint256[2] memory _amounts, uint256 _max_burn_amount) external returns (uint256); function remove_liquidity_imbalance(uint256[2] memory _amounts, uint256 _max_burn_amount, address _receiver) external returns (uint256); function calc_withdraw_one_coin(uint256 _burn_amount, int128 i) external view returns (uint256); function calc_withdraw_one_coin(uint256 _burn_amount, int128 i, bool _previous) external view returns (uint256); function remove_liquidity_one_coin(uint256 _burn_amount, int128 i, uint256 _min_received) external returns (uint256); function remove_liquidity_one_coin(uint256 _burn_amount, int128 i, uint256 _min_received, address _receiver) external returns (uint256); function ramp_A(uint256 _future_A, uint256 _future_time) external; function stop_ramp_A() external; function admin_balances(uint256 i) external view returns (uint256); function withdraw_admin_fees() external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // https://github.com/swervefi/swerve/blob/master/packages/swerve-contracts/interfaces/ILiquidityGauge.sol interface ILiquidityGauge { // Public variables function minter() external view returns (address); function crv_token() external view returns (address); function lp_token() external view returns (address); function controller() external view returns (address); function voting_escrow() external view returns (address); function balanceOf(address) external view returns (uint256); function totalSupply() external view returns (uint256); function future_epoch_time() external view returns (uint256); function approved_to_deposit(address, address) external view returns (bool); function working_balances(address) external view returns (uint256); function working_supply() external view returns (uint256); function period() external view returns (int128); function period_timestamp(uint256) external view returns (uint256); function integrate_inv_supply(uint256) external view returns (uint256); function integrate_inv_supply_of(address) external view returns (uint256); function integrate_checkpoint_of(address) external view returns (uint256); function integrate_fraction(address) external view returns (uint256); function inflation_rate() external view returns (uint256); // Getter functions function integrate_checkpoint() external view returns (uint256); // External functions function user_checkpoint(address) external returns (bool); function claim_rewards(address) external; function claimable_tokens(address) external view returns (uint256); // function can be manually changed to "view" in the ABI function kick(address) external; function set_approve_deposit(address, bool) external; function deposit(uint256) external; function deposit(uint256, address) external; function withdraw(uint256) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // https://github.com/swervefi/swerve/blob/master/packages/swerve-contracts/interfaces/IMinter.sol interface IMinter { // Public variables function minter() external view returns (address); function controller() external view returns (address); function minted(address, address) external view returns (uint256); function allowed_to_mint_for(address, address) external view returns (bool); // External functions function mint(address) external; function mint_many(address[] memory) external; function mint_for(address, address) external; function toggle_approve_mint(address) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "../Common/Context.sol"; import "./IERC20.sol"; import "../Math/SafeMath.sol"; import "../Utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address.approve(address spender, uint256 amount) */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of `from`'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of `from`'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================= FRAXStablecoin (FRAX) ====================== // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../Common/Context.sol"; import "../ERC20/IERC20.sol"; import "../ERC20/ERC20Custom.sol"; import "../ERC20/ERC20.sol"; import "../Math/SafeMath.sol"; import "../FXS/FXS.sol"; import "./Pools/FraxPool.sol"; import "../Oracle/UniswapPairOracle.sol"; import "../Oracle/ChainlinkETHUSDPriceConsumer.sol"; import "../Governance/AccessControl.sol"; contract FRAXStablecoin is ERC20Custom, AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ enum PriceChoice { FRAX, FXS } ChainlinkETHUSDPriceConsumer private eth_usd_pricer; uint8 private eth_usd_pricer_decimals; UniswapPairOracle private fraxEthOracle; UniswapPairOracle private fxsEthOracle; string public symbol; string public name; uint8 public constant decimals = 18; address public owner_address; address public creator_address; address public timelock_address; // Governance timelock address address public controller_address; // Controller contract to dynamically adjust system parameters automatically address public fxs_address; address public frax_eth_oracle_address; address public fxs_eth_oracle_address; address public weth_address; address public eth_usd_consumer_address; uint256 public constant genesis_supply = 2000000e18; // 2M FRAX (only for testing, genesis supply will be 5k on Mainnet). This is to help with establishing the Uniswap pools, as they need liquidity // The addresses in this array are added by the oracle and these contracts are able to mint frax address[] public frax_pools_array; // Mapping is also used for faster verification mapping(address => bool) public frax_pools; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 public global_collateral_ratio; // 6 decimals of precision, e.g. 924102 = 0.924102 uint256 public redemption_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee uint256 public minting_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee uint256 public frax_step; // Amount to change the collateralization ratio by upon refreshCollateralRatio() uint256 public refresh_cooldown; // Seconds to wait before being able to run refreshCollateralRatio() again uint256 public price_target; // The price of FRAX at which the collateral ratio will respond to; this value is only used for the collateral ratio mechanism and not for minting and redeeming which are hardcoded at $1 uint256 public price_band; // The bound above and below the price target at which the refreshCollateralRatio() will not change the collateral ratio address public DEFAULT_ADMIN_ADDRESS; bytes32 public constant COLLATERAL_RATIO_PAUSER = keccak256("COLLATERAL_RATIO_PAUSER"); bool public collateral_ratio_paused = false; /* ========== MODIFIERS ========== */ modifier onlyCollateralRatioPauser() { require(hasRole(COLLATERAL_RATIO_PAUSER, msg.sender)); _; } modifier onlyPools() { require(frax_pools[msg.sender] == true, "Only frax pools can call this function"); _; } modifier onlyByOwnerOrGovernance() { require(msg.sender == owner_address || msg.sender == timelock_address || msg.sender == controller_address, "You are not the owner, controller, or the governance timelock"); _; } modifier onlyByOwnerGovernanceOrPool() { require( msg.sender == owner_address || msg.sender == timelock_address || frax_pools[msg.sender] == true, "You are not the owner, the governance timelock, or a pool"); _; } /* ========== CONSTRUCTOR ========== */ constructor( string memory _name, string memory _symbol, address _creator_address, address _timelock_address ) public { name = _name; symbol = _symbol; creator_address = _creator_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); DEFAULT_ADMIN_ADDRESS = _msgSender(); owner_address = _creator_address; _mint(creator_address, genesis_supply); grantRole(COLLATERAL_RATIO_PAUSER, creator_address); grantRole(COLLATERAL_RATIO_PAUSER, timelock_address); frax_step = 2500; // 6 decimals of precision, equal to 0.25% global_collateral_ratio = 1000000; // Frax system starts off fully collateralized (6 decimals of precision) refresh_cooldown = 3600; // Refresh cooldown period is set to 1 hour (3600 seconds) at genesis price_target = 1000000; // Collateral ratio will adjust according to the $1 price target at genesis price_band = 5000; // Collateral ratio will not adjust if between $0.995 and $1.005 at genesis } /* ========== VIEWS ========== */ // Choice = 'FRAX' or 'FXS' for now function oracle_price(PriceChoice choice) internal view returns (uint256) { // Get the ETH / USD price first, and cut it down to 1e6 precision uint256 eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals); uint256 price_vs_eth; if (choice == PriceChoice.FRAX) { price_vs_eth = uint256(fraxEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FRAX if you put in PRICE_PRECISION WETH } else if (choice == PriceChoice.FXS) { price_vs_eth = uint256(fxsEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FXS if you put in PRICE_PRECISION WETH } else revert("INVALID PRICE CHOICE. Needs to be either 0 (FRAX) or 1 (FXS)"); // Will be in 1e6 format return eth_usd_price.mul(PRICE_PRECISION).div(price_vs_eth); } // Returns X FRAX = 1 USD function frax_price() public view returns (uint256) { return oracle_price(PriceChoice.FRAX); } // Returns X FXS = 1 USD function fxs_price() public view returns (uint256) { return oracle_price(PriceChoice.FXS); } function eth_usd_price() public view returns (uint256) { return uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals); } // This is needed to avoid costly repeat calls to different getter functions // It is cheaper gas-wise to just dump everything and only use some of the info function frax_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { return ( oracle_price(PriceChoice.FRAX), // frax_price() oracle_price(PriceChoice.FXS), // fxs_price() totalSupply(), // totalSupply() global_collateral_ratio, // global_collateral_ratio() globalCollateralValue(), // globalCollateralValue minting_fee, // minting_fee() redemption_fee, // redemption_fee() uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals) //eth_usd_price ); } // Iterate through all frax pools and calculate all value of collateral in all pools globally function globalCollateralValue() public view returns (uint256) { uint256 total_collateral_value_d18 = 0; for (uint i = 0; i < frax_pools_array.length; i++){ // Exclude null addresses if (frax_pools_array[i] != address(0)){ total_collateral_value_d18 = total_collateral_value_d18.add(FraxPool(frax_pools_array[i]).collatDollarBalance()); } } return total_collateral_value_d18; } /* ========== PUBLIC FUNCTIONS ========== */ // There needs to be a time interval that this can be called. Otherwise it can be called multiple times per expansion. uint256 public last_call_time; // Last time the refreshCollateralRatio function was called function refreshCollateralRatio() public { require(collateral_ratio_paused == false, "Collateral Ratio has been paused"); uint256 frax_price_cur = frax_price(); require(block.timestamp - last_call_time >= refresh_cooldown, "Must wait for the refresh cooldown since last refresh"); // Step increments are 0.25% (upon genesis, changable by setFraxStep()) if (frax_price_cur > price_target.add(price_band)) { //decrease collateral ratio if(global_collateral_ratio <= frax_step){ //if within a step of 0, go to 0 global_collateral_ratio = 0; } else { global_collateral_ratio = global_collateral_ratio.sub(frax_step); } } else if (frax_price_cur < price_target.sub(price_band)) { //increase collateral ratio if(global_collateral_ratio.add(frax_step) >= 1000000){ global_collateral_ratio = 1000000; // cap collateral ratio at 1.000000 } else { global_collateral_ratio = global_collateral_ratio.add(frax_step); } } last_call_time = block.timestamp; // Set the time of the last expansion } /* ========== RESTRICTED FUNCTIONS ========== */ // Used by pools when user redeems function pool_burn_from(address b_address, uint256 b_amount) public onlyPools { super._burnFrom(b_address, b_amount); emit FRAXBurned(b_address, msg.sender, b_amount); } // This function is what other frax pools will call to mint new FRAX function pool_mint(address m_address, uint256 m_amount) public onlyPools { super._mint(m_address, m_amount); emit FRAXMinted(msg.sender, m_address, m_amount); } // Adds collateral addresses supported, such as tether and busd, must be ERC20 function addPool(address pool_address) public onlyByOwnerOrGovernance { require(frax_pools[pool_address] == false, "address already exists"); frax_pools[pool_address] = true; frax_pools_array.push(pool_address); } // Remove a pool function removePool(address pool_address) public onlyByOwnerOrGovernance { require(frax_pools[pool_address] == true, "address doesn't exist already"); // Delete from the mapping delete frax_pools[pool_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < frax_pools_array.length; i++){ if (frax_pools_array[i] == pool_address) { frax_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function setRedemptionFee(uint256 red_fee) public onlyByOwnerOrGovernance { redemption_fee = red_fee; } function setMintingFee(uint256 min_fee) public onlyByOwnerOrGovernance { minting_fee = min_fee; } function setFraxStep(uint256 _new_step) public onlyByOwnerOrGovernance { frax_step = _new_step; } function setPriceTarget (uint256 _new_price_target) public onlyByOwnerOrGovernance { price_target = _new_price_target; } function setRefreshCooldown(uint256 _new_cooldown) public onlyByOwnerOrGovernance { refresh_cooldown = _new_cooldown; } function setFXSAddress(address _fxs_address) public onlyByOwnerOrGovernance { fxs_address = _fxs_address; } function setETHUSDOracle(address _eth_usd_consumer_address) public onlyByOwnerOrGovernance { eth_usd_consumer_address = _eth_usd_consumer_address; eth_usd_pricer = ChainlinkETHUSDPriceConsumer(eth_usd_consumer_address); eth_usd_pricer_decimals = eth_usd_pricer.getDecimals(); } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setController(address _controller_address) external onlyByOwnerOrGovernance { controller_address = _controller_address; } function setPriceBand(uint256 _price_band) external onlyByOwnerOrGovernance { price_band = _price_band; } // Sets the FRAX_ETH Uniswap oracle address function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance { frax_eth_oracle_address = _frax_oracle_addr; fraxEthOracle = UniswapPairOracle(_frax_oracle_addr); weth_address = _weth_address; } // Sets the FXS_ETH Uniswap oracle address function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance { fxs_eth_oracle_address = _fxs_oracle_addr; fxsEthOracle = UniswapPairOracle(_fxs_oracle_addr); weth_address = _weth_address; } function toggleCollateralRatio() public onlyCollateralRatioPauser { collateral_ratio_paused = !collateral_ratio_paused; } /* ========== EVENTS ========== */ // Track FRAX burned event FRAXBurned(address indexed from, address indexed to, uint256 amount); // Track FRAX minted event FRAXMinted(address indexed from, address indexed to, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================= FRAXShares (FXS) ========================= // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../Common/Context.sol"; import "../ERC20/ERC20Custom.sol"; import "../ERC20/IERC20.sol"; import "../Frax/Frax.sol"; import "../Math/SafeMath.sol"; import "../Governance/AccessControl.sol"; contract FRAXShares is ERC20Custom, AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ string public symbol; string public name; uint8 public constant decimals = 18; address public FRAXStablecoinAdd; uint256 public constant genesis_supply = 100000000e18; // 100M is printed upon genesis uint256 public FXS_DAO_min; // Minimum FXS required to join DAO groups address public owner_address; address public oracle_address; address public timelock_address; // Governance timelock address FRAXStablecoin private FRAX; bool public trackingVotes = true; // Tracking votes (only change if need to disable votes) // A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } // A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; // The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /* ========== MODIFIERS ========== */ modifier onlyPools() { require(FRAX.frax_pools(msg.sender) == true, "Only frax pools can mint new FRAX"); _; } modifier onlyByOwnerOrGovernance() { require(msg.sender == owner_address || msg.sender == timelock_address, "You are not an owner or the governance timelock"); _; } /* ========== CONSTRUCTOR ========== */ constructor( string memory _name, string memory _symbol, address _oracle_address, address _owner_address, address _timelock_address ) public { name = _name; symbol = _symbol; owner_address = _owner_address; oracle_address = _oracle_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _mint(owner_address, genesis_supply); // Do a checkpoint for the owner _writeCheckpoint(owner_address, 0, 0, uint96(genesis_supply)); } /* ========== RESTRICTED FUNCTIONS ========== */ function setOracle(address new_oracle) external onlyByOwnerOrGovernance { oracle_address = new_oracle; } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setFRAXAddress(address frax_contract_address) external onlyByOwnerOrGovernance { FRAX = FRAXStablecoin(frax_contract_address); } function setFXSMinDAO(uint256 min_FXS) external onlyByOwnerOrGovernance { FXS_DAO_min = min_FXS; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function mint(address to, uint256 amount) public onlyPools { _mint(to, amount); } // This function is what other frax pools will call to mint new FXS (similar to the FRAX mint) function pool_mint(address m_address, uint256 m_amount) external onlyPools { if(trackingVotes){ uint32 srcRepNum = numCheckpoints[address(this)]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0; uint96 srcRepNew = add96(srcRepOld, uint96(m_amount), "pool_mint new votes overflows"); _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // mint new votes trackVotes(address(this), m_address, uint96(m_amount)); } super._mint(m_address, m_amount); emit FXSMinted(address(this), m_address, m_amount); } // This function is what other frax pools will call to burn FXS function pool_burn_from(address b_address, uint256 b_amount) external onlyPools { if(trackingVotes){ trackVotes(b_address, address(this), uint96(b_amount)); uint32 srcRepNum = numCheckpoints[address(this)]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, uint96(b_amount), "pool_burn_from new votes underflows"); _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // burn votes } super._burnFrom(b_address, b_amount); emit FXSBurned(b_address, address(this), b_amount); } function toggleVotes() external onlyByOwnerOrGovernance { trackingVotes = !trackingVotes; } /* ========== OVERRIDDEN PUBLIC FUNCTIONS ========== */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { if(trackingVotes){ // Transfer votes trackVotes(_msgSender(), recipient, uint96(amount)); } _transfer(_msgSender(), recipient, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { if(trackingVotes){ // Transfer votes trackVotes(sender, recipient, uint96(amount)); } _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /* ========== PUBLIC FUNCTIONS ========== */ /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "FXS::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } /* ========== INTERNAL FUNCTIONS ========== */ // From compound's _moveDelegates // Keep track of votes. "Delegates" is a misnomer here function trackVotes(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "FXS::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "FXS::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address voter, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "FXS::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[voter][nCheckpoints - 1].votes = newVotes; } else { checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[voter] = nCheckpoints + 1; } emit VoterVotesChanged(voter, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } /* ========== EVENTS ========== */ /// @notice An event thats emitted when a voters account's vote balance changes event VoterVotesChanged(address indexed voter, uint previousBalance, uint newBalance); // Track FXS burned event FXSBurned(address indexed from, address indexed to, uint256 amount); // Track FXS minted event FXSMinted(address indexed from, address indexed to, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.6.0 <0.9.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "../Common/Context.sol"; import "../Math/SafeMath.sol"; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11 <0.9.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "../Common/Context.sol"; import "./IERC20.sol"; import "../Math/SafeMath.sol"; import "../Utils/Address.sol"; // Due to compiling issues, _name, _symbol, and _decimals were removed /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Custom is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address.approve(address spender, uint256 amount) */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of `from`'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of `from`'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ============================= FraxPool ============================= // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../../Math/SafeMath.sol"; import "../../FXS/FXS.sol"; import "../../Frax/Frax.sol"; import "../../ERC20/ERC20.sol"; import "../../Oracle/UniswapPairOracle.sol"; import "../../Governance/AccessControl.sol"; import "./FraxPoolLibrary.sol"; contract FraxPool is AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ ERC20 private collateral_token; address private collateral_address; address private owner_address; address private frax_contract_address; address private fxs_contract_address; address private timelock_address; FRAXShares private FXS; FRAXStablecoin private FRAX; UniswapPairOracle private collatEthOracle; address public collat_eth_oracle_address; address private weth_address; uint256 public minting_fee; uint256 public redemption_fee; uint256 public buyback_fee; uint256 public recollat_fee; mapping (address => uint256) public redeemFXSBalances; mapping (address => uint256) public redeemCollateralBalances; uint256 public unclaimedPoolCollateral; uint256 public unclaimedPoolFXS; mapping (address => uint256) public lastRedeemed; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_MAX = 1e6; // Number of decimals needed to get to 18 uint256 private immutable missing_decimals; // Pool_ceiling is the total units of collateral that a pool contract can hold uint256 public pool_ceiling = 0; // Stores price of the collateral, if price is paused uint256 public pausedPrice = 0; // Bonus rate on FXS minted during recollateralizeFRAX(); 6 decimals of precision, set to 0.75% on genesis uint256 public bonus_rate = 7500; // Number of blocks to wait before being able to collectRedemption() uint256 public redemption_delay = 1; // AccessControl Roles bytes32 private constant MINT_PAUSER = keccak256("MINT_PAUSER"); bytes32 private constant REDEEM_PAUSER = keccak256("REDEEM_PAUSER"); bytes32 private constant BUYBACK_PAUSER = keccak256("BUYBACK_PAUSER"); bytes32 private constant RECOLLATERALIZE_PAUSER = keccak256("RECOLLATERALIZE_PAUSER"); bytes32 private constant COLLATERAL_PRICE_PAUSER = keccak256("COLLATERAL_PRICE_PAUSER"); // AccessControl state variables bool public mintPaused = false; bool public redeemPaused = false; bool public recollateralizePaused = false; bool public buyBackPaused = false; bool public collateralPricePaused = false; /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock"); _; } modifier notRedeemPaused() { require(redeemPaused == false, "Redeeming is paused"); _; } modifier notMintPaused() { require(mintPaused == false, "Minting is paused"); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _frax_contract_address, address _fxs_contract_address, address _collateral_address, address _creator_address, address _timelock_address, uint256 _pool_ceiling ) public { FRAX = FRAXStablecoin(_frax_contract_address); FXS = FRAXShares(_fxs_contract_address); frax_contract_address = _frax_contract_address; fxs_contract_address = _fxs_contract_address; collateral_address = _collateral_address; timelock_address = _timelock_address; owner_address = _creator_address; collateral_token = ERC20(_collateral_address); pool_ceiling = _pool_ceiling; missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); grantRole(MINT_PAUSER, timelock_address); grantRole(REDEEM_PAUSER, timelock_address); grantRole(RECOLLATERALIZE_PAUSER, timelock_address); grantRole(BUYBACK_PAUSER, timelock_address); grantRole(COLLATERAL_PRICE_PAUSER, timelock_address); } /* ========== VIEWS ========== */ // Returns dollar value of collateral held in this Frax pool function collatDollarBalance() public view returns (uint256) { if(collateralPricePaused == true){ return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(pausedPrice).div(PRICE_PRECISION); } else { uint256 eth_usd_price = FRAX.eth_usd_price(); uint256 eth_collat_price = collatEthOracle.consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals))); uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price); return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6); } } // Returns the value of excess collateral held in this Frax pool, compared to what is needed to maintain the global collateral ratio function availableExcessCollatDV() public view returns (uint256) { uint256 total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR > 1 uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio if (global_collat_value > required_collat_dollar_value_d18) return global_collat_value.sub(required_collat_dollar_value_d18); else return 0; } /* ========== PUBLIC FUNCTIONS ========== */ // Returns the price of the pool collateral in USD function getCollateralPrice() public view returns (uint256) { if(collateralPricePaused == true){ return pausedPrice; } else { uint256 eth_usd_price = FRAX.eth_usd_price(); return eth_usd_price.mul(PRICE_PRECISION).div(collatEthOracle.consult(weth_address, PRICE_PRECISION * (10 ** missing_decimals))); } } function setCollatETHOracle(address _collateral_weth_oracle_address, address _weth_address) external onlyByOwnerOrGovernance { collat_eth_oracle_address = _collateral_weth_oracle_address; collatEthOracle = UniswapPairOracle(_collateral_weth_oracle_address); weth_address = _weth_address; } // We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency function mint1t1FRAX(uint256 collateral_amount, uint256 FRAX_out_min) external notMintPaused { uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); require(FRAX.global_collateral_ratio() >= COLLATERAL_RATIO_MAX, "Collateral ratio must be >= 1"); require((collateral_token.balanceOf(address(this))).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "[Pool's Closed]: Ceiling reached"); (uint256 frax_amount_d18) = FraxPoolLibrary.calcMint1t1FRAX( getCollateralPrice(), collateral_amount_d18 ); //1 FRAX for each $1 worth of collateral frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); //remove precision at the end require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached"); collateral_token.transferFrom(msg.sender, address(this), collateral_amount); FRAX.pool_mint(msg.sender, frax_amount_d18); } // 0% collateral-backed function mintAlgorithmicFRAX(uint256 fxs_amount_d18, uint256 FRAX_out_min) external notMintPaused { uint256 fxs_price = FRAX.fxs_price(); require(FRAX.global_collateral_ratio() == 0, "Collateral ratio must be 0"); (uint256 frax_amount_d18) = FraxPoolLibrary.calcMintAlgorithmicFRAX( fxs_price, // X FXS / 1 USD fxs_amount_d18 ); frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached"); FXS.pool_burn_from(msg.sender, fxs_amount_d18); FRAX.pool_mint(msg.sender, frax_amount_d18); } // Will fail if fully collateralized or fully algorithmic // > 0% and < 100% collateral-backed function mintFractionalFRAX(uint256 collateral_amount, uint256 fxs_amount, uint256 FRAX_out_min) external notMintPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); require(collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "Pool ceiling reached, no more FRAX can be minted with this collateral"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); FraxPoolLibrary.MintFF_Params memory input_params = FraxPoolLibrary.MintFF_Params( fxs_price, getCollateralPrice(), fxs_amount, collateral_amount_d18, global_collateral_ratio ); (uint256 mint_amount, uint256 fxs_needed) = FraxPoolLibrary.calcMintFractionalFRAX(input_params); mint_amount = (mint_amount.mul(uint(1e6).sub(minting_fee))).div(1e6); require(FRAX_out_min <= mint_amount, "Slippage limit reached"); require(fxs_needed <= fxs_amount, "Not enough FXS inputted"); FXS.pool_burn_from(msg.sender, fxs_needed); collateral_token.transferFrom(msg.sender, address(this), collateral_amount); FRAX.pool_mint(msg.sender, mint_amount); } // Redeem collateral. 100% collateral-backed function redeem1t1FRAX(uint256 FRAX_amount, uint256 COLLATERAL_out_min) external notRedeemPaused { require(FRAX.global_collateral_ratio() == COLLATERAL_RATIO_MAX, "Collateral ratio must be == 1"); // Need to adjust for decimals of collateral uint256 FRAX_amount_precision = FRAX_amount.div(10 ** missing_decimals); (uint256 collateral_needed) = FraxPoolLibrary.calcRedeem1t1FRAX( getCollateralPrice(), FRAX_amount_precision ); collateral_needed = (collateral_needed.mul(uint(1e6).sub(redemption_fee))).div(1e6); require(collateral_needed <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_needed, "Slippage limit reached"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); } // Will fail if fully collateralized or algorithmic // Redeem FRAX for collateral and FXS. > 0% and < 100% collateral-backed function redeemFractionalFRAX(uint256 FRAX_amount, uint256 FXS_out_min, uint256 COLLATERAL_out_min) external notRedeemPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); uint256 col_price_usd = getCollateralPrice(); uint256 FRAX_amount_post_fee = (FRAX_amount.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); uint256 fxs_dollar_value_d18 = FRAX_amount_post_fee.sub(FRAX_amount_post_fee.mul(global_collateral_ratio).div(PRICE_PRECISION)); uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price); // Need to adjust for decimals of collateral uint256 FRAX_amount_precision = FRAX_amount_post_fee.div(10 ** missing_decimals); uint256 collateral_dollar_value = FRAX_amount_precision.mul(global_collateral_ratio).div(PRICE_PRECISION); uint256 collateral_amount = collateral_dollar_value.mul(PRICE_PRECISION).div(col_price_usd); require(collateral_amount <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_amount, "Slippage limit reached [collateral]"); require(FXS_out_min <= fxs_amount, "Slippage limit reached [FXS]"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount); redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount); unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); FXS.pool_mint(address(this), fxs_amount); } // Redeem FRAX for FXS. 0% collateral-backed function redeemAlgorithmicFRAX(uint256 FRAX_amount, uint256 FXS_out_min) external notRedeemPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio == 0, "Collateral ratio must be 0"); uint256 fxs_dollar_value_d18 = FRAX_amount; fxs_dollar_value_d18 = (fxs_dollar_value_d18.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); //apply fees uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price); redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount); unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount); lastRedeemed[msg.sender] = block.number; require(FXS_out_min <= fxs_amount, "Slippage limit reached"); // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); FXS.pool_mint(address(this), fxs_amount); } // After a redemption happens, transfer the newly minted FXS and owed collateral from this pool // contract to the user. Redemption is split into two functions to prevent flash loans from being able // to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system. function collectRedemption() external { require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Must wait for redemption_delay blocks before collecting redemption"); bool sendFXS = false; bool sendCollateral = false; uint FXSAmount; uint CollateralAmount; // Use Checks-Effects-Interactions pattern if(redeemFXSBalances[msg.sender] > 0){ FXSAmount = redeemFXSBalances[msg.sender]; redeemFXSBalances[msg.sender] = 0; unclaimedPoolFXS = unclaimedPoolFXS.sub(FXSAmount); sendFXS = true; } if(redeemCollateralBalances[msg.sender] > 0){ CollateralAmount = redeemCollateralBalances[msg.sender]; redeemCollateralBalances[msg.sender] = 0; unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount); sendCollateral = true; } if(sendFXS == true){ FXS.transfer(msg.sender, FXSAmount); } if(sendCollateral == true){ collateral_token.transfer(msg.sender, CollateralAmount); } } // When the protocol is recollateralizing, we need to give a discount of FXS to hit the new CR target // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get FXS for adding collateral // This function simply rewards anyone that sends collateral to a pool with the same amount of FXS + the bonus rate // Anyone can call this function to recollateralize the protocol and take the extra FXS value from the bonus rate as an arb opportunity function recollateralizeFRAX(uint256 collateral_amount, uint256 FXS_out_min) external { require(recollateralizePaused == false, "Recollateralize is paused"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); uint256 fxs_price = FRAX.fxs_price(); uint256 frax_total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); (uint256 collateral_units, uint256 amount_to_recollat) = FraxPoolLibrary.calcRecollateralizeFRAXInner( collateral_amount_d18, getCollateralPrice(), global_collat_value, frax_total_supply, global_collateral_ratio ); uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals); uint256 fxs_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate).sub(recollat_fee)).div(fxs_price); require(FXS_out_min <= fxs_paid_back, "Slippage limit reached"); collateral_token.transferFrom(msg.sender, address(this), collateral_units_precision); FXS.pool_mint(msg.sender, fxs_paid_back); } // Function can be called by an FXS holder to have the protocol buy back FXS with excess collateral value from a desired collateral pool // This can also happen if the collateral ratio > 1 function buyBackFXS(uint256 FXS_amount, uint256 COLLATERAL_out_min) external { require(buyBackPaused == false, "Buyback is paused"); uint256 fxs_price = FRAX.fxs_price(); FraxPoolLibrary.BuybackFXS_Params memory input_params = FraxPoolLibrary.BuybackFXS_Params( availableExcessCollatDV(), fxs_price, getCollateralPrice(), FXS_amount ); (uint256 collateral_equivalent_d18) = (FraxPoolLibrary.calcBuyBackFXS(input_params)).mul(uint(1e6).sub(buyback_fee)).div(1e6); uint256 collateral_precision = collateral_equivalent_d18.div(10 ** missing_decimals); require(COLLATERAL_out_min <= collateral_precision, "Slippage limit reached"); // Give the sender their desired collateral and burn the FXS FXS.pool_burn_from(msg.sender, FXS_amount); collateral_token.transfer(msg.sender, collateral_precision); } /* ========== RESTRICTED FUNCTIONS ========== */ function toggleMinting() external { require(hasRole(MINT_PAUSER, msg.sender)); mintPaused = !mintPaused; } function toggleRedeeming() external { require(hasRole(REDEEM_PAUSER, msg.sender)); redeemPaused = !redeemPaused; } function toggleRecollateralize() external { require(hasRole(RECOLLATERALIZE_PAUSER, msg.sender)); recollateralizePaused = !recollateralizePaused; } function toggleBuyBack() external { require(hasRole(BUYBACK_PAUSER, msg.sender)); buyBackPaused = !buyBackPaused; } function toggleCollateralPrice(uint256 _new_price) external { require(hasRole(COLLATERAL_PRICE_PAUSER, msg.sender)); // If pausing, set paused price; else if unpausing, clear pausedPrice if(collateralPricePaused == false){ pausedPrice = _new_price; } else { pausedPrice = 0; } collateralPricePaused = !collateralPricePaused; } // Combined into one function due to 24KiB contract memory limit function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee) external onlyByOwnerOrGovernance { pool_ceiling = new_ceiling; bonus_rate = new_bonus_rate; redemption_delay = new_redemption_delay; minting_fee = new_mint_fee; redemption_fee = new_redeem_fee; buyback_fee = new_buyback_fee; recollat_fee = new_recollat_fee; } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } /* ========== EVENTS ========== */ } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import '../Uniswap/Interfaces/IUniswapV2Factory.sol'; import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; import '../Math/FixedPoint.sol'; import '../Uniswap/UniswapV2OracleLibrary.sol'; import '../Uniswap/UniswapV2Library.sol'; // Fixed window oracle that recomputes the average price for the entire period once every period // Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period contract UniswapPairOracle { using FixedPoint for *; address owner_address; address timelock_address; uint public PERIOD = 3600; // 1 hour TWAP (time-weighted average price) uint public CONSULT_LENIENCY = 120; // Used for being able to consult past the period end bool public ALLOW_STALE_CONSULTS = false; // If false, consult() will fail if the TWAP is stale IUniswapV2Pair public immutable pair; address public immutable token0; address public immutable token1; uint public price0CumulativeLast; uint public price1CumulativeLast; uint32 public blockTimestampLast; FixedPoint.uq112x112 public price0Average; FixedPoint.uq112x112 public price1Average; modifier onlyByOwnerOrGovernance() { require(msg.sender == owner_address || msg.sender == timelock_address, "You are not an owner or the governance timelock"); _; } constructor(address factory, address tokenA, address tokenB, address _owner_address, address _timelock_address) public { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB)); pair = _pair; token0 = _pair.token0(); token1 = _pair.token1(); price0CumulativeLast = _pair.price0CumulativeLast(); // Fetch the current accumulated price value (1 / 0) price1CumulativeLast = _pair.price1CumulativeLast(); // Fetch the current accumulated price value (0 / 1) uint112 reserve0; uint112 reserve1; (reserve0, reserve1, blockTimestampLast) = _pair.getReserves(); require(reserve0 != 0 && reserve1 != 0, 'UniswapPairOracle: NO_RESERVES'); // Ensure that there's liquidity in the pair owner_address = _owner_address; timelock_address = _timelock_address; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function setTimelock(address _timelock_address) external onlyByOwnerOrGovernance { timelock_address = _timelock_address; } function setPeriod(uint _period) external onlyByOwnerOrGovernance { PERIOD = _period; } function setConsultLeniency(uint _consult_leniency) external onlyByOwnerOrGovernance { CONSULT_LENIENCY = _consult_leniency; } function setAllowStaleConsults(bool _allow_stale_consults) external onlyByOwnerOrGovernance { ALLOW_STALE_CONSULTS = _allow_stale_consults; } // Check if update() can be called instead of wasting gas calling it function canUpdate() public view returns (bool) { uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired return (timeElapsed >= PERIOD); } function update() external { (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired // Ensure that at least one full period has passed since the last update require(timeElapsed >= PERIOD, 'UniswapPairOracle: PERIOD_NOT_ELAPSED'); // Overflow is desired, casting never truncates // Cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)); price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)); price0CumulativeLast = price0Cumulative; price1CumulativeLast = price1Cumulative; blockTimestampLast = blockTimestamp; } // Note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint amountIn) external view returns (uint amountOut) { uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired // Ensure that the price is not stale require((timeElapsed < (PERIOD + CONSULT_LENIENCY)) || ALLOW_STALE_CONSULTS, 'UniswapPairOracle: PRICE_IS_STALE_NEED_TO_CALL_UPDATE'); if (token == token0) { amountOut = price0Average.mul(amountIn).decode144(); } else { require(token == token1, 'UniswapPairOracle: INVALID_TOKEN'); amountOut = price1Average.mul(amountIn).decode144(); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "./AggregatorV3Interface.sol"; contract ChainlinkETHUSDPriceConsumer { AggregatorV3Interface internal priceFeed; constructor() public { priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } function getDecimals() public view returns (uint8) { return priceFeed.decimals(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../Utils/EnumerableSet.sol"; import "../Utils/Address.sol"; import "../Common/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; //bytes32(uint256(0x4B437D01b575618140442A4975db38850e3f8f5f) << 96); /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../Math/SafeMath.sol"; library FraxPoolLibrary { using SafeMath for uint256; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; // ================ Structs ================ // Needed to lower stack size struct MintFF_Params { uint256 fxs_price_usd; uint256 col_price_usd; uint256 fxs_amount; uint256 collateral_amount; uint256 col_ratio; } struct BuybackFXS_Params { uint256 excess_collateral_dollar_value_d18; uint256 fxs_price_usd; uint256 col_price_usd; uint256 FXS_amount; } // ================ Functions ================ function calcMint1t1FRAX(uint256 col_price, uint256 collateral_amount_d18) public pure returns (uint256) { return (collateral_amount_d18.mul(col_price)).div(1e6); } function calcMintAlgorithmicFRAX(uint256 fxs_price_usd, uint256 fxs_amount_d18) public pure returns (uint256) { return fxs_amount_d18.mul(fxs_price_usd).div(1e6); } // Must be internal because of the struct function calcMintFractionalFRAX(MintFF_Params memory params) internal pure returns (uint256, uint256) { // Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error // The contract must check the proper ratio was sent to mint FRAX. We do this by seeing the minimum mintable FRAX based on each amount uint256 fxs_dollar_value_d18; uint256 c_dollar_value_d18; // Scoping for stack concerns { // USD amounts of the collateral and the FXS fxs_dollar_value_d18 = params.fxs_amount.mul(params.fxs_price_usd).div(1e6); c_dollar_value_d18 = params.collateral_amount.mul(params.col_price_usd).div(1e6); } uint calculated_fxs_dollar_value_d18 = (c_dollar_value_d18.mul(1e6).div(params.col_ratio)) .sub(c_dollar_value_d18); uint calculated_fxs_needed = calculated_fxs_dollar_value_d18.mul(1e6).div(params.fxs_price_usd); return ( c_dollar_value_d18.add(calculated_fxs_dollar_value_d18), calculated_fxs_needed ); } function calcRedeem1t1FRAX(uint256 col_price_usd, uint256 FRAX_amount) public pure returns (uint256) { return FRAX_amount.mul(1e6).div(col_price_usd); } // Must be internal because of the struct function calcBuyBackFXS(BuybackFXS_Params memory params) internal pure returns (uint256) { // If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible FXS with the desired collateral require(params.excess_collateral_dollar_value_d18 > 0, "No excess collateral to buy back!"); // Make sure not to take more than is available uint256 fxs_dollar_value_d18 = params.FXS_amount.mul(params.fxs_price_usd).div(1e6); require(fxs_dollar_value_d18 <= params.excess_collateral_dollar_value_d18, "You are trying to buy back more than the excess!"); // Get the equivalent amount of collateral based on the market value of FXS provided uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(1e6).div(params.col_price_usd); //collateral_equivalent_d18 = collateral_equivalent_d18.sub((collateral_equivalent_d18.mul(params.buyback_fee)).div(1e6)); return ( collateral_equivalent_d18 ); } // Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization) function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) { uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6 // Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize return target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow // return(recollateralization_left); } function calcRecollateralizeFRAXInner( uint256 collateral_amount, uint256 col_price, uint256 global_collat_value, uint256 frax_total_supply, uint256 global_collateral_ratio ) public pure returns (uint256, uint256) { uint256 collat_value_attempted = collateral_amount.mul(col_price).div(1e6); uint256 effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6 uint256 recollat_possible = (global_collateral_ratio.mul(frax_total_supply).sub(frax_total_supply.mul(effective_collateral_ratio))).div(1e6); uint256 amount_to_recollat; if(collat_value_attempted <= recollat_possible){ amount_to_recollat = collat_value_attempted; } else { amount_to_recollat = recollat_possible; } return (amount_to_recollat.mul(1e6).div(col_price), amount_to_recollat); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import './Babylonian.sol'; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; uint private constant Q112 = uint(1) << RESOLUTION; uint private constant Q224 = Q112 << RESOLUTION; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // take the reciprocal of a UQ112x112 function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; import '../Math/FixedPoint.sol'; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import './Interfaces/IUniswapV2Pair.sol'; import './Interfaces/IUniswapV2Factory.sol'; import "../Math/SafeMath.sol"; library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // Less efficient than the CREATE2 method below function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = IUniswapV2Factory(factory).getPair(token0, token1); } // calculates the CREATE2 address for a pair without making any external calls function pairForCreate2(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); // this matches the CREATE2 in UniswapV2Factory.createPair } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); }
NOTE: The custodian_address can be set to the governance contract to be used as a mega-voter or sorts. The CRV here can be converted to veCRV and then used to vote
function withdrawCRVRewards() public onlyCustodian { ERC20(crv_address).transfer(custodian_address, ERC20(crv_address).balanceOf(address(this))); }
1,120,164
./full_match/137/0x6ceb95626A59a2F8B1d0B6DB970F4190B89354C7/sources/contracts/oracle/OracleWeightedPoolMiscData.sol
Sets the logarithm of the invariant in `data`, returning the updated value./
function setLogInvariant(bytes32 data, int256 _logInvariant) internal pure returns (bytes32) { return data.insertInt(_logInvariant, _LOG_INVARIANT_OFFSET, 22); }
3,751,472
// contracts/PartyCollection.sol // SPDX-License-Identifier: MIT // Written by white8785 @ twitter // October 2021 pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /** * @dev Contract that creates fungible, and non-fungible tokens to * the Ethereum blockchain. * * By default, the owner will be the one that deploys the contract. This * can be changed by with {trasnferOwnership}. * */ /// @title Project Pool Party Collection /// @custom:security-contact [email protected] contract Dynamic1155 is ERC1155, Ownable, Pausable, ERC1155Burnable { // tokenId -> URI mapping(uint256 => string) private _uris; // tokenId -> max_supply mapping(uint256 => uint256) public tokenMaxSupply; // tokenId -> total_supply mapping(uint256 => uint256) public tokenSupply; // URI for all assets created under this collection string private _contractURI = "ContractURI not configured. Execute {setContractURI}"; // Define if sale is active bool public saleIsActive = true; // Max amount of tokens per mint uint256 public MAX_PURCHASE = 50; // Duplicated events is how optional params work in Solidity. <facepalm> event BatchBurnLoggingEvent( address account, uint256[] ids, uint256[] amounts ); event ContractLoggingEvent(string log); event ContractLoggingEvent( address account, uint256 id, uint256 amount, string data ); event ContractURILoggingEvent(string log); event ContractURILoggingEvent(string log, string data); event MaxSupplyLoggingEvent(uint256 id, uint256 maxSupply); event MintLoggingEvent( address account, uint256 id, uint256 amount, string data ); event MintLoggingEvent( address account, uint256[] ids, uint256[] amounts, string data ); event TokenURILoggingEvent(string log, uint256 newURI, string data); constructor() ERC1155("") { tokenMaxSupply[1] = 333; // RSVPs tokenMaxSupply[2] = 333; // mint(msg.sender, 1, 333, ""); _uris[0] = "Invalid token"; _uris[1] = "TokenURI not configured. See {setTokenURI}."; } /// Owner Functions /// /** * @dev Updates the contractURI */ function setContractURI(string memory _newcontractURI) external onlyOwner whenNotPaused { _contractURI = _newcontractURI; emit ContractURILoggingEvent("ContractURI set.", _newcontractURI); } /** * @dev Updates the tokenURI for a given tokenId */ function setTokenUri(uint256 tokenId, string memory _uri) external onlyOwner whenNotPaused { _uris[tokenId] = _uri; emit TokenURILoggingEvent("TokenURI set.", tokenId, _uri); } /** * @dev Pauses all contract operations */ function pause() external onlyOwner { _pause(); emit ContractLoggingEvent("Contract is paused."); } /** * @dev Unpauses all contract operations */ function unpause() external onlyOwner { emit ContractLoggingEvent("Contract is unpaused."); } /* * Pause sale if active, make active if paused */ function setSaleState(bool newState) public onlyOwner whenNotPaused { saleIsActive = newState; } /** * @dev Sets the tokenId's max supply value. */ function setTokenMaxSupply(uint256 id, uint256 maxSupply) external onlyOwner whenNotPaused { tokenMaxSupply[id] = maxSupply; emit ContractLoggingEvent("Token max supply set."); emit MaxSupplyLoggingEvent(id, maxSupply); } /// Primary Operations /// /** * @dev Returns the contractURI. * * NOTE: Required by OpenSea */ function contractURI() public view returns (string memory) { return _contractURI; } /** * @dev Returns the tokenURI. * * NOTE: Required by OpenSea */ function uri(uint256 tokenId) public view override returns (string memory) { return (_uris[tokenId]); } /** * @dev Creates any amount of tokens for a single tokenId to * a single owner as long as the total amount of tokens requested * does not exceed the max supply of tokens. * * @param account Intended token owner's wallet address * @param id ID of token to be minted * @param amount Number of tokens to mint * @param data Data to include in token * */ function mint( address account, uint256 id, uint256 amount, string memory data ) public onlyOwner whenNotPaused { require(saleIsActive, "Minting is closed"); emit ContractLoggingEvent("Minting started."); emit MintLoggingEvent(account, id, amount, data); // Fail if token's max supply will be exceeded uint256 _requestedtokenSupply = tokenSupply[id] + amount; require( _requestedtokenSupply <= tokenMaxSupply[id], "Requested token amount exceeds token supply" ); // Validate the world is sane and update assert(_requestedtokenSupply >= tokenSupply[id]); tokenSupply[id] = _requestedtokenSupply; // Complete transaction _mint(account, id, amount, abi.encode(data)); // Flex on the haters emit ContractLoggingEvent("Minting successful."); } /** * @dev Creates any amount of tokens for multiple tokenIds to a * single owner as long as the requested amount of tokens * doesn't exceed the max supply of said token. * * @param account Intended token owner's wallet address * @param ids List of IDs of tokens to be minted * @param amounts List of amounts of tokens to mint * @param data Data to include in token * * NOTE: The 'ids' & 'amounts' lists should match in length. * */ function mintBatch( address account, uint256[] memory ids, uint256[] memory amounts, string memory data ) public onlyOwner whenNotPaused { require(saleIsActive, "Minting is closed."); emit ContractLoggingEvent("Batch Minting started."); emit MintLoggingEvent(account, ids, amounts, data); /** * For the number of items in the array starting from zero, * increment by one, until equal to the total number of items, * and ensure tokenSupplies are not exceeded. */ for (uint256 index = 0; index < ids.length; index++) { uint256 _requestedTokenId = ids[index]; uint256 _requestedtokenSupply = tokenSupply[_requestedTokenId] + amounts[index]; // Do not exceed max token count require( _requestedtokenSupply <= tokenMaxSupply[_requestedTokenId], string( abi.encodePacked( "Requested tokenId: ", Strings.toString(_requestedTokenId), " amount: ", Strings.toString(amounts[index]), " exceeds token supply: ", Strings.toString(tokenMaxSupply[_requestedTokenId]) ) ) ); // update supply data tokenSupply[_requestedTokenId] += amounts[index]; } // Party Time! _mintBatch(account, ids, amounts, abi.encode(data)); // flex on everyone emit ContractLoggingEvent("Batch Minting successful."); } /** * @dev Burns any amount of tokens for a single tokenId to * a single owner as long as the total amount of tokens requested * to be burned does not exceed yield a negative value. * * @param account Intended token owner's wallet address * @param id ID of token to be burned * @param amount Number of tokens to burn * */ function burn( address account, uint256 id, uint256 amount ) public override onlyOwner whenNotPaused { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); emit ContractLoggingEvent("Burning started."); uint256 _requestedTokenId = id; uint256 _tokenSupply = tokenSupply[_requestedTokenId]; // If negative, this triggers a revert uint256 _adjustedSupply = _tokenSupply - amount; // Validate the world is sane and update assert(_adjustedSupply >= _tokenSupply); // Set new tokenSupply value tokenSupply[_requestedTokenId] = _adjustedSupply; _burn(account, id, amount); // Yell it from the rooftop emit ContractLoggingEvent("Burning successful."); } /** * @dev Burns any amount of tokens for multiple tokenIds for a * single owner as long as the requested amount of tokens * to burn of said token yields a negative value, and the caller * is the owner or approved. * * @param account Intended token owner's wallet address * @param ids List of IDs of tokens to be burned * @param amounts List of amounts of tokens to burned * * NOTE: The 'ids' & 'amounts' lists should match in length. * */ function burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) public override onlyOwner whenNotPaused { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); emit ContractLoggingEvent("Burning started."); /** * For the number of items in the array starting from zero, * increment by one, until equal to the total number of items, * and ensure tokenSupplies are not exceeded. */ for (uint256 index = 0; index < ids.length; index++) { require(ids[index] != 0, "Burning zero tokens is not possible."); uint256 _requestedTokenId = ids[index]; uint256 _tokenSupply = tokenSupply[_requestedTokenId]; // If negative, this uint256 triggers a revert uint256 _requestedtokenSupply = _tokenSupply - amounts[index]; require( _requestedtokenSupply < _tokenSupply, "The new supply count is not less than original, what did you do?" ); // update supply data tokenSupply[_requestedTokenId] = _requestedtokenSupply; } _burnBatch(account, ids, amounts); emit BatchBurnLoggingEvent(account, ids, amounts); emit ContractLoggingEvent("Batch burn complete."); } }
Unpauses all contract operations/
function unpause() external onlyOwner { emit ContractLoggingEvent("Contract is unpaused."); }
14,050,664
./full_match/1/0x8b9e20D9970Af54fbaFe64049174e24d6DE0C412/sources/contracts/v2/strategies/DsrBaseStrategy.sol
The latest checkpoint of each asset balance this strategy holds, and the current debt. This will be used to report equity performance: `sum(asset value in STABLE) - debt` The conversion of each asset price into the stable token (eg DAI) will be done off-chain The asset value may be stale at any point in time, depending on the strategy. It may optionally implement `checkpointAssetBalances()` in order to update those balances./
) { assetBalances = new AssetBalance[](1); function latestAssetBalances() public override(AbstractStrategy, ITempleBaseStrategy) view returns ( AssetBalance[] memory assetBalances assetBalances[0] = AssetBalance({ asset: address(daiToken), balance: latestDsrBalance() }); }
9,812,701
./full_match/1/0x1c1024Cf1D08428eB45f4904211799fF1609E27a/sources/zombronies.sol
get base URI for NFT metadata/
function _baseURI() internal view virtual override returns (string memory) { return baseURI; }
16,548,494
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. * @author WyndBlast Team Developer */ contract WBMultiSigWallet { event WalletAdded( uint indexed walletIndex, address walletContract, string name, string symbol ); event WalletUpdated( uint indexed walletIndex, address walletContract, string name, string symbol ); event Deposit( address sender, uint indexed amount, uint indexed balance ); event SubmitTransaction( address owner, uint indexed walletIndex, uint indexed txIndex, address to, uint value, bytes data ); event ConfirmTransaction( address owner, uint indexed walletIndex, uint indexed txIndex ); event RevokeConfirmation( address owner, uint indexed walletIndex, uint indexed txIndex ); event ExecuteTransaction( address indexed owner, uint indexed walletIndex, uint indexed txIndex ); event DailyLimitChange(uint indexed walletIndex, uint indexed dailyLimit); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); address[] public owners; address private deployer; mapping(address => bool) public isOwner; uint public numConfirmationsRequired; uint constant public MAX_OWNER_COUNT = 50; struct Transaction { address to; uint value; bytes data; bool executed; uint numConfirmations; } mapping(uint => mapping(uint => mapping(address => bool))) public isConfirmed; mapping(uint => Transaction[]) public transactions; struct Wallet { address contractAddress; string name; string symbol; uint256 dailyLimit; uint256 lastDay; uint256 spentToday; } Wallet[] public wallets; modifier validAddress(address _address) { require(_address != address(0), "Address is nulled"); _; } modifier validRequirement(uint ownerCount, uint _required) { require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0, "Invalid requirement"); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner], "Owner exists"); _; } modifier ownerExists(address owner) { require(isOwner[owner], "Owner is not exists"); _; } modifier onlyDeployer() { require(deployer == msg.sender, "Caller is not the deployer"); _; } modifier isDeployer(address owner) { require(owner != deployer, "Can't remove deployer"); _; } modifier onlyOwner() { require(isOwner[msg.sender] || deployer == msg.sender, "Unauthorized caller"); _; } modifier txExists(uint _walletIndex, uint _txIndex) { require(_txIndex < transactions[_walletIndex].length, "Transaction does not exist"); _; } modifier notExecuted(uint _walletIndex, uint _txIndex) { require(!transactions[_walletIndex][_txIndex].executed, "Transaction already executed"); _; } modifier notConfirmed(uint _walletIndex, uint _txIndex) { require(!isConfirmed[_walletIndex][_txIndex][msg.sender], "Transaction already confirmed"); _; } /** * @notice Default number of required confirmation is 1. * Default daily limit is 1000000000000000000 wei */ constructor() { _transferOwnership(msg.sender); address owner = msg.sender; isOwner[owner] = true; owners.push(owner); numConfirmationsRequired = 1; /// set default avax wallet addWallet(address(this), "Avax C-Chain", "AVAX", 1000); } /** * @dev Internal check to make sure that amount is under limit * @return boolean */ function _isUnderLimit(uint walletIndex, uint amount) internal returns (bool) { Wallet storage wallet = wallets[walletIndex]; if (block.timestamp > wallet.lastDay + 24 hours) { wallet.lastDay = block.timestamp; wallet.spentToday = 0; } if (wallet.spentToday + amount > wallet.dailyLimit || wallet.spentToday + amount < wallet.spentToday) { return false; } return true; } /** * @notice Receive deposit of token */ receive() external payable { emit Deposit(msg.sender, msg.value, address(this).balance); } /** * -------------------------------------------------------------------------------------- * -------------------------------- OWNER FUNCTIONS ------------------------------------- * -------------------------------------------------------------------------------------- */ /** * @notice Execute transaction, payout to recipient address * @param walletIndex Wallet index * @param _to Recipient wallet address * @param _value Amount of token in wei * @param _data Some data that converted in to hex format */ function submitTransaction( uint walletIndex, address _to, uint _value, bytes memory _data ) public onlyOwner { uint txIndex = transactions[walletIndex].length; transactions[walletIndex].push( Transaction({ to: _to, value: _value, data: _data, executed: false, numConfirmations: 0 }) ); emit SubmitTransaction(msg.sender, walletIndex, txIndex, _to, _value, _data); } /** * @notice Confirm transaction or approve transaction by sender * @param _walletIndex Wallet index * @param _txIndex Transaction index */ function confirmTransaction(uint _walletIndex, uint _txIndex) public onlyOwner txExists(_walletIndex, _txIndex) notExecuted(_walletIndex, _txIndex) notConfirmed(_walletIndex, _txIndex) { Transaction storage transaction = transactions[_walletIndex][_txIndex]; transaction.numConfirmations += 1; isConfirmed[_walletIndex][_txIndex][msg.sender] = true; emit ConfirmTransaction(msg.sender, _walletIndex, _txIndex); } /** * @notice Execute transaction, payout to recipient address * @param _walletIndex Wallet index * @param _txIndex Transaction index */ function executeTransaction(uint _walletIndex, uint _txIndex) public onlyOwner txExists(_walletIndex, _txIndex) notExecuted(_walletIndex, _txIndex) { Wallet storage wallet = wallets[_walletIndex]; Transaction storage transaction = transactions[_walletIndex][_txIndex]; require(transaction.numConfirmations >= numConfirmationsRequired, "Cannot execute transaction"); require(_isUnderLimit(_walletIndex, transaction.value), "Maximum daily limit"); transaction.executed = true; wallet.spentToday += transaction.value; bool paymenStatus = false; if (_walletIndex == 0) { (bool success, ) = transaction.to.call{value: transaction.value}( transaction.data ); paymenStatus = success; } else { (bool success) = IERC20(wallet.contractAddress).transfer(transaction.to, transaction.value); paymenStatus = success; } if (!paymenStatus) { transaction.executed = false; wallet.spentToday -= transaction.value; } require(paymenStatus, "Failed or insufficent funds"); emit ExecuteTransaction(msg.sender, _walletIndex, _txIndex); } /** * @notice Revoke confirmed transaction * @param _walletIndex Wallet index * @param _txIndex Transaction index */ function revokeConfirmation(uint _walletIndex, uint _txIndex) public onlyOwner txExists(_walletIndex, _txIndex) notExecuted(_walletIndex, _txIndex) { Transaction storage transaction = transactions[_walletIndex][_txIndex]; require(isConfirmed[_walletIndex][_txIndex][msg.sender], "Transaction not confirmed"); transaction.numConfirmations -= 1; isConfirmed[_walletIndex][_txIndex][msg.sender] = false; emit RevokeConfirmation(msg.sender, _walletIndex, _txIndex); } /** * -------------------------------------------------------------------------------------- * -------------------------------- PUBLIC FUNCTIONS ------------------------------------ * -------------------------------------------------------------------------------------- */ /** * @notice Get owner addresses */ function getOwners() public view returns (address[] memory) { return owners; } /** * @notice Get wallet address */ function getWallets() public view returns (Wallet[] memory) { return wallets; } /** * @notice Get transaction count */ function getTransactionCount(uint _walletIndex) public view returns (uint) { return transactions[_walletIndex].length; } /** * @notice Get transaction details * @param _walletIndex Wallet index * @param _txIndex Transaction index */ function getTransaction(uint _walletIndex, uint _txIndex) public view returns ( address to, uint value, bytes memory data, bool executed, uint numConfirmations ) { Transaction storage transaction = transactions[_walletIndex][_txIndex]; return ( transaction.to, transaction.value, transaction.data, transaction.executed, transaction.numConfirmations ); } /** * @notice Get transactions * @param _walletIndex Wallet index * @return Transaction array */ function getTransactions(uint _walletIndex) public view returns (Transaction[] memory) { return transactions[_walletIndex]; } /** * @notice Get contract balance */ function getBalance(uint _walletIndex) public view returns (uint256) { Wallet storage wallet = wallets[_walletIndex]; if (_walletIndex == 0) { return address(this).balance; } else { return IERC20(wallet.contractAddress).balanceOf(address(this)); } } /** * @notice Get maximum withdraw amount. * @return Maximum amount today */ function calcMaxWithdraw(uint _walletIndex) public view returns (uint) { Wallet storage wallet = wallets[_walletIndex]; if (block.timestamp > wallet.lastDay + 24 hours) { return wallet.dailyLimit; } if (wallet.dailyLimit < wallet.spentToday) { return 0; } return wallet.dailyLimit - wallet.spentToday; } /** * @notice Get current deployer as owner of contract */ function getDeployer() public view returns (address) { return deployer; } /** * -------------------------------------------------------------------------------------- * ------------------------------ DEPLOYER FUNCTIONS ------------------------------------ * -------------------------------------------------------------------------------------- */ /** * @notice Change daily limit * @param _walletIndex Wallet index * @param _dailyLimit Max of amount in wei */ function changeDailyLimit(uint _walletIndex, uint _dailyLimit) public onlyDeployer { Wallet storage wallet = wallets[_walletIndex]; wallet.dailyLimit = _dailyLimit; emit DailyLimitChange(_walletIndex, _dailyLimit); } /** * @notice Add new owner * @param _owner Wallet address */ function addOwner(address _owner) public onlyDeployer ownerDoesNotExist(_owner) validAddress(_owner) validRequirement(owners.length + 1, numConfirmationsRequired) { isOwner[_owner] = true; owners.push(_owner); emit OwnerAddition(_owner); } /** * @notice Remove owner from owners array * @param _owner Owner address */ function removeOwner(address _owner) public onlyDeployer ownerExists(_owner) isDeployer(_owner) { isOwner[_owner] = false; for (uint i = 0; i < owners.length - 1; i++) { if (owners[i] == _owner) { owners[i] = owners[owners.length - 1]; break; } } owners.pop(); if (numConfirmationsRequired > owners.length) { changeRequirement(owners.length); } emit OwnerRemoval(_owner); } /** * @notice Change number of required confirmation * @param _required Number of required confirmation */ function changeRequirement(uint _required) public onlyDeployer validRequirement(owners.length, _required) { numConfirmationsRequired = _required; emit RequirementChange(_required); } /** * @notice Leaves the contract without owner. It will not be possible to call * `onlyDeployer` functions anymore. Can only be called by the current owner. */ function renounceOwnership() public onlyDeployer { _transferOwnership(address(0)); } /** * @notice Transfers ownership of the contract to a new account * @param newOwner New owner address */ function transferOwnership(address newOwner) public onlyDeployer { require(newOwner != address(0), "Invalid new owner"); _transferOwnership(newOwner); } /** * @notice Transfers ownership of the contract to a new account * @param newOwner New owner address */ function _transferOwnership(address newOwner) internal { address oldOwner = deployer; deployer = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @notice Add new wallet * @param _contractAddress Token contract address * @param _name Token name * @param _symbol Token symbol * @param _dailyLimit Daily limit */ function addWallet( address _contractAddress, string memory _name, string memory _symbol, uint256 _dailyLimit ) public onlyDeployer { uint walletIndex = wallets.length; wallets.push(Wallet(_contractAddress, _name, _symbol, _dailyLimit, 0, 0)); emit WalletAdded(walletIndex, _contractAddress, _name, _symbol); } /** * @notice Update wallet * @param _walletIndex Wallet index * @param _contractAddress Token contract address * @param _name Token name * @param _symbol Token symbol * @param _dailyLimit Daily limit */ function updateWallet( uint _walletIndex, address _contractAddress, string memory _name, string memory _symbol, uint256 _dailyLimit ) public onlyDeployer { uint walletIndex = wallets.length; Wallet storage wallet = wallets[_walletIndex]; wallet.contractAddress = _contractAddress; wallet.name = _name; wallet.symbol = _symbol; wallet.dailyLimit = _dailyLimit; emit WalletUpdated(walletIndex, _contractAddress, _name, _symbol); } }
Leaves the contract without owner. It will not be possible to call `onlyDeployer` functions anymore. Can only be called by the current owner./
function renounceOwnership() public onlyDeployer { _transferOwnership(address(0)); }
15,802,430
./full_match/5/0x0e58687f92A3cfcf8F32A88f9ACccf7dD2aD3D94/sources/contracts/Sample_Contract.sol
Function to check the balance of a specific token
function getTokenBalance(address token) external view returns (uint256) { if(token == address(1)){ return address(this).balance; } else{ return balances[token]; } }
11,635,274
pragma solidity 0.4.25; // File: contracts/sogur/interfaces/IModelDataSource.sol /** * @title Model Data Source Interface. */ interface IModelDataSource { /** * @dev Get interval parameters. * @param _rowNum Interval row index. * @param _colNum Interval column index. * @return Interval minimum amount of SGR. * @return Interval maximum amount of SGR. * @return Interval minimum amount of SDR. * @return Interval maximum amount of SDR. * @return Interval alpha value (scaled up). * @return Interval beta value (scaled up). */ function getInterval(uint256 _rowNum, uint256 _colNum) external view returns (uint256, uint256, uint256, uint256, uint256, uint256); /** * @dev Get interval alpha and beta. * @param _rowNum Interval row index. * @param _colNum Interval column index. * @return Interval alpha value (scaled up). * @return Interval beta value (scaled up). */ function getIntervalCoefs(uint256 _rowNum, uint256 _colNum) external view returns (uint256, uint256); /** * @dev Get the amount of SGR required for moving to the next minting-point. * @param _rowNum Interval row index. * @return Required amount of SGR. */ function getRequiredMintAmount(uint256 _rowNum) external view returns (uint256); } // File: contracts/sogur/interfaces/IMintingPointTimersManager.sol /** * @title Minting Point Timers Manager Interface. */ interface IMintingPointTimersManager { /** * @dev Start a given timestamp. * @param _id The ID of the timestamp. * @notice When tested, this timestamp will be either 'running' or 'expired'. */ function start(uint256 _id) external; /** * @dev Reset a given timestamp. * @param _id The ID of the timestamp. * @notice When tested, this timestamp will be neither 'running' nor 'expired'. */ function reset(uint256 _id) external; /** * @dev Get an indication of whether or not a given timestamp is 'running'. * @param _id The ID of the timestamp. * @return An indication of whether or not a given timestamp is 'running'. * @notice Even if this timestamp is not 'running', it is not necessarily 'expired'. */ function running(uint256 _id) external view returns (bool); /** * @dev Get an indication of whether or not a given timestamp is 'expired'. * @param _id The ID of the timestamp. * @return An indication of whether or not a given timestamp is 'expired'. * @notice Even if this timestamp is not 'expired', it is not necessarily 'running'. */ function expired(uint256 _id) external view returns (bool); } // File: contracts/sogur/interfaces/ISGRAuthorizationManager.sol /** * @title SGR Authorization Manager Interface. */ interface ISGRAuthorizationManager { /** * @dev Determine whether or not a user is authorized to buy SGR. * @param _sender The address of the user. * @return Authorization status. */ function isAuthorizedToBuy(address _sender) external view returns (bool); /** * @dev Determine whether or not a user is authorized to sell SGR. * @param _sender The address of the user. * @return Authorization status. */ function isAuthorizedToSell(address _sender) external view returns (bool); /** * @dev Determine whether or not a user is authorized to transfer SGR to another user. * @param _sender The address of the source user. * @param _target The address of the target user. * @return Authorization status. */ function isAuthorizedToTransfer(address _sender, address _target) external view returns (bool); /** * @dev Determine whether or not a user is authorized to transfer SGR from one user to another user. * @param _sender The address of the custodian user. * @param _source The address of the source user. * @param _target The address of the target user. * @return Authorization status. */ function isAuthorizedToTransferFrom(address _sender, address _source, address _target) external view returns (bool); /** * @dev Determine whether or not a user is authorized for public operation. * @param _sender The address of the user. * @return Authorization status. */ function isAuthorizedForPublicOperation(address _sender) external view returns (bool); } // File: contracts/sogur/interfaces/IMintListener.sol /** * @title Mint Listener Interface. */ interface IMintListener { /** * @dev Mint SGR for SGN holders. * @param _value The amount of SGR to mint. */ function mintSgrForSgnHolders(uint256 _value) external; } // File: contracts/saga-genesis/interfaces/IMintHandler.sol /** * @title Mint Handler Interface. */ interface IMintHandler { /** * @dev Upon minting of SGN vested in delay. * @param _index The minting-point index. */ function mintSgnVestedInDelay(uint256 _index) external; } // File: contracts/saga-genesis/interfaces/IMintManager.sol /** * @title Mint Manager Interface. */ interface IMintManager { /** * @dev Return the current minting-point index. */ function getIndex() external view returns (uint256); } // File: contracts/contract_address_locator/interfaces/IContractAddressLocator.sol /** * @title Contract Address Locator Interface. */ interface IContractAddressLocator { /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) external view returns (address); /** * @dev Determine whether or not a contract address relates to one of the identifiers. * @param _contractAddress The contract address to look for. * @param _identifiers The identifiers. * @return A boolean indicating if the contract address relates to one of the identifiers. */ function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool); } // File: contracts/contract_address_locator/ContractAddressLocatorHolder.sol /** * @title Contract Address Locator Holder. * @dev Hold a contract address locator, which maps a unique identifier to every contract address in the system. * @dev Any contract which inherits from this contract can retrieve the address of any contract in the system. * @dev Thus, any contract can remain "oblivious" to the replacement of any other contract in the system. * @dev In addition to that, any function in any contract can be restricted to a specific caller. */ contract ContractAddressLocatorHolder { bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource"; bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ; bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ; bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ; bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ; bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ; bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ; bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ; bytes32 internal constant _IMintHandler_ = "IMintHandler" ; bytes32 internal constant _IMintListener_ = "IMintListener" ; bytes32 internal constant _IMintManager_ = "IMintManager" ; bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ; bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ; bytes32 internal constant _IRedButton_ = "IRedButton" ; bytes32 internal constant _IReserveManager_ = "IReserveManager" ; bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ; bytes32 internal constant _ISogurExchanger_ = "ISogurExchanger" ; bytes32 internal constant _SgnToSgrExchangeInitiator_ = "SgnToSgrExchangeInitiator" ; bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ; bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ; bytes32 internal constant _ISGRAuthorizationManager_ = "ISGRAuthorizationManager"; bytes32 internal constant _ISGRToken_ = "ISGRToken" ; bytes32 internal constant _ISGRTokenManager_ = "ISGRTokenManager" ; bytes32 internal constant _ISGRTokenInfo_ = "ISGRTokenInfo" ; bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager"; bytes32 internal constant _ISGNToken_ = "ISGNToken" ; bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ; bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ; bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ; bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ; bytes32 internal constant _BuyWalletsTradingDataSource_ = "BuyWalletsTradingDataSource" ; bytes32 internal constant _SellWalletsTradingDataSource_ = "SellWalletsTradingDataSource" ; bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ; bytes32 internal constant _BuyWalletsTradingLimiter_SGRTokenManager_ = "BuyWalletsTLSGRTokenManager" ; bytes32 internal constant _SellWalletsTradingLimiter_SGRTokenManager_ = "SellWalletsTLSGRTokenManager" ; bytes32 internal constant _IETHConverter_ = "IETHConverter" ; bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ; bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ; bytes32 internal constant _IRateApprover_ = "IRateApprover" ; bytes32 internal constant _SGAToSGRInitializer_ = "SGAToSGRInitializer" ; IContractAddressLocator private contractAddressLocator; /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) internal { require(_contractAddressLocator != address(0), "locator is illegal"); contractAddressLocator = _contractAddressLocator; } /** * @dev Get the contract address locator. * @return The contract address locator. */ function getContractAddressLocator() external view returns (IContractAddressLocator) { return contractAddressLocator; } /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) internal view returns (address) { return contractAddressLocator.getContractAddress(_identifier); } /** * @dev Determine whether or not the sender relates to one of the identifiers. * @param _identifiers The identifiers. * @return A boolean indicating if the sender relates to one of the identifiers. */ function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) { return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers); } /** * @dev Verify that the caller is mapped to a given identifier. * @param _identifier The identifier. */ modifier only(bytes32 _identifier) { require(msg.sender == getContractAddress(_identifier), "caller is illegal"); _; } } // File: contracts/sogur/MintManager.sol /** * Details of usage of licenced software see here: https://www.sogur.com/software/readme_v1 */ /** * @title Mint Manager. */ contract MintManager is IMintManager, ContractAddressLocatorHolder { string public constant VERSION = "2.0.0"; uint256 public index; /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {} /** * @dev Return the contract which implements the IModelDataSource interface. */ function getModelDataSource() public view returns (IModelDataSource) { return IModelDataSource(getContractAddress(_IModelDataSource_)); } /** * @dev Return the contract which implements the IMintingPointTimersManager interface. */ function getMintingPointTimersManager() public view returns (IMintingPointTimersManager) { return IMintingPointTimersManager(getContractAddress(_IMintingPointTimersManager_)); } /** * @dev Return the contract which implements the ISGRAuthorizationManager interface. */ function getSGRAuthorizationManager() public view returns (ISGRAuthorizationManager) { return ISGRAuthorizationManager(getContractAddress(_ISGRAuthorizationManager_)); } /** * @dev Return the contract which implements the IMintHandler interface. */ function getMintHandler() public view returns (IMintHandler) { return IMintHandler(getContractAddress(_IMintHandler_)); } /** * @dev Return the contract which implements the IMintListener interface. */ function getMintListener() public view returns (IMintListener) { return IMintListener(getContractAddress(_IMintListener_)); } /** * @dev Return whether or not the minting-state should be updated. */ function isMintingStateOutdated() public view returns (bool) { return getMintingPointTimersManager().expired(index + 1); } /** * @dev Update the minting-state if it is outdated. */ function updateMintingState() external { require(getSGRAuthorizationManager().isAuthorizedForPublicOperation(msg.sender), "update minting state is not authorized"); if (isMintingStateOutdated()) { uint256 amount = getModelDataSource().getRequiredMintAmount(index); getMintListener().mintSgrForSgnHolders(amount); getMintHandler().mintSgnVestedInDelay(index + 1); index += 1; } } /** * @dev Return the current minting-point index. */ function getIndex() external view returns (uint256) { return index; } }
Return the current minting-point index./
function getIndex() external view returns (uint256) { return index; }
10,323,270
pragma solidity 0.4.23; /* *DivvyUp for Goo * * ====================================================================* *'||''|. || '||' '|' * || || ... .... ... .... ... .... ... , || | ... ... * || || || '|. | '|. | '|. | <> / || | ||' || * || || || '|.| '|.| '|.| / || | || | *.||...|' .||. '| '| '| / '|..' ||...' * .. | / || * '' / <> '''' * =====================================================================* * * A wealth redistribution smart contract cleverly disguised as a ERC20 token. * Complete with a factory for making new verticals, and a fair launch contract * to ensure a fair launch. * */ // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint256); function balanceOf(address tokenOwner) public constant returns (uint256 balance); function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining); function transfer(address to, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom(address from, address to, uint256 tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public ownerCandidate; function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function changeOwner(address _newOwner) public onlyOwner { ownerCandidate = _newOwner; } function acceptOwnership() public { require(msg.sender == ownerCandidate); owner = ownerCandidate; } } /** * @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; } } contract DivvyUpFactoryInterface { function create( bytes32 name, // Name of the DivvyUp bytes32 symbol, // ERC20 Symbol fo the DivvyUp uint8 dividendDivisor, // Amount to divide incoming counter by as fees for dividens. Example: 3 for 33%, 10 for 10%, 100 for 1% uint8 decimals, // Number of decimals the token has. Example: 18 uint256 initialPrice, // Starting price per token. Example: 0.0000001 ether uint256 incrementPrice, // How much to increment the price by. Example: 0.00000001 ether uint256 magnitude, //magnitude to multiply the fees by before distribution. Example: 2**64 address counter // The counter currency to accept. Example: 0x0 for ETH, otherwise the ERC20 token address. ) public returns(address); } contract DivvyUpFactory is Owned { event Create( bytes32 name, bytes32 symbol, uint8 dividendDivisor, uint8 decimals, uint256 initialPrice, uint256 incrementPrice, uint256 magnitude, address creator ); DivvyUp[] public registry; function create( bytes32 name, // Name of the DivvyUp bytes32 symbol, // ERC20 Symbol fo the DivvyUp uint8 dividendDivisor, // Amount to divide incoming counter by as fees for dividens. Example: 3 for 33%, 10 for 10%, 100 for 1% uint8 decimals, // Number of decimals the token has. Example: 18 uint256 initialPrice, // Starting price per token. Example: 0.0000001 ether uint256 incrementPrice, // How much to increment the price by. Example: 0.00000001 ether uint256 magnitude, //magnitude to multiply the fees by before distribution. Example: 2**64 address counter // The counter currency to accept. Example: 0x0 for ETH, otherwise the ERC20 token address. ) public returns(address) { DivvyUp divvyUp = new DivvyUp(name, symbol, dividendDivisor, decimals, initialPrice, incrementPrice, magnitude, counter); divvyUp.changeOwner(msg.sender); registry.push(divvyUp); emit Create(name, symbol, dividendDivisor, decimals, initialPrice, incrementPrice, magnitude, msg.sender); return divvyUp; } function die() onlyOwner public { selfdestruct(msg.sender); } /** * Owner can transfer out any accidentally sent ERC20 tokens * * Implementation taken from ERC20 reference * */ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } } contract DivvyUpInterface{ function purchaseTokens() public payable returns(uint256); function purchaseTokensERC20(uint256 amount) public returns(uint256); } contract DivvyUp is ERC20Interface, Owned, DivvyUpInterface { using SafeMath for uint256; /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyTokenHolders() { require(myTokens() > 0); _; } // only people with profits modifier onlyDividendHolders() { require(dividendDivisor > 0 && myDividends() > 0); _; } modifier erc20Destination(){ require(counter != 0x0); _; } /*============================== = EVENTS = ==============================*/ event Purchase( address indexed customerAddress, uint256 incomingCounter, uint256 tokensMinted ); event Sell( address indexed customerAddress, uint256 tokensBurned, uint256 counterEarned ); event Reinvestment( address indexed customerAddress, uint256 counterReinvested, uint256 tokensMinted ); event Withdraw( address indexed customerAddress, uint256 counterWithdrawn ); /*===================================== = CONFIGURABLES = =====================================*/ bytes32 public name; bytes32 public symbol; uint8 public dividendDivisor; uint8 public decimals;// = 18; uint256 public tokenPriceInitial;// = 0.0000001 ether; uint256 public tokenPriceIncremental;// = 0.00000001 ether; uint256 public magnitude;// = 2**64; address counter; /*================================ = DATASETS = ================================*/ // amount of tokens for each address mapping(address => uint256) internal tokenBalanceLedger; // amount of eth withdrawn mapping(address => int256) internal payoutsTo; // amount of tokens allowed to someone else mapping(address => mapping(address => uint)) allowed; // the actual amount of tokens uint256 internal tokenSupply = 0; // the amount of dividends per token uint256 internal profitPerShare; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /** * -- APPLICATION ENTRY POINTS -- */ function DivvyUp(bytes32 aName, bytes32 aSymbol, uint8 aDividendDivisor, uint8 aDecimals, uint256 aTokenPriceInitial, uint256 aTokenPriceIncremental, uint256 aMagnitude, address aCounter) public { require(aDividendDivisor < 100); name = aName; symbol = aSymbol; dividendDivisor = aDividendDivisor; decimals = aDecimals; tokenPriceInitial = aTokenPriceInitial; tokenPriceIncremental = aTokenPriceIncremental; magnitude = aMagnitude; counter = aCounter; } /** * Allows the owner to change the name of the contract */ function changeName(bytes32 newName) onlyOwner() public { name = newName; } /** * Allows the owner to change the symbol of the contract */ function changeSymbol(bytes32 newSymbol) onlyOwner() public { symbol = newSymbol; } /** * Converts all incoming counter to tokens for the caller */ function purchaseTokens() public payable returns(uint256) { if(msg.value > 0){ require(counter == 0x0); } return purchaseTokens(msg.value); } /** * Converts all incoming counter to tokens for the caller */ function purchaseTokensERC20(uint256 amount) public erc20Destination returns(uint256) { require(ERC20Interface(counter).transferFrom(msg.sender, this, amount)); return purchaseTokens(amount); } /** * Fallback function to handle counter that was send straight to the contract. * Causes tokens to be purchased. */ function() payable public { if(msg.value > 0){ require(counter == 0x0); } purchaseTokens(msg.value); } /** * Converts all of caller's dividends to tokens. */ function reinvestDividends() onlyDividendHolders() public returns (uint256) { // fetch dividends uint256 dividends = myDividends(); // pay out the dividends virtually address customerAddress = msg.sender; payoutsTo[customerAddress] += (int256) (dividends * magnitude); // dispatch a buy order with the virtualized "withdrawn dividends" if we have dividends uint256 tokens = purchaseTokens(dividends); // fire event emit Reinvestment(customerAddress, dividends, tokens); return 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); } // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyDividendHolders() public { // setup data address customerAddress = msg.sender; uint256 dividends = myDividends(); // update dividend tracker payoutsTo[customerAddress] += (int256) (dividends * magnitude); // fire event emit Withdraw(customerAddress, dividends); } /** * Liquifies tokens to counter. */ function sell(uint256 amountOfTokens) onlyTokenHolders() public { require(amountOfTokens > 0); // setup data address customerAddress = msg.sender; // russian hackers BTFO require(amountOfTokens <= tokenBalanceLedger[customerAddress]); uint256 tokens = amountOfTokens; uint256 counterAmount = tokensToCounter(tokens); uint256 dividends = dividendDivisor > 0 ? SafeMath.div(counterAmount, dividendDivisor) : 0; uint256 taxedCounter = SafeMath.sub(counterAmount, dividends); // burn the sold tokens tokenSupply = SafeMath.sub(tokenSupply, tokens); tokenBalanceLedger[customerAddress] = SafeMath.sub(tokenBalanceLedger[customerAddress], tokens); // update dividends tracker int256 updatedPayouts = (int256) (profitPerShare * tokens + (taxedCounter * magnitude)); payoutsTo[customerAddress] -= updatedPayouts; // dividing by zero is a bad idea if (tokenSupply > 0 && dividendDivisor > 0) { // update the amount of dividends per token profitPerShare = SafeMath.add(profitPerShare, (dividends * magnitude) / tokenSupply); } // fire event emit Sell(customerAddress, tokens, taxedCounter); } /** * Transfer tokens from the caller to a new holder. * Transfering ownership of tokens requires settling outstanding dividends * and transfering them back. You can therefore send 0 tokens to this contract to * trigger your withdraw. */ function transfer(address toAddress, uint256 amountOfTokens) onlyTokenHolders public returns(bool) { // Sell on transfer in instad of transfering to if(toAddress == address(this)){ // If we sent in tokens, destroy them and credit their account with ETH if(amountOfTokens > 0){ sell(amountOfTokens); } // Send them their ETH withdraw(); // fire event emit Transfer(0x0, msg.sender, amountOfTokens); return true; } // Deal with outstanding dividends first if(myDividends() > 0) { withdraw(); } return _transfer(toAddress, amountOfTokens); } function transferWithDividends(address toAddress, uint256 amountOfTokens) public onlyTokenHolders returns (bool) { return _transfer(toAddress, amountOfTokens); } function _transfer(address toAddress, uint256 amountOfTokens) internal onlyTokenHolders returns(bool) { // setup address customerAddress = msg.sender; // make sure we have the requested tokens require(amountOfTokens <= tokenBalanceLedger[customerAddress]); // exchange tokens tokenBalanceLedger[customerAddress] = SafeMath.sub(tokenBalanceLedger[customerAddress], amountOfTokens); tokenBalanceLedger[toAddress] = SafeMath.add(tokenBalanceLedger[toAddress], amountOfTokens); // fire event emit Transfer(customerAddress, toAddress, amountOfTokens); return true; } // ERC20 function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } /** * Transfer `tokens` from the `from` account to the `to` account * * The calling account must already have sufficient tokens approve(...)-d * for spending from the `from` account and * - From account must have sufficient balance to transfer * - Spender must have sufficient allowance to transfer * - 0 value transfers are allowed * * Implementation taken from ERC20 reference * */ function transferFrom(address from, address to, uint tokens) public returns (bool success) { tokenBalanceLedger[from] = tokenBalanceLedger[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); tokenBalanceLedger[to] = tokenBalanceLedger[to].add(tokens); emit Transfer(from, to, tokens); return true; } /** * Returns the amount of tokens approved by the owner that can be * transferred to the spender's account * * Implementation taken from ERC20 reference * */ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } /** * Token owner can approve for `spender` to transferFrom(...) `tokens` * from the token owner's account. The `spender` contract function * `receiveApproval(...)` is then executed * */ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Counter stored in the contract * Example: totalDestinationBalance() */ function totalDestinationBalance() public view returns(uint256) { if(counter == 0x0){ return address(this).balance; } else { return ERC20Interface(counter).balanceOf(this); } } /** * Retrieve the name of the token. */ function name() public view returns(bytes32) { return name; } /** * Retrieve the symbol of the token. */ function symbol() public view returns(bytes32) { return symbol; } /** * 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 dividends owned by the caller. */ function myDividends() public view returns(uint256) { address customerAddress = msg.sender; return (uint256) ((int256)(profitPerShare * tokenBalanceLedger[customerAddress]) - payoutsTo[customerAddress]) / magnitude; } /** * Retrieve the token balance of any single address. */ function balanceOf(address customerAddress) view public returns(uint256) { return tokenBalanceLedger[customerAddress]; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply == 0){ return tokenPriceInitial - tokenPriceIncremental; } else { uint256 counterAmount = tokensToCounter(1e18); uint256 dividends = SafeMath.div(counterAmount, dividendDivisor); uint256 taxedCounter = SafeMath.sub(counterAmount, dividends); return taxedCounter; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply == 0){ return tokenPriceInitial + tokenPriceIncremental; } else { uint256 counterAmount = tokensToCounter(1e18); uint256 dividends = SafeMath.div(counterAmount, dividendDivisor); uint256 taxedCounter = SafeMath.add(counterAmount, dividends); return taxedCounter; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 counterToSpend) public view returns(uint256) { uint256 dividends = SafeMath.div(counterToSpend, dividendDivisor); uint256 taxedCounter = SafeMath.sub(counterToSpend, dividends); uint256 amountOfTokens = counterToTokens(taxedCounter); return amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateCounterReceived(uint256 tokensToSell) public view returns(uint256) { require(tokensToSell <= tokenSupply); uint256 counterAmount = tokensToCounter(tokensToSell); uint256 dividends = SafeMath.div(counterAmount, dividendDivisor); uint256 taxedCounter = SafeMath.sub(counterAmount, dividends); return taxedCounter; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 incomingCounter) internal returns(uint256) { if(incomingCounter == 0){ return reinvestDividends(); } // book keeping address customerAddress = msg.sender; // uint256 undividedDividends = dividendDivisor > 0 ? SafeMath.div(incomingCounter, dividendDivisor) : 0; //this was ref bonus uint256 dividends = dividendDivisor > 0 ? SafeMath.div(incomingCounter, dividendDivisor) : 0; uint256 taxedCounter = SafeMath.sub(incomingCounter, dividends); uint256 amountOfTokens = counterToTokens(taxedCounter); uint256 fee = dividends * magnitude; // prevents overflow assert(amountOfTokens > 0 && (SafeMath.add(amountOfTokens,tokenSupply) > tokenSupply)); // Start making sure we can do the math. No token holders means no dividends, yet. if(tokenSupply > 0){ // add tokens to the pool tokenSupply = SafeMath.add(tokenSupply, amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare += (dividends * magnitude / (tokenSupply)); // calculate the amount of tokens the customer receives fee = dividendDivisor > 0 ? fee - (fee-(amountOfTokens * (dividends * magnitude / (tokenSupply)))) : 0x0; } else { // add tokens to the pool tokenSupply = amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger[customerAddress] = SafeMath.add(tokenBalanceLedger[customerAddress], amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them int256 updatedPayouts = (int256) ((profitPerShare * amountOfTokens) - fee); payoutsTo[customerAddress] += updatedPayouts; // fire events emit Purchase(customerAddress, incomingCounter, amountOfTokens); emit Transfer(0x0, customerAddress, amountOfTokens); return amountOfTokens; } /** * Calculate Token price based on an amount of incoming counter */ function counterToTokens(uint256 counterAmount) internal view returns(uint256) { uint256 tokenPrice = tokenPriceInitial * 1e18; uint256 tokensReceived = ((SafeMath.sub((sqrt((tokenPrice**2)+(2*(tokenPriceIncremental * 1e18)*(counterAmount * 1e18))+(((tokenPriceIncremental)**2)*(tokenSupply**2))+(2*(tokenPriceIncremental)*tokenPrice*tokenSupply))), tokenPrice))/(tokenPriceIncremental))-(tokenSupply); return tokensReceived; } /** * Calculate token sell value. */ function tokensToCounter(uint256 tokens) internal view returns(uint256) { uint256 theTokens = (tokens + 1e18); uint256 theTokenSupply = (tokenSupply + 1e18); // underflow attempts BTFO uint256 etherReceived = (SafeMath.sub((((tokenPriceInitial + (tokenPriceIncremental * (theTokenSupply/1e18)))-tokenPriceIncremental)*(theTokens - 1e18)),(tokenPriceIncremental*((theTokens**2-theTokens)/1e18))/2)/1e18); return etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei 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; } } /** * Owner can transfer out any accidentally sent ERC20 tokens * * Implementation taken from ERC20 reference * */ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { require(tokenAddress != counter); return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
Converts all incoming counter to tokens for the caller/
function purchaseTokensERC20(uint256 amount) public erc20Destination returns(uint256) { require(ERC20Interface(counter).transferFrom(msg.sender, this, amount)); return purchaseTokens(amount); }
957,390
./partial_match/288/0x6AAfC01751A13031A4CA87aF5aA432423021176A/sources/contracts/Ola/Peripheral/PriceOracle/open-oracle/Uniswap/UniswapAnchoredView.sol
Post open oracle reporter prices, and recalculate stored price by comparing to anchor We let anyone pay to post anything, but only prices from configured reporter will be stored in the view. symbols The symbols to compare to anchor for authoritative reading/ OLA_ADDITIONS : Using 'core asset price' instead of 'ethPrice Try to update the view storage
function freshenPrices(string[] calldata symbols) external { uint referenceAssetPrice = fetchReferenceAssetPrice(); for (uint i = 0; i < symbols.length; i++) { postPriceInternal(symbols[i], referenceAssetPrice); } }
16,906,897
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @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() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( ERC20Basic _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } // File: contracts/IMonethaVoucher.sol interface IMonethaVoucher { /** * @dev Total number of vouchers in shared pool */ function totalInSharedPool() external view returns (uint256); /** * @dev Converts vouchers to equivalent amount of wei. * @param _value amount of vouchers (vouchers) to convert to amount of wei * @return A uint256 specifying the amount of wei. */ function toWei(uint256 _value) external view returns (uint256); /** * @dev Converts amount of wei to equivalent amount of vouchers. * @param _value amount of wei to convert to vouchers (vouchers) * @return A uint256 specifying the amount of vouchers. */ function fromWei(uint256 _value) external view returns (uint256); /** * @dev Applies discount for address by returning vouchers to shared pool and transferring funds (in wei). May be called only by Monetha. * @param _for address to apply discount for * @param _vouchers amount of vouchers to return to shared pool * @return Actual number of vouchers returned to shared pool and amount of funds (in wei) transferred. */ function applyDiscount(address _for, uint256 _vouchers) external returns (uint256 amountVouchers, uint256 amountWei); /** * @dev Applies payback by transferring vouchers from the shared pool to the user. * The amount of transferred vouchers is equivalent to the amount of Ether in the `_amountWei` parameter. * @param _for address to apply payback for * @param _amountWei amount of Ether to estimate the amount of vouchers * @return The number of vouchers added */ function applyPayback(address _for, uint256 _amountWei) external returns (uint256 amountVouchers); /** * @dev Function to buy vouchers by transferring equivalent amount in Ether to contract. May be called only by Monetha. * After the vouchers are purchased, they can be sold or released to another user. Purchased vouchers are stored in * a separate pool and may not be expired. * @param _vouchers The amount of vouchers to buy. The caller must also transfer an equivalent amount of Ether. */ function buyVouchers(uint256 _vouchers) external payable; /** * @dev The function allows Monetha account to sell previously purchased vouchers and get Ether from the sale. * The equivalent amount of Ether will be transferred to the caller. May be called only by Monetha. * @param _vouchers The amount of vouchers to sell. * @return A uint256 specifying the amount of Ether (in wei) transferred to the caller. */ function sellVouchers(uint256 _vouchers) external returns(uint256 weis); /** * @dev Function allows Monetha account to release the purchased vouchers to any address. * The released voucher acquires an expiration property and should be used in Monetha ecosystem within 6 months, otherwise * it will be returned to shared pool. May be called only by Monetha. * @param _to address to release vouchers to. * @param _value the amount of vouchers to release. */ function releasePurchasedTo(address _to, uint256 _value) external returns (bool); /** * @dev Function to check the amount of vouchers that an owner (Monetha account) allowed to sell or release to some user. * @param owner The address which owns the funds. * @return A uint256 specifying the amount of vouchers still available for the owner. */ function purchasedBy(address owner) external view returns (uint256); } // File: monetha-utility-contracts/contracts/Restricted.sol /** @title Restricted * Exposes onlyMonetha modifier */ contract Restricted is Ownable { //MonethaAddress set event event MonethaAddressSet( address _address, bool _isMonethaAddress ); mapping (address => bool) public isMonethaAddress; /** * Restrict methods in such way, that they can be invoked only by monethaAddress account. */ modifier onlyMonetha() { require(isMonethaAddress[msg.sender]); _; } /** * Allows owner to set new monetha address */ function setMonethaAddress(address _address, bool _isMonethaAddress) onlyOwner public { isMonethaAddress[_address] = _isMonethaAddress; emit MonethaAddressSet(_address, _isMonethaAddress); } } // File: contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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); } // File: contracts/ownership/CanReclaimEther.sol contract CanReclaimEther is Ownable { event ReclaimEther(address indexed to, uint256 amount); /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { uint256 value = address(this).balance; owner.transfer(value); emit ReclaimEther(owner, value); } /** * @dev Transfer specified amount of Ether held by the contract to the address. * @param _to The address which will receive the Ether * @param _value The amount of Ether to transfer */ function reclaimEtherTo(address _to, uint256 _value) external onlyOwner { require(_to != address(0), "zero address is not allowed"); _to.transfer(_value); emit ReclaimEther(_to, _value); } } // File: contracts/ownership/CanReclaimTokens.sol contract CanReclaimTokens is Ownable { using SafeERC20 for ERC20Basic; event ReclaimTokens(address indexed to, uint256 amount); /** * @dev Reclaim all ERC20Basic compatible tokens * @param _token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic _token) external onlyOwner { uint256 balance = _token.balanceOf(this); _token.safeTransfer(owner, balance); emit ReclaimTokens(owner, balance); } /** * @dev Reclaim specified amount of ERC20Basic compatible tokens * @param _token ERC20Basic The address of the token contract * @param _to The address which will receive the tokens * @param _value The amount of tokens to transfer */ function reclaimTokenTo(ERC20Basic _token, address _to, uint256 _value) external onlyOwner { require(_to != address(0), "zero address is not allowed"); _token.safeTransfer(_to, _value); emit ReclaimTokens(_to, _value); } } // File: contracts/MonethaVoucher.sol contract MonethaVoucher is IMonethaVoucher, Restricted, Pausable, IERC20, CanReclaimEther, CanReclaimTokens { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event DiscountApplied(address indexed user, uint256 releasedVouchers, uint256 amountWeiTransferred); event PaybackApplied(address indexed user, uint256 addedVouchers, uint256 amountWeiEquivalent); event VouchersBought(address indexed user, uint256 vouchersBought); event VouchersSold(address indexed user, uint256 vouchersSold, uint256 amountWeiTransferred); event VoucherMthRateUpdated(uint256 oldVoucherMthRate, uint256 newVoucherMthRate); event MthEthRateUpdated(uint256 oldMthEthRate, uint256 newMthEthRate); event VouchersAdded(address indexed user, uint256 vouchersAdded); event VoucherReleased(address indexed user, uint256 releasedVoucher); event PurchasedVouchersReleased(address indexed from, address indexed to, uint256 vouchers); /* Public variables of the token */ string constant public standard = "ERC20"; string constant public name = "Monetha Voucher"; string constant public symbol = "MTHV"; uint8 constant public decimals = 5; /* For calculating half year */ uint256 constant private DAY_IN_SECONDS = 86400; uint256 constant private YEAR_IN_SECONDS = 365 * DAY_IN_SECONDS; uint256 constant private LEAP_YEAR_IN_SECONDS = 366 * DAY_IN_SECONDS; uint256 constant private YEAR_IN_SECONDS_AVG = (YEAR_IN_SECONDS * 3 + LEAP_YEAR_IN_SECONDS) / 4; uint256 constant private HALF_YEAR_IN_SECONDS_AVG = YEAR_IN_SECONDS_AVG / 2; uint256 constant public RATE_COEFFICIENT = 1000000000000000000; // 10^18 uint256 constant private RATE_COEFFICIENT2 = RATE_COEFFICIENT * RATE_COEFFICIENT; // RATE_COEFFICIENT^2 uint256 public voucherMthRate; // number of voucher units in 10^18 MTH units uint256 public mthEthRate; // number of mth units in 10^18 wei uint256 internal voucherMthEthRate; // number of vouchers units (= voucherMthRate * mthEthRate) in 10^36 wei ERC20Basic public mthToken; mapping(address => uint256) public purchased; // amount of vouchers purchased by other monetha contract uint256 public totalPurchased; // total amount of vouchers purchased by monetha mapping(uint16 => uint256) public totalDistributedIn; // аmount of vouchers distributed in specific half-year mapping(uint16 => mapping(address => uint256)) public distributed; // amount of vouchers distributed in specific half-year to specific user constructor(uint256 _voucherMthRate, uint256 _mthEthRate, ERC20Basic _mthToken) public { require(_voucherMthRate > 0, "voucherMthRate should be greater than 0"); require(_mthEthRate > 0, "mthEthRate should be greater than 0"); require(_mthToken != address(0), "must be valid contract"); voucherMthRate = _voucherMthRate; mthEthRate = _mthEthRate; mthToken = _mthToken; _updateVoucherMthEthRate(); } /** * @dev Total number of vouchers in existence = vouchers in shared pool + vouchers distributed + vouchers purchased */ function totalSupply() external view returns (uint256) { return _totalVouchersSupply(); } /** * @dev Total number of vouchers in shared pool */ function totalInSharedPool() external view returns (uint256) { return _vouchersInSharedPool(_currentHalfYear()); } /** * @dev Total number of vouchers distributed */ function totalDistributed() external view returns (uint256) { return _vouchersDistributed(_currentHalfYear()); } /** * @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) external view returns (uint256) { return _distributedTo(owner, _currentHalfYear()).add(purchased[owner]); } /** * @dev Function to check the amount of vouchers 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 vouchers still available for the spender. */ function allowance(address owner, address spender) external view returns (uint256) { owner; spender; return 0; } /** * @dev Transfer voucher for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) external returns (bool) { to; value; revert(); } /** * @dev Approve the passed address to spend the specified amount of vouchers 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 vouchers to be spent. */ function approve(address spender, uint256 value) external returns (bool) { spender; value; revert(); } /** * @dev Transfer vouchers from one address to another * @param from address The address which you want to send vouchers from * @param to address The address which you want to transfer to * @param value uint256 the amount of vouchers to be transferred */ function transferFrom(address from, address to, uint256 value) external returns (bool) { from; to; value; revert(); } // Allows direct funds send by Monetha function () external onlyMonetha payable { } /** * @dev Converts vouchers to equivalent amount of wei. * @param _value amount of vouchers to convert to amount of wei * @return A uint256 specifying the amount of wei. */ function toWei(uint256 _value) external view returns (uint256) { return _vouchersToWei(_value); } /** * @dev Converts amount of wei to equivalent amount of vouchers. * @param _value amount of wei to convert to vouchers * @return A uint256 specifying the amount of vouchers. */ function fromWei(uint256 _value) external view returns (uint256) { return _weiToVouchers(_value); } /** * @dev Applies discount for address by returning vouchers to shared pool and transferring funds (in wei). May be called only by Monetha. * @param _for address to apply discount for * @param _vouchers amount of vouchers to return to shared pool * @return Actual number of vouchers returned to shared pool and amount of funds (in wei) transferred. */ function applyDiscount(address _for, uint256 _vouchers) external onlyMonetha returns (uint256 amountVouchers, uint256 amountWei) { require(_for != address(0), "zero address is not allowed"); uint256 releasedVouchers = _releaseVouchers(_for, _vouchers); if (releasedVouchers == 0) { return (0,0); } uint256 amountToTransfer = _vouchersToWei(releasedVouchers); require(address(this).balance >= amountToTransfer, "insufficient funds"); _for.transfer(amountToTransfer); emit DiscountApplied(_for, releasedVouchers, amountToTransfer); return (releasedVouchers, amountToTransfer); } /** * @dev Applies payback by transferring vouchers from the shared pool to the user. * The amount of transferred vouchers is equivalent to the amount of Ether in the `_amountWei` parameter. * @param _for address to apply payback for * @param _amountWei amount of Ether to estimate the amount of vouchers * @return The number of vouchers added */ function applyPayback(address _for, uint256 _amountWei) external onlyMonetha returns (uint256 amountVouchers) { amountVouchers = _weiToVouchers(_amountWei); require(_addVouchers(_for, amountVouchers), "vouchers must be added"); emit PaybackApplied(_for, amountVouchers, _amountWei); } /** * @dev Function to buy vouchers by transferring equivalent amount in Ether to contract. May be called only by Monetha. * After the vouchers are purchased, they can be sold or released to another user. Purchased vouchers are stored in * a separate pool and may not be expired. * @param _vouchers The amount of vouchers to buy. The caller must also transfer an equivalent amount of Ether. */ function buyVouchers(uint256 _vouchers) external onlyMonetha payable { uint16 currentHalfYear = _currentHalfYear(); require(_vouchersInSharedPool(currentHalfYear) >= _vouchers, "insufficient vouchers present"); require(msg.value == _vouchersToWei(_vouchers), "insufficient funds"); _addPurchasedTo(msg.sender, _vouchers); emit VouchersBought(msg.sender, _vouchers); } /** * @dev The function allows Monetha account to sell previously purchased vouchers and get Ether from the sale. * The equivalent amount of Ether will be transferred to the caller. May be called only by Monetha. * @param _vouchers The amount of vouchers to sell. * @return A uint256 specifying the amount of Ether (in wei) transferred to the caller. */ function sellVouchers(uint256 _vouchers) external onlyMonetha returns(uint256 weis) { require(_vouchers <= purchased[msg.sender], "Insufficient vouchers"); _subPurchasedFrom(msg.sender, _vouchers); weis = _vouchersToWei(_vouchers); msg.sender.transfer(weis); emit VouchersSold(msg.sender, _vouchers, weis); } /** * @dev Function allows Monetha account to release the purchased vouchers to any address. * The released voucher acquires an expiration property and should be used in Monetha ecosystem within 6 months, otherwise * it will be returned to shared pool. May be called only by Monetha. * @param _to address to release vouchers to. * @param _value the amount of vouchers to release. */ function releasePurchasedTo(address _to, uint256 _value) external onlyMonetha returns (bool) { require(_value <= purchased[msg.sender], "Insufficient Vouchers"); require(_to != address(0), "address should be valid"); _subPurchasedFrom(msg.sender, _value); _addVouchers(_to, _value); emit PurchasedVouchersReleased(msg.sender, _to, _value); return true; } /** * @dev Function to check the amount of vouchers that an owner (Monetha account) allowed to sell or release to some user. * @param owner The address which owns the funds. * @return A uint256 specifying the amount of vouchers still available for the owner. */ function purchasedBy(address owner) external view returns (uint256) { return purchased[owner]; } /** * @dev updates voucherMthRate. */ function updateVoucherMthRate(uint256 _voucherMthRate) external onlyMonetha { require(_voucherMthRate > 0, "should be greater than 0"); require(voucherMthRate != _voucherMthRate, "same as previous value"); voucherMthRate = _voucherMthRate; _updateVoucherMthEthRate(); emit VoucherMthRateUpdated(voucherMthRate, _voucherMthRate); } /** * @dev updates mthEthRate. */ function updateMthEthRate(uint256 _mthEthRate) external onlyMonetha { require(_mthEthRate > 0, "should be greater than 0"); require(mthEthRate != _mthEthRate, "same as previous value"); mthEthRate = _mthEthRate; _updateVoucherMthEthRate(); emit MthEthRateUpdated(mthEthRate, _mthEthRate); } function _addPurchasedTo(address _to, uint256 _value) internal { purchased[_to] = purchased[_to].add(_value); totalPurchased = totalPurchased.add(_value); } function _subPurchasedFrom(address _from, uint256 _value) internal { purchased[_from] = purchased[_from].sub(_value); totalPurchased = totalPurchased.sub(_value); } function _updateVoucherMthEthRate() internal { voucherMthEthRate = voucherMthRate.mul(mthEthRate); } /** * @dev Transfer vouchers from shared pool to address. May be called only by Monetha. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function _addVouchers(address _to, uint256 _value) internal returns (bool) { require(_to != address(0), "zero address is not allowed"); uint16 currentHalfYear = _currentHalfYear(); require(_vouchersInSharedPool(currentHalfYear) >= _value, "must be less or equal than vouchers present in shared pool"); uint256 oldDist = totalDistributedIn[currentHalfYear]; totalDistributedIn[currentHalfYear] = oldDist.add(_value); uint256 oldBalance = distributed[currentHalfYear][_to]; distributed[currentHalfYear][_to] = oldBalance.add(_value); emit VouchersAdded(_to, _value); return true; } /** * @dev Transfer vouchers from address to shared pool * @param _from address The address which you want to send vouchers from * @param _value uint256 the amount of vouchers to be transferred * @return A uint256 specifying the amount of vouchers released to shared pool. */ function _releaseVouchers(address _from, uint256 _value) internal returns (uint256) { require(_from != address(0), "must be valid address"); uint16 currentHalfYear = _currentHalfYear(); uint256 released = 0; if (currentHalfYear > 0) { released = released.add(_releaseVouchers(_from, _value, currentHalfYear - 1)); _value = _value.sub(released); } released = released.add(_releaseVouchers(_from, _value, currentHalfYear)); emit VoucherReleased(_from, released); return released; } function _releaseVouchers(address _from, uint256 _value, uint16 _currentHalfYear) internal returns (uint256) { if (_value == 0) { return 0; } uint256 oldBalance = distributed[_currentHalfYear][_from]; uint256 subtracted = _value; if (oldBalance <= _value) { delete distributed[_currentHalfYear][_from]; subtracted = oldBalance; } else { distributed[_currentHalfYear][_from] = oldBalance.sub(_value); } uint256 oldDist = totalDistributedIn[_currentHalfYear]; if (oldDist == subtracted) { delete totalDistributedIn[_currentHalfYear]; } else { totalDistributedIn[_currentHalfYear] = oldDist.sub(subtracted); } return subtracted; } // converts vouchers to Ether (in wei) function _vouchersToWei(uint256 _value) internal view returns (uint256) { return _value.mul(RATE_COEFFICIENT2).div(voucherMthEthRate); } // converts Ether (in wei) to vouchers function _weiToVouchers(uint256 _value) internal view returns (uint256) { return _value.mul(voucherMthEthRate).div(RATE_COEFFICIENT2); } // converts MTH tokens to vouchers function _mthToVouchers(uint256 _value) internal view returns (uint256) { return _value.mul(voucherMthRate).div(RATE_COEFFICIENT); } // converts Ether (in wei) to MTH function _weiToMth(uint256 _value) internal view returns (uint256) { return _value.mul(mthEthRate).div(RATE_COEFFICIENT); } function _totalVouchersSupply() internal view returns (uint256) { return _mthToVouchers(mthToken.balanceOf(address(this))); } function _vouchersInSharedPool(uint16 _currentHalfYear) internal view returns (uint256) { return _totalVouchersSupply().sub(_vouchersDistributed(_currentHalfYear)).sub(totalPurchased); } function _vouchersDistributed(uint16 _currentHalfYear) internal view returns (uint256) { uint256 dist = totalDistributedIn[_currentHalfYear]; if (_currentHalfYear > 0) { // include previous half-year dist = dist.add(totalDistributedIn[_currentHalfYear - 1]); } return dist; } function _distributedTo(address _owner, uint16 _currentHalfYear) internal view returns (uint256) { uint256 balance = distributed[_currentHalfYear][_owner]; if (_currentHalfYear > 0) { // include previous half-year balance = balance.add(distributed[_currentHalfYear - 1][_owner]); } return balance; } function _currentHalfYear() internal view returns (uint16) { return uint16(now / HALF_YEAR_IN_SECONDS_AVG); } }
Reclaim all ERC20Basic compatible tokens _token ERC20Basic The address of the token contract/
function reclaimToken(ERC20Basic _token) external onlyOwner { uint256 balance = _token.balanceOf(this); _token.safeTransfer(owner, balance); emit ReclaimTokens(owner, balance); }
1,015,211
./full_match/1/0xd2e730d5a15eA4bE6c1cb520e8B81e9fCF79AE62/sources/contracts/token/NativeMetaTransaction.sol
Append userAddress and relayer address at the end to extract it from calling context
emit MetaTransactionExecuted(userAddress, msg.sender, functionSignature); (bool success, bytes memory returnData) = address(this).call(abi.encodePacked(functionSignature, userAddress)); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode(META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature)) ); }
2,947,538
./partial_match/1/0x255D260e73AA6334DA76bb912C14C659912C4A83/sources/contracts/controllers/insurace/InsuracePositionController.sol
If we want to stake other than the base currency, we swap.
function stake(uint256 _amount) external override onlyIndex { require(canStake(), "InsuracePositionController: IPC0"); require( _amount >= _stakingController.minStakeAmtPT(stakingAsset), "InsuracePositionController: IPC1" ); base.safeTransferFrom(_msgSender(), address(this), _amount); if (address(base) != stakingAsset) { _checkApprovals(IERC20(base), address(_uniswapRouter), _amount); _swapTokenForToken(_amount, address(base), stakingAsset, swapVia); } uint256 investmentAmount = ERC20(stakingAsset).balanceOf(address(this)); require(investmentAmount != 0, "InsuracePositionController: IPC3"); require(_lptokenBalance >= 0, "InsuracePositionController: IPC4"); setStakingState(); }
15,723,994
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 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 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); } } /// @dev Interface to the Core Contract of Ether Dungeon. contract EDCoreInterface { /// @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 ); /** * @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 ); /** * @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 ); /** * @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 ); /** * @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 ); /// @dev Get the attributes (equipments + stats) of a hero from its gene. function getHeroAttributes(uint _genes) public pure returns (uint[]); /// @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 ); /// @dev Calculate the power of a dungeon floor. function getDungeonPower(uint _genes) public pure returns (uint); /** * @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); } /** * @title Core Contract of "Dungeon Run" event game of the ED (Ether Dungeon) Platform. * @dev Dungeon Run is a single-player game mode added to the Ether Dungeon platform. * The objective of Dungeon Run is to defeat as many monsters as possible. */ contract DungeonRunBeta is Pausable, Destructible { /*================================= = STRUCTS = =================================*/ struct Monster { uint64 creationTime; uint8 level; uint16 initialHealth; uint16 health; } /*================================= = CONTRACTS = =================================*/ /// @dev The address of the EtherDungeonCore contract. EDCoreInterface public edCoreContract = EDCoreInterface(0xf7eD56c1AC4d038e367a987258b86FC883b960a1); /*================================= = CONSTANTS = =================================*/ /// @dev By defeating the checkPointLevel, half of the entranceFee is refunded. uint8 public constant checkpointLevel = 4; /// @dev By defeating the breakevenLevel, another half of the entranceFee is refunded. uint8 public constant breakevenLevel = 8; /// @dev By defeating the jackpotLevel, the player win the entire jackpot. uint8 public constant jackpotLevel = 12; /// @dev Dungeon difficulty to be used when calculating super hero power boost, 3 is 64 power boost. uint public constant dungeonDifficulty = 3; /// @dev The health of a monster is level * monsterHealth; uint16 public monsterHealth = 10; /// @dev When a monster flees, the hero health is reduced by monster level + monsterStrength. uint public monsterStrength = 4; /// @dev After a certain period of time, the monster will attack the hero and flee. uint64 public monsterFleeTime = 8 minutes; /*================================= = SETTINGS = =================================*/ /// @dev To start a run, a player need to pay an entrance fee. uint public entranceFee = 0.04 ether; /// @dev 0.1 ether is provided as the initial jackpot. uint public jackpot = 0.1 ether; /** * @dev The dungeon run entrance fee will first be deposited to a pool first, when the hero is * defeated by a monster, then the fee will be added to the jackpot. */ uint public entranceFeePool; /// @dev Private seed for the PRNG used for calculating damage amount. uint _seed; /*================================= = STATE VARIABLES = =================================*/ /// @dev A mapping from hero ID to the current run monster, a 0 value indicates no current run. mapping(uint => Monster) public heroIdToMonster; /// @dev A mapping from hero ID to its current health. mapping(uint => uint) public heroIdToHealth; /// @dev A mapping from hero ID to the refunded fee. mapping(uint => uint) public heroIdToRefundedFee; /*============================== = EVENTS = ==============================*/ /// @dev The LogAttack event is fired whenever a hero attack a monster. event LogAttack(uint timestamp, address indexed player, uint indexed heroId, uint indexed monsterLevel, uint damageByHero, uint damageByMonster, bool isMonsterDefeated, uint rewards); function DungeonRunAlpha() public payable {} /*======================================= = PUBLIC/EXTERNAL FUNCTIONS = =======================================*/ /// @dev The external function to get all the game settings in one call. function getGameSettings() external view returns ( uint _checkpointLevel, uint _breakevenLevel, uint _jackpotLevel, uint _dungeonDifficulty, uint _monsterHealth, uint _monsterStrength, uint _monsterFleeTime, uint _entranceFee ) { _checkpointLevel = checkpointLevel; _breakevenLevel = breakevenLevel; _jackpotLevel = jackpotLevel; _dungeonDifficulty = dungeonDifficulty; _monsterHealth = monsterHealth; _monsterStrength = monsterStrength; _monsterFleeTime = monsterFleeTime; _entranceFee = entranceFee; } /// @dev The external function to get the dungeon run details in one call. function getRunDetails(uint _heroId) external view returns ( uint _heroPower, uint _heroStrength, uint _heroInitialHealth, uint _heroHealth, uint _monsterCreationTime, uint _monsterLevel, uint _monsterInitialHealth, uint _monsterHealth, uint _gameState // 0: NotStarted | 1: NewMonster | 2: Active | 3: RunEnded ) { uint genes; address owner; (,,, genes, owner,,) = edCoreContract.getHeroDetails(_heroId); (_heroPower,,,,) = edCoreContract.getHeroPower(genes, dungeonDifficulty); _heroStrength = (genes / (32 ** 8)) % 32 + 1; _heroInitialHealth = (genes / (32 ** 12)) % 32 + 1; _heroHealth = heroIdToHealth[_heroId]; Monster memory monster = heroIdToMonster[_heroId]; _monsterCreationTime = monster.creationTime; // Dungeon run is ended if either hero is defeated (health exhausted), // or hero failed to damage a monster before it flee. bool _dungeonRunEnded = monster.level > 0 && ( _heroHealth == 0 || now > _monsterCreationTime + monsterFleeTime * 2 || (monster.health == monster.initialHealth && now > monster.creationTime + monsterFleeTime) ); // Calculate hero and monster stats based on different game state. if (monster.level == 0) { // Dungeon run not started yet. _heroHealth = _heroInitialHealth; _monsterLevel = 1; _monsterInitialHealth = monsterHealth; _monsterHealth = _monsterInitialHealth; _gameState = 0; } else if (_dungeonRunEnded) { // Dungeon run ended. _monsterLevel = monster.level; _monsterInitialHealth = monster.initialHealth; _monsterHealth = monster.health; _gameState = 3; } else if (now > _monsterCreationTime + monsterFleeTime) { // Previous monster just fled, new monster awaiting. if (monster.level + monsterStrength > _heroHealth) { _heroHealth = 0; _monsterLevel = monster.level; _monsterInitialHealth = monster.initialHealth; _monsterHealth = monster.health; _gameState = 2; } else { _heroHealth -= monster.level + monsterStrength; _monsterCreationTime += monsterFleeTime; _monsterLevel = monster.level + 1; _monsterInitialHealth = _monsterLevel * monsterHealth; _monsterHealth = _monsterInitialHealth; _gameState = 1; } } else { // Active monster. _monsterLevel = monster.level; _monsterInitialHealth = monster.initialHealth; _monsterHealth = monster.health; _gameState = 2; } } /** * @dev To start a dungeon run, player need to call the attack function with an entranceFee. * Future attcks required no fee, player just need to send a free transaction * to the contract, before the monster flee. The lower the gas price, the larger the damage. * This function is prevented from being called by a contract, using the onlyHumanAddress modifier. * Note that each hero can only perform one dungeon run. */ function attack(uint _heroId) whenNotPaused onlyHumanAddress external payable { uint genes; address owner; (,,, genes, owner,,) = edCoreContract.getHeroDetails(_heroId); // Throws if the hero is not owned by the player. require(msg.sender == owner); // Get the health and strength of the hero. uint heroInitialHealth = (genes / (32 ** 12)) % 32 + 1; uint heroStrength = (genes / (32 ** 8)) % 32 + 1; // Get the current monster and hero current health. Monster memory monster = heroIdToMonster[_heroId]; uint currentLevel = monster.level; uint heroCurrentHealth = heroIdToHealth[_heroId]; // A flag determine whether the dungeon run has ended. bool dungeonRunEnded; // To start a run, the player need to pay an entrance fee. if (currentLevel == 0) { // Throws if not enough fee, and any exceeding fee will be transferred back to the player. require(msg.value >= entranceFee); entranceFeePool += entranceFee; // Create level 1 monster, initial health is 1 * monsterHealth. heroIdToMonster[_heroId] = Monster(uint64(now), 1, monsterHealth, monsterHealth); monster = heroIdToMonster[_heroId]; // Set the hero initial health to storage. heroIdToHealth[_heroId] = heroInitialHealth; heroCurrentHealth = heroInitialHealth; // Refund exceeding fee. if (msg.value > entranceFee) { msg.sender.transfer(msg.value - entranceFee); } } else { // If the hero health is 0, the dungeon run has ends. require(heroCurrentHealth > 0); // If a hero failed to damage a monster before it flee, the dungeon run ends, // regardless of the remaining hero health. dungeonRunEnded = now > monster.creationTime + monsterFleeTime * 2 || (monster.health == monster.initialHealth && now > monster.creationTime + monsterFleeTime); if (dungeonRunEnded) { // Add the non-refunded fee to jackpot. uint addToJackpot = entranceFee - heroIdToRefundedFee[_heroId]; jackpot += addToJackpot; entranceFeePool -= addToJackpot; // Sanity check. assert(addToJackpot <= entranceFee); } // Future attack do not require any fee, so refund all ether sent with the transaction. msg.sender.transfer(msg.value); } if (!dungeonRunEnded) { // All pre-conditions passed, call the internal attack function. _attack(_heroId, genes, heroStrength, heroCurrentHealth); } } /*======================================= = SETTER FUNCTIONS = =======================================*/ function setEdCoreContract(address _newEdCoreContract) onlyOwner external { edCoreContract = EDCoreInterface(_newEdCoreContract); } function setEntranceFee(uint _newEntranceFee) onlyOwner external { entranceFee = _newEntranceFee; } /*======================================= = INTERNAL/PRIVATE FUNCTIONS = =======================================*/ /// @dev Internal function of attack, assume all parameter checking is done. function _attack(uint _heroId, uint _genes, uint _heroStrength, uint _heroCurrentHealth) internal { Monster storage monster = heroIdToMonster[_heroId]; uint8 currentLevel = monster.level; // Get the hero power. uint heroPower; (heroPower,,,,) = edCoreContract.getHeroPower(_genes, dungeonDifficulty); uint damageByMonster; uint damageByHero; // Calculate the damage by monster. // Determine if the monster has fled due to hero failed to attack within flee period. if (now > monster.creationTime + monsterFleeTime) { // When a monster flees, the monster will attack the hero and flee. // The damage is calculated by monster level + monsterStrength. damageByMonster = currentLevel + monsterStrength; } else { // When a monster attack back the hero, the damage will be less than monster level / 2. if (currentLevel >= 2) { damageByMonster = _getRandomNumber(currentLevel / 2); } } // Check if hero is defeated. if (damageByMonster >= _heroCurrentHealth) { // Hero is defeated, the dungeon run ends. heroIdToHealth[_heroId] = 0; // Added the non-refunded fee to jackpot. uint addToJackpot = entranceFee - heroIdToRefundedFee[_heroId]; jackpot += addToJackpot; entranceFeePool -= addToJackpot; // Sanity check. assert(addToJackpot <= entranceFee); } else { // Hero is damanged but didn&#39;t defeated, game continues with a new monster. heroIdToHealth[_heroId] -= damageByMonster; // If monser fled, create next level monster. if (now > monster.creationTime + monsterFleeTime) { currentLevel++; heroIdToMonster[_heroId] = Monster(uint64(monster.creationTime + monsterFleeTime), currentLevel, currentLevel * monsterHealth, currentLevel * monsterHealth); monster = heroIdToMonster[_heroId]; } // Calculate the damage by hero. // The damage formula is [[strength / gas + power / (10 * rand)]], // where rand is a random integer from 1 to 5. damageByHero = (_heroStrength * 1e9 + heroPower * 1e9 / (10 * (1 + _getRandomNumber(5)))) / tx.gasprice; bool isMonsterDefeated = damageByHero >= monster.health; uint rewards; if (isMonsterDefeated) { // Monster is defeated, game continues with a new monster. // Create next level monster. uint8 newLevel = currentLevel + 1; heroIdToMonster[_heroId] = Monster(uint64(now), newLevel, newLevel * monsterHealth, newLevel * monsterHealth); monster = heroIdToMonster[_heroId]; // Determine the rewards based on current level. if (currentLevel == checkpointLevel) { // By defeating the checkPointLevel, half of the entranceFee is refunded. rewards = entranceFee / 2; heroIdToRefundedFee[_heroId] += rewards; entranceFeePool -= rewards; } else if (currentLevel == breakevenLevel) { // By defeating the breakevenLevel, another half of the entranceFee is refunded. rewards = entranceFee / 2; heroIdToRefundedFee[_heroId] += rewards; entranceFeePool -= rewards; } else if (currentLevel == jackpotLevel) { // By defeating the jackpotLevel, the player win the entire jackpot. rewards = jackpot / 2; jackpot -= rewards; } msg.sender.transfer(rewards); } else { // Monster is damanged but not defeated, hurry up! monster.health -= uint8(damageByHero); } } // Emit LogAttack event. LogAttack(now, msg.sender, _heroId, currentLevel, damageByHero, damageByMonster, isMonsterDefeated, rewards); } /// @dev Return a pseudo random uint smaller than _upper bounds. function _getRandomNumber(uint _upper) private returns (uint) { _seed = uint(keccak256( _seed, block.blockhash(block.number - 1), block.coinbase, block.difficulty )); return _seed % _upper; } /*============================== = MODIFIERS = ==============================*/ /// @dev Throws if the caller address is a contract. modifier onlyHumanAddress() { address addr = msg.sender; uint size; assembly { size := extcodesize(addr) } require(size == 0); _; } }
Internal function of attack, assume all parameter checking is done. Get the hero power. Calculate the damage by monster. Determine if the monster has fled due to hero failed to attack within flee period. When a monster flees, the monster will attack the hero and flee. The damage is calculated by monster level + monsterStrength. When a monster attack back the hero, the damage will be less than monster level / 2. Check if hero is defeated. Hero is defeated, the dungeon run ends. Added the non-refunded fee to jackpot. Sanity check. Hero is damanged but didn&39;t defeated, game continues with a new monster. If monser fled, create next level monster. Monster is defeated, game continues with a new monster. Create next level monster. Determine the rewards based on current level. By defeating the checkPointLevel, half of the entranceFee is refunded. By defeating the breakevenLevel, another half of the entranceFee is refunded. By defeating the jackpotLevel, the player win the entire jackpot.
function _attack(uint _heroId, uint _genes, uint _heroStrength, uint _heroCurrentHealth) internal { Monster storage monster = heroIdToMonster[_heroId]; uint8 currentLevel = monster.level; uint heroPower; (heroPower,,,,) = edCoreContract.getHeroPower(_genes, dungeonDifficulty); uint damageByMonster; uint damageByHero; if (now > monster.creationTime + monsterFleeTime) { damageByMonster = currentLevel + monsterStrength; if (currentLevel >= 2) { damageByMonster = _getRandomNumber(currentLevel / 2); } } if (damageByMonster >= _heroCurrentHealth) { heroIdToHealth[_heroId] = 0; uint addToJackpot = entranceFee - heroIdToRefundedFee[_heroId]; jackpot += addToJackpot; entranceFeePool -= addToJackpot; assert(addToJackpot <= entranceFee); heroIdToHealth[_heroId] -= damageByMonster; if (now > monster.creationTime + monsterFleeTime) { currentLevel++; heroIdToMonster[_heroId] = Monster(uint64(monster.creationTime + monsterFleeTime), currentLevel, currentLevel * monsterHealth, currentLevel * monsterHealth); monster = heroIdToMonster[_heroId]; } bool isMonsterDefeated = damageByHero >= monster.health; uint rewards; if (isMonsterDefeated) { uint8 newLevel = currentLevel + 1; heroIdToMonster[_heroId] = Monster(uint64(now), newLevel, newLevel * monsterHealth, newLevel * monsterHealth); monster = heroIdToMonster[_heroId]; if (currentLevel == checkpointLevel) { rewards = entranceFee / 2; heroIdToRefundedFee[_heroId] += rewards; entranceFeePool -= rewards; rewards = entranceFee / 2; heroIdToRefundedFee[_heroId] += rewards; entranceFeePool -= rewards; rewards = jackpot / 2; jackpot -= rewards; } msg.sender.transfer(rewards); } } }
2,123,363
./full_match/1/0xE40782171Fd4f583c98E41bD889b702bA9574BBB/sources/contracts/ETHGen.sol
Allows a Provider to send commissions to the network (the provider MUST be a Member as well) _providerAmountInGWEI + _distAmountInGWEI must match the amount sent by the purchaser A percentage of the provider amount goes to ETH Gen as sales commissions unless the entire amount is sent to commission tree Note: This will use the stored fee...or default to a standard 5.00% fee...providerToFee is set in setProviderFee by the contract owner If the sender is in the system, it determines the enroller and ignores the _enroller passed Otherwise, if the sender is not in the system, the sender is assumed to be a customer and an enroller should be specified who is responsible for the sale Note: This means the provider tracked who the customer was brought to their site by (in other words, the affiliate who IS a member of this system) Note: This is on the honor of the provider as the smart contract would not know this...they could pass a bad address and keep the customer as their own But, if there is no _enroller passed, then the amount is considered a house sale and distribution amount starts with the provider as the enroller/ Compute the provider fee collected by ETHGen... Transfer failed to ETHGen Transfer failed to Provider Provider Not Found In System (they must be a member)... If we have a customer and the enroller is not passed, then they are treated as a customer of the partner directly In that case we treat the enroller as the partner's member account directly for distribution... The caller is not a member, so they must be a customer... If the provider tracked that customer's affiliate status and passed a member to use we use that here... We found the purchaser and they are a member...so make sure their enroller is the start of the distribution...
function processProductPurchase(address _provider, address _enroller, uint256 _providerAmountInWEI, uint256 _distAmountInWEI) external payable returns(uint256) { if(_providerAmountInWEI > 0) { uint256 eamount = (_providerAmountInWEI.mul(ethgenFee)).div(10000); uint256 pamount = _providerAmountInWEI.sub(eamount); if(eamount > 0) { } if(pamount > 0) { } } if(_distAmountInWEI > 0) { uint256 ID = getID(msg.sender); if(ID == 0) { uint256 eID = getID(_enroller); if(eID == 0) { uint256 pID = getID(_provider); } else { } } else { } } return block.number; }
3,109,604
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false // Authorized callers mapping(address => bool) private authorizedContracts; // Airline vars struct Airline { string name; address airlineAddress; bool isPendingDeposit; } mapping(address => Airline) private airlines; uint private airlinesAmount = 0; // User account vars struct Insurance { address airline; string flight; uint256 timestamp; uint256 insuranceAmount; uint256 creditInsuree; } struct User { address userAddress; bool isActive; mapping(bytes32 => Insurance) insurances; // bytes32 key => flightKey } mapping(address => User) private userAccounts; // address key => userAddress // Max insurance value (configurable by onlyOwner method) uint256 maxInsuranceCharge = 1; /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner * * The deployer is the original owner, not the contract caller */ constructor(string _name, address _airlineAddress) public { contractOwner = msg.sender; registerAirline(_name, _airlineAddress); } /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ // Emitted when the airline pass the consensus event AirlineAccepted(string _name, address _airlineAddress); // Emitted when the airline deposit de insurance amount event AirlineRegistred(string _name, address _airlineAddress); // Emitted when user buy an insurance event PurchasedInsurance(address _userAddress, address _airlineAddress, string _flight, uint256 timestamp); // Emitted when the insurance credit to refund is set to user account event InsuranceCreditAvailableToRefund(address _userAddress, uint256 _creditInsurees, address _airlineAddress, string _flight, uint256 _timestamp); // Emitted when the insurance credit is refunded event InsuranceCreditRefunded(address _userAddress, uint256 refund, address _airlineAddress, string _flight, uint256 _timestamp); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireIsCallerAuthorized() { require(authorizedContracts[msg.sender] || msg.sender == contractOwner, "Caller not authorized"); _; } modifier requireIsAirlinePendingDeposit(address _airlineAddress) { require(airlines[_airlineAddress].isPendingDeposit, "Airline not authorized to deposit funds"); _; } modifier requireIsAirlinePaidEnough() { require(msg.value >= 10 ether, "Insufficent funds, must be 10 ether"); _; } modifier requireIsUserPaidEnough() { require(msg.value >= 0, "Incorrect deposit, must be a maximum of 1 ether"); _; } modifier requireIsUserActive(address _userAddress) { require(userAccounts[_userAddress].isActive, "User not exists"); _; } modifier requireIsElegiblePayout(address _userAddress, address _airlineAddress, string _flight, uint256 _timestamp) { bytes32 flightKey = getFlightKey(_airlineAddress, _flight, _timestamp); require(userAccounts[_userAddress].insurances[flightKey].creditInsuree > 0, "User is not elegible to payout"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() external view returns(bool) { return operational; } function isAirlineAuthorized() external view returns(bool) { return !airlines[msg.sender].isPendingDeposit; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus(bool mode) external requireContractOwner { operational = mode; } function authorizeContract(address contractAddress) public requireContractOwner { authorizedContracts[contractAddress] = true; } function deauthorizeContract(address contractAddress) external requireContractOwner { delete authorizedContracts[contractAddress]; } function setMaxInsuranceCharge(uint256 _maxInsuranceCharge) external requireContractOwner { maxInsuranceCharge = _maxInsuranceCharge; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ function getAirlinesAmount() external view requireIsOperational requireIsCallerAuthorized returns(uint) { return airlinesAmount; } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * * struct Airline { * string name; * address airlineAddress; * bool isPendingDeposit; * } */ function registerAirline(string _name, address _airlineAddress) public requireIsOperational requireIsCallerAuthorized { Airline memory newAirline = Airline( _name, _airlineAddress, true ); airlines[_airlineAddress] = newAirline; airlinesAmount++; emit AirlineAccepted(_name, _airlineAddress); } /** * @dev Buy insurance for a flight * */ function buy(address _userAddress, address _airlineAddress, string _flight, uint256 _timestamp) external payable requireIsOperational requireIsCallerAuthorized requireIsUserActive(_userAddress) requireIsUserPaidEnough { bytes32 flightKey = getFlightKey(_airlineAddress, _flight, _timestamp); if (msg.value > maxInsuranceCharge) { // Set payment userAccounts[_userAddress].insurances[flightKey].insuranceAmount = maxInsuranceCharge; // Return the difference uint amountToReturn = msg.value - maxInsuranceCharge; _userAddress.transfer(amountToReturn); } else { // Set payment userAccounts[_userAddress].insurances[flightKey].insuranceAmount = msg.value; } // Inform to listeners emit PurchasedInsurance(msg.sender, _airlineAddress, _flight, _timestamp); } function getInsurancePaymentAmount(address _userAddress, address _airlineAddress, string _flight, uint256 _timestamp) external view requireIsOperational requireIsCallerAuthorized returns(uint256) { bytes32 flightKey = getFlightKey(_airlineAddress, _flight, _timestamp); return userAccounts[_userAddress].insurances[flightKey].insuranceAmount; } /** * @dev Credits payouts to insurees * Queremos asegurarnos de no enviar los fondos directamente. Primero acreditar si los usuarios son elegibles para un pago y luego, cuando llega en momento de los pagos, podemos llamar a la función pay para retirar los fondos */ function setCreditInsuree(address _userAddress, uint256 _creditInsurees, address _airlineAddress, string _flight, uint256 _timestamp) external requireIsOperational requireIsCallerAuthorized { bytes32 flightKey = getFlightKey(_airlineAddress, _flight, _timestamp); userAccounts[_userAddress].insurances[flightKey].creditInsuree = _creditInsurees; emit InsuranceCreditAvailableToRefund(_userAddress, _creditInsurees, _airlineAddress, _flight, _timestamp); } /** * @dev Transfers eligible payout funds to insuree * */ function pay(address _userAddress, address _airlineAddress, string _flight, uint256 _timestamp) external payable // TODO: Must be payable? requireIsOperational requireIsCallerAuthorized requireIsElegiblePayout(_userAddress, _airlineAddress, _flight, _timestamp) { // Reset insurace vars bytes32 flightKey = getFlightKey(_airlineAddress, _flight, _timestamp); uint256 refund = userAccounts[_userAddress].insurances[flightKey].creditInsuree; userAccounts[_userAddress].insurances[flightKey].creditInsuree = 0; userAccounts[_userAddress].insurances[flightKey].insuranceAmount = 0; // Refund _userAddress.transfer(refund); emit InsuranceCreditRefunded(_userAddress, refund, _airlineAddress, _flight, _timestamp); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * El lo que la aerolinea usaría para activarse ella misma. * Las aerolineas pasan por un proceso de 2 pasos: primero deben registrarse, y después de la cuarta aerolinea deben esperar que el resto de aerolineas voten. Una vez hecho esto, deben ingresar (fund) los 10 ethers para estar activos en el contrato */ function fund(address _airlineAddress) public payable requireIsOperational requireIsCallerAuthorized requireIsAirlinePendingDeposit(_airlineAddress) requireIsAirlinePaidEnough { // Set the airline deposit up to date airlines[_airlineAddress].isPendingDeposit = false; // Return the payment difference to sender uint amountToReturn = msg.value - 10 ether; _airlineAddress.transfer(amountToReturn); emit AirlineRegistred(airlines[_airlineAddress].name, airlines[_airlineAddress].airlineAddress); } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) view internal requireIsOperational returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ // function() // external // payable // { // fund(); // } }
Initial funding for the insurance. Unless there are too many delayed flights resulting in insurance payouts, the contract should be self-sustaining El lo que la aerolinea usaría para activarse ella misma. Las aerolineas pasan por un proceso de 2 pasos: primero deben registrarse, y después de la cuarta aerolinea deben esperar que el resto de aerolineas voten. Una vez hecho esto, deben ingresar (fund) los 10 ethers para estar activos en el contrato/ Set the airline deposit up to date Return the payment difference to sender
function fund(address _airlineAddress) public payable requireIsOperational requireIsCallerAuthorized requireIsAirlinePendingDeposit(_airlineAddress) requireIsAirlinePaidEnough { airlines[_airlineAddress].isPendingDeposit = false; uint amountToReturn = msg.value - 10 ether; _airlineAddress.transfer(amountToReturn); emit AirlineRegistred(airlines[_airlineAddress].name, airlines[_airlineAddress].airlineAddress); }
1,774,615
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { DSMath } from "../lib/ds-hub.sol"; import { StorageSlotOwnable } from "../lib/StorageSlotOwnable.sol"; import { OnApprove } from "../token/ERC20OnApprove.sol"; import { NonLinearTimeLockSwapperV2_0_4Storage } from "./NonLinearTimeLockSwapperV2_0_4Storage.sol"; contract NonLinearTimeLockSwapperV2_0_4 is NonLinearTimeLockSwapperV2_0_4Storage, StorageSlotOwnable, DSMath, OnApprove { using SafeERC20 for IERC20; using SafeMath for uint256; modifier onlyValidAddress(address account) { require(account != address(0), "zero-address"); _; } modifier onlyDeposit(address sourceToken, address account) { require(depositAmounts[sourceToken][account] != 0, "no-deposit"); _; } event Deposited( address indexed sourceToken, address indexed beneficiary, uint256 sourceTokenAmount, uint256 targetTokenAmount ); event Undeposited(address indexed sourceToken, address indexed beneficiary, uint256 amount, address receiver); event Claimed(address indexed sourceToken, address indexed beneficiary, uint256 targetTokenAmount); event TokenWalletChanged(address indexed previousWallet, address newWallet); ////////////////////////////////////////// // // kernel // ////////////////////////////////////////// function implementationVersion() public view virtual override returns (string memory) { return "2.0.4"; } function _initializeKernel(bytes memory data) internal override { (address owner_, address token_, address tokenWallet_) = abi.decode(data, (address, address, address)); _initializeV2(owner_, token_, tokenWallet_); } function _initializeV2( address owner_, address token_, address tokenWallet_ ) private onlyValidAddress(owner_) onlyValidAddress(token_) onlyValidAddress(tokenWallet_) { if (owner() == address(0)) _setOwner(owner_); if (address(token) == address(0)) token = IERC20(token_); if (tokenWallet == address(0)) tokenWallet = tokenWallet_; _registerInterface(OnApprove(this).onApprove.selector); } ////////////////////////////////////////// // // token wallet // ////////////////////////////////////////// function setTokenWallet(address tokenWallet_) external onlyOwner onlyValidAddress(tokenWallet_) { address previousWallet = tokenWallet; tokenWallet = tokenWallet_; emit TokenWalletChanged(previousWallet, tokenWallet_); } ////////////////////////////////////////// // // register source token // ////////////////////////////////////////// /** * @dev register source token with vesting data */ function register( address sourceToken, uint128 rate, uint128 startTime, uint256[] memory stepEndTimes, uint256[] memory stepRatio ) external onlyOwner { require(!isRegistered(sourceToken), "duplicate-register"); require(rate > 0, "invalid-rate"); require(stepEndTimes.length == stepRatio.length, "invalid-array-length"); uint256 n = stepEndTimes.length; uint256[] memory accStepRatio = new uint256[](n); uint256 accRatio; for (uint256 i = 0; i < n; i++) { accRatio = add(accRatio, stepRatio[i]); accStepRatio[i] = accRatio; } require(accRatio == WAD, "invalid-acc-ratio"); for (uint256 i = 1; i < n; i++) { require(stepEndTimes[i - 1] < stepEndTimes[i], "unsorted-times"); } sourceTokenDatas[sourceToken] = SourceTokeData({ rate: rate, startTime: startTime, stepEndTimes: stepEndTimes, accStepRatio: accStepRatio }); } function isRegistered(address sourceToken) public view returns (bool) { return sourceTokenDatas[sourceToken].startTime > 0; } function getStepEndTimes(address sourceToken) external view returns (uint256[] memory) { return sourceTokenDatas[sourceToken].stepEndTimes; } function getAccStepRatio(address sourceToken) external view returns (uint256[] memory) { return sourceTokenDatas[sourceToken].accStepRatio; } ////////////////////////////////////////// // // source token deposit // ////////////////////////////////////////// function onApprove( address owner, address spender, uint256 amount, bytes calldata data ) external override returns (bool) { require(spender == address(this), "invalid-approval"); require(isRegistered(msg.sender), "unregistered-source-token"); deposit(msg.sender, owner, amount); data; return true; } // deposit sender's token function deposit( address sourceToken, address beneficiary, uint256 sourceTokenAmount ) public onlyValidAddress(beneficiary) { require(isRegistered(sourceToken), "unregistered-source-token"); require(sourceTokenAmount > 0, "invalid-amount"); require(msg.sender == address(sourceToken) || msg.sender == beneficiary, "no-auth"); SourceTokeData storage data = sourceTokenDatas[sourceToken]; uint256 targetTokenAmount = wmul(sourceTokenAmount, data.rate); // update initial balance depositAmounts[sourceToken][beneficiary] = depositAmounts[sourceToken][beneficiary].add(sourceTokenAmount); // get source token from beneficiary IERC20(sourceToken).safeTransferFrom(beneficiary, address(this), sourceTokenAmount); emit Deposited(sourceToken, beneficiary, sourceTokenAmount, targetTokenAmount); } ////////////////////////////////////////// // // claim // ////////////////////////////////////////// function claim(address sourceToken) public onlyDeposit(sourceToken, msg.sender) { uint256 amount = claimable(sourceToken, msg.sender); require(amount > 0, "invalid-amount"); claimedAmounts[sourceToken][msg.sender] = claimedAmounts[sourceToken][msg.sender].add(amount); token.safeTransferFrom(tokenWallet, msg.sender, amount); emit Claimed(sourceToken, msg.sender, amount); } function claimTokens(address[] calldata sourceTokens) external { for (uint256 i = 0; i < sourceTokens.length; i++) { claim(sourceTokens[i]); } } /** * @dev get claimable tokens now */ function claimable(address sourceToken, address beneficiary) public view returns (uint256) { return claimableAt(sourceToken, beneficiary, block.timestamp); } /** * @dev get claimable tokens at `timestamp` */ function claimableAt( address sourceToken, address beneficiary, uint256 timestamp ) public view returns (uint256) { require(block.timestamp <= timestamp, "invalid-timestamp"); SourceTokeData storage sourceTokenData = sourceTokenDatas[sourceToken]; uint256 totalClaimable = wmul(depositAmounts[sourceToken][beneficiary], sourceTokenData.rate); uint256 claimedAmount = claimedAmounts[sourceToken][beneficiary]; if (timestamp < sourceTokenData.startTime) return 0; if (timestamp >= sourceTokenData.stepEndTimes[sourceTokenData.stepEndTimes.length - 1]) return totalClaimable.sub(claimedAmount); uint256 step = getStepAt(sourceToken, timestamp); uint256 accRatio = sourceTokenData.accStepRatio[step]; uint256 claimableAmount = wmul(totalClaimable, accRatio); return claimableAmount > claimedAmount ? claimableAmount.sub(claimedAmount) : 0; } function initialBalance(address sourceToken, address beneficiary) external view returns (uint256) { return depositAmounts[sourceToken][beneficiary]; } /** * @dev get current step */ function getStep(address sourceToken) public view returns (uint256) { return getStepAt(sourceToken, block.timestamp); } /** * @dev get step at `timestamp` */ function getStepAt(address sourceToken, uint256 timestamp) public view returns (uint256) { SourceTokeData storage sourceTokenData = sourceTokenDatas[sourceToken]; require(timestamp >= sourceTokenData.startTime, "not-started"); uint256 n = sourceTokenData.stepEndTimes.length; if (timestamp >= sourceTokenData.stepEndTimes[n - 1]) { return n - 1; } if (timestamp <= sourceTokenData.stepEndTimes[0]) { return 0; } uint256 lo = 1; uint256 hi = n - 1; uint256 md; while (lo < hi) { md = (hi + lo + 1) / 2; if (timestamp < sourceTokenData.stepEndTimes[md - 1]) { hi = md - 1; } else { lo = md; } } return lo; } } // 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 Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface DSAuthority { function canCall( address src, address dst, bytes4 sig ) external view returns (bool); } contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(address(0))) { return false; } else { return authority.canCall(src, address(this), sig); } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; uint256 wad; assembly { foo := calldataload(4) bar := calldataload(36) wad := callvalue() } _; emit LogNote(msg.sig, msg.sender, foo, bar, wad, msg.data); } } contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; //rounds to zero if x*y < WAD / 2 function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } //rounds to zero if x*y < WAD / 2 function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } //rounds to zero if x*y < RAY / 2 function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract DSThing is DSAuth, DSNote, DSMath { function S(string memory s) internal pure returns (bytes4) { return bytes4(keccak256(abi.encodePacked(s))); } } contract DSValue is DSThing { bool has; bytes32 val; function peek() public view returns (bytes32, bool) { return (val, has); } function read() public view returns (bytes32) { bytes32 wut; bool haz; (wut, haz) = peek(); require(haz, "haz-not"); return wut; } function poke(bytes32 wut) public note auth { val = wut; has = true; } function void() public note auth { // unset the value has = false; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/StorageSlot.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 StorageSlotOwnable is Context { bytes32 private constant _OWNER_SLOT = bytes32(uint256(keccak256("StorageSlotOwnable.owner")) - 1); /** * @dev Returns the current owner. */ function _getOwner() internal view returns (address) { return StorageSlot.getAddressSlot(_OWNER_SLOT).value; } /** * @dev Stores a new address in the owner slot. */ function _setOwner(address newOwner) internal { require(newOwner != address(0), "StorageSlotOwnable: new admin is the zero address"); StorageSlot.getAddressSlot(_OWNER_SLOT).value = newOwner; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _getOwner(); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "StorageSlotOwnable: 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(_getOwner(), address(0)); _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), "StorageSlotOwnable: new owner is the zero address"); emit OwnershipTransferred(_getOwner(), newOwner); _setOwner(newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // solhint-disable-line compiler-version import { ERC165 } from "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import { ERC165Checker } from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import { ERC165Storage } from "@openzeppelin/contracts/utils/introspection/ERC165Storage.sol"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; abstract contract OnApprove is ERC165Storage { constructor() { _registerInterface(OnApprove(this).onApprove.selector); } function onApprove( address owner, address spender, uint256 amount, bytes calldata data ) external virtual returns (bool); } abstract contract ERC20OnApprove is ERC20 { function approveAndCall( address spender, uint256 amount, bytes calldata data ) external returns (bool) { require(approve(spender, amount), "ERC20OnApprove: fail to approve"); _callOnApprove(msg.sender, spender, amount, data); return true; } function _callOnApprove( address owner, address spender, uint256 amount, bytes memory data ) internal { bytes4 onApproveSelector = OnApprove(spender).onApprove.selector; require( ERC165Checker.supportsInterface(spender, onApproveSelector), "ERC20OnApprove: spender doesn't support onApprove" ); (bool ok, bytes memory res) = spender.call( abi.encodeWithSelector(onApproveSelector, owner, spender, amount, data) ); // check if low-level call reverted or not require(ok, string(res)); assembly { ok := mload(add(res, 0x20)) } // check if OnApprove.onApprove returns true or false require(ok, "ERC20OnApprove: failed to call onApprove"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Kernel } from "../proxy/Kernel.sol"; abstract contract NonLinearTimeLockSwapperV2_0_4Storage is Kernel { // swap data for each source token, i.e., teamCFX, ecoCFX, backCFX struct SourceTokeData { uint128 rate; // convertion rate from source token to target token uint128 startTime; uint256[] stepEndTimes; uint256[] accStepRatio; } IERC20 public token; // target token, i.e., CFX address public tokenWallet; // address who supply target token /// @dev `migrationStopped` is deprecated. this exists only to remain storage layout. bool public _____DEPRECATED_____migrationStopped; // time lock data for each source token mapping(address => SourceTokeData) public sourceTokenDatas; // source token deposit amounts // sourceToken => beneficiary => deposit amounts mapping(address => mapping(address => uint256)) public depositAmounts; // source token claimed amounts // sourceToken => beneficiary => claimed amounts mapping(address => mapping(address => uint256)) public claimedAmounts; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, type(IERC165).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165(account).supportsInterface.selector, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return false; return success && abi.decode(result, (bool)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC165.sol"; /** * @dev Storage based implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Storage is ERC165 { /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return super.supportsInterface(interfaceId) || _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 defaut 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"); _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"); _approve(_msgSender(), spender, currentAllowance - 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 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"); _balances[sender] = senderBalance - amount; _balances[recipient] += 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 += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal 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"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // 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 "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This contains proxy initialization data */ abstract contract Kernel { bytes32 private constant INITIALIZED = bytes32(uint256(keccak256("Kernel.INITIALIZED")) - 1); // initialized for the version mapping(bytes32 => bool) private _initialized; modifier onlyKernelInitialized() { require(kernelInitialized(), "Kernel: no-init"); _; } modifier onlyKernelInitializedWithVersion(string memory version) { require(kernelInitialized(getVersionHash(version)), "Kernel: no-init"); _; } /// @dev Each implementation contract must implement `implementationVersion` with unique return value for a proxy. function implementationVersion() public view virtual returns (string memory); /// @dev External function to initialize proxy, with specific `_initializeKernel` /// implemented in each implementation contract. function initializeKernel(bytes calldata data) external returns (bool) { require(!kernelInitialized(), "Kernel: already-init"); bytes32 h = getVersionHash(); _initialized[h] = true; _initializeKernel(data); return true; } /// @dev Implementation contract have to override `_initializeKernel` to initialize after proxy upgraded. function _initializeKernel(bytes memory data) internal virtual; function kernelInitialized() public view returns (bool) { bytes32 h = getVersionHash(); return _initialized[h]; } /// @dev Return whether kernel is initialized with version hash. function kernelInitialized(bytes32 h) public view returns (bool) { return _initialized[h]; } /// @dev Return hash of current implementation version. function getVersionHash() public view returns (bytes32) { return getVersionHash(implementationVersion()); } /// @dev Return hash of given implementation version. function getVersionHash(string memory version) public pure returns (bytes32) { bytes32 h = keccak256(abi.encode(INITIALIZED, version)); return h; } }
get claimable tokens at `timestamp`/
function claimableAt( address sourceToken, address beneficiary, uint256 timestamp ) public view returns (uint256) { require(block.timestamp <= timestamp, "invalid-timestamp"); SourceTokeData storage sourceTokenData = sourceTokenDatas[sourceToken]; uint256 totalClaimable = wmul(depositAmounts[sourceToken][beneficiary], sourceTokenData.rate); uint256 claimedAmount = claimedAmounts[sourceToken][beneficiary]; if (timestamp < sourceTokenData.startTime) return 0; if (timestamp >= sourceTokenData.stepEndTimes[sourceTokenData.stepEndTimes.length - 1]) return totalClaimable.sub(claimedAmount); uint256 step = getStepAt(sourceToken, timestamp); uint256 accRatio = sourceTokenData.accStepRatio[step]; uint256 claimableAmount = wmul(totalClaimable, accRatio); return claimableAmount > claimedAmount ? claimableAmount.sub(claimedAmount) : 0; }
299,415
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (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; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/WukongStaking1 (1).sol pragma solidity ^0.8.7; contract WukongStaking is Ownable, ReentrancyGuard { IERC721 public WukongNFT; uint256 public constant SECONDS_IN_DAY = 24 * 60 * 60; uint256 public HARDSTAKE_YIELD_PERDAY = 15; uint256 public PASSIVESTAKE_YIELD_PERDAY = 5; uint256 public stakingStartPoint; address[] public authorisedLog; bool public stakingLaunched; bool public depositPaused; uint256 public totalHardStaker; uint256 public totalStakedNFT; struct HardStaker { uint256 accumulatedAmount; uint256 lastCheckpoint; uint256[] hardStakedWukongId; } struct PassiveStaker { uint256 lastCheckPoint; uint256 accumulatedAmount; } mapping(address => PassiveStaker) private _passiveStakers; mapping(address => HardStaker) private _hardStakers; mapping(uint256 => address) private _ownerOfHardStakingToken; mapping (address => bool) private _authorised; constructor( address _wukong, uint256 _stakingStartPoint ) { WukongNFT = IERC721(_wukong); stakingStartPoint = _stakingStartPoint; } modifier authorised() { require(_authorised[_msgSender()], "The token contract is not authorised"); _; } function getHardStakingTokens(address _owner) public view returns (uint256[] memory) { return _hardStakers[_owner].hardStakedWukongId; } function hardStake(uint256 tokenId) external returns (bool) { address _sender = _msgSender(); require(WukongNFT.ownerOf(tokenId) == _sender, "Not owner"); HardStaker storage user = _hardStakers[_sender]; accumulatePassiveStake(_sender); WukongNFT.safeTransferFrom(_sender, address(this), tokenId); _ownerOfHardStakingToken[tokenId] = _sender; accumulateHardStake(_sender); user.hardStakedWukongId.push(tokenId); if (user.hardStakedWukongId.length == 1) { totalHardStaker += 1; } totalStakedNFT += 1; return true; } function hardMultiStake(uint256[] memory tokenIds) external returns (bool) { require(tokenIds.length > 0, "Token Ids must be an array"); address _sender = _msgSender(); HardStaker storage user = _hardStakers[_sender]; accumulatePassiveStake(_sender); accumulateHardStake(_sender); for(uint256 i = 0;i < tokenIds.length;i++) { require(WukongNFT.ownerOf(tokenIds[i]) == _sender, "Not owner"); WukongNFT.safeTransferFrom(_sender, address(this), tokenIds[i]); _ownerOfHardStakingToken[tokenIds[i]] = _sender; user.hardStakedWukongId.push(tokenIds[i]); } if (user.hardStakedWukongId.length == tokenIds.length) { totalHardStaker += 1; } totalStakedNFT += tokenIds.length; return true; } function unHardStake(uint256 tokenId) external returns (bool) { address sender = _msgSender(); require(_ownerOfHardStakingToken[tokenId] == sender, "Not owner of the staking NFT"); HardStaker storage user = _hardStakers[sender]; accumulatePassiveStake(sender); accumulateHardStake(sender); WukongNFT.safeTransferFrom(address(this), sender, tokenId); _ownerOfHardStakingToken[tokenId] = address(0); user.hardStakedWukongId = _moveTokenInTheList(user.hardStakedWukongId, tokenId); user.hardStakedWukongId.pop(); if (user.hardStakedWukongId.length == 0) { totalHardStaker -= 1; } totalStakedNFT -= 1; return true; } function unHardMultiStake(uint256[] memory tokenIds) external returns (bool) { require(tokenIds.length > 0, "Token Ids must be an array"); address sender = _msgSender(); HardStaker storage user = _hardStakers[sender]; accumulatePassiveStake(sender); accumulateHardStake(sender); for(uint256 i = 0;i < tokenIds.length;i++) { uint256 tokenId = tokenIds[i]; require(_ownerOfHardStakingToken[tokenId] == sender, "Not owner of the staking NFT"); WukongNFT.safeTransferFrom(address(this), sender, tokenId); _ownerOfHardStakingToken[tokenId] = address(0); user.hardStakedWukongId = _moveTokenInTheList(user.hardStakedWukongId, tokenId); user.hardStakedWukongId.pop(); } if (user.hardStakedWukongId.length == 0) { totalHardStaker -= 1; } totalStakedNFT -= tokenIds.length; return true; } function getAccumulatedHardStakeAmount(address staker) external view returns (uint256) { return _hardStakers[staker].accumulatedAmount + getCurrentHardStakeReward(staker); } function getAccumulatedPassiveStakeAmount(address _owner) external view returns (uint256) { return _passiveStakers[_owner].accumulatedAmount + getPassiveStakeReward(_owner); } function accumulatePassiveStake(address _owner) internal { _passiveStakers[_owner].accumulatedAmount += getPassiveStakeReward(_owner); _passiveStakers[_owner].lastCheckPoint = block.timestamp; } function accumulateHardStake(address staker) internal { _hardStakers[staker].accumulatedAmount += getCurrentHardStakeReward(staker); _hardStakers[staker].lastCheckpoint = block.timestamp; } function getCurrentHardStakeReward(address staker) internal view returns (uint256) { HardStaker memory user = _hardStakers[staker]; // return (block.timestamp - user.lastCheckpoint); if (user.lastCheckpoint == 0 || block.timestamp < stakingStartPoint) {return 0;} return (block.timestamp - user.lastCheckpoint) / SECONDS_IN_DAY * user.hardStakedWukongId.length * HARDSTAKE_YIELD_PERDAY; } function getPassiveStakeReward(address _owner) internal view returns (uint256) { uint256 nftAmount = WukongNFT.balanceOf(_owner); uint256 startPoint = stakingStartPoint; if (_passiveStakers[_owner].lastCheckPoint != 0) { startPoint = _passiveStakers[_owner].lastCheckPoint; } return (block.timestamp - startPoint) / SECONDS_IN_DAY * nftAmount * PASSIVESTAKE_YIELD_PERDAY; } /** * @dev Returns token owner address (returns address(0) if token is not inside the gateway) */ function ownerOf(uint256 tokenID) public view returns (address) { return _ownerOfHardStakingToken[tokenID]; } /** * @dev Admin function to authorise the contract address */ function authorise(address toAuth) public onlyOwner { _authorised[toAuth] = true; authorisedLog.push(toAuth); } /** * @dev Function allows admin add unauthorised address. */ function unauthorise(address addressToUnAuth) public onlyOwner { _authorised[addressToUnAuth] = false; } function emergencyWithdraw(uint256[] memory tokenIDs) public onlyOwner { require(tokenIDs.length <= 50, "50 is max per tx"); pauseDeposit(true); for (uint256 i; i < tokenIDs.length; i++) { address receiver = _ownerOfHardStakingToken[tokenIDs[i]]; if (receiver != address(0) && IERC721(WukongNFT).ownerOf(tokenIDs[i]) == address(this)) { IERC721(WukongNFT).transferFrom(address(this), receiver, tokenIDs[i]); // emit WithdrawStuckERC721(receiver, WukongNFT, tokenIDs[i]); } } } function _moveTokenInTheList(uint256[] memory list, uint256 tokenId) internal pure returns (uint256[] memory) { uint256 tokenIndex = 0; uint256 lastTokenIndex = list.length - 1; uint256 length = list.length; for(uint256 i = 0; i < length; i++) { if (list[i] == tokenId) { tokenIndex = i + 1; break; } } require(tokenIndex != 0, "msg.sender is not the owner"); tokenIndex -= 1; if (tokenIndex != lastTokenIndex) { list[tokenIndex] = list[lastTokenIndex]; list[lastTokenIndex] = tokenId; } return list; } /** * @dev Function allows to pause deposits if needed. Withdraw remains active. */ function pauseDeposit(bool _pause) public onlyOwner { depositPaused = _pause; } function launchStaking() public onlyOwner { require(!stakingLaunched, "Staking has been launched already"); stakingLaunched = true; // acceleratedYield = block.timestamp + (SECONDS_IN_DAY * HARDSTAKE_YIELD_PERDAY); } function onERC721Received(address, address, uint256, bytes calldata) external pure returns(bytes4){ return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); } }
return (block.timestamp - user.lastCheckpoint);
function getCurrentHardStakeReward(address staker) internal view returns (uint256) { HardStaker memory user = _hardStakers[staker]; return (block.timestamp - user.lastCheckpoint) / SECONDS_IN_DAY * user.hardStakedWukongId.length * HARDSTAKE_YIELD_PERDAY; }
346,167
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event TransferSell(address indexed from, uint tokens, uint eth); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; owner = newOwner; } // function acceptOwnership() public { // require(msg.sender == newOwner); // OwnershipTransferred(owner, newOwner); // owner = newOwner; // newOwner = address(0); // } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals // Receives ETH and generates tokens // ---------------------------------------------------------------------------- contract MyToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public totalSupply; uint public sellRate; uint public buyRate; uint public startTime; uint public endTime; address[] admins; struct lockPosition{ uint time; uint count; uint releaseRate; uint lockTime; } struct lockPosition1{ uint8 typ; // 1 2 3 4 uint count; uint time1; uint8 releaseRate1; uint time2; uint8 releaseRate2; uint time3; uint8 releaseRate3; uint time4; uint8 releaseRate4; } mapping(address => lockPosition) private lposition; mapping(address => lockPosition1) public lposition1; // locked account dictionary that maps addresses to boolean mapping (address => bool) public lockedAccounts; mapping (address => bool) public isAdmin; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; modifier is_not_locked(address _address) { if (lockedAccounts[_address] == true) revert(); _; } modifier validate_address(address _address) { if (_address == address(0)) revert(); _; } modifier is_admin { if (isAdmin[msg.sender] != true && msg.sender != owner) revert(); _; } modifier validate_position(address _address,uint count) { if(count <= 0) revert(); if(balances[_address] < count) revert(); if(lposition[_address].count > 0 && safeSub(balances[_address],count) < lposition[_address].count && now < lposition[_address].time) revert(); if(lposition1[_address].count > 0 && safeSub(balances[_address],count) < lposition1[_address].count && now < lposition1[_address].time1) revert(); checkPosition1(_address,count); checkPosition(_address,count); _; } function checkPosition(address _address,uint count) private view { if(lposition[_address].releaseRate < 100 && lposition[_address].count > 0){ uint _rate = safeDiv(100,lposition[_address].releaseRate); uint _time = lposition[_address].time; uint _tmpRate = lposition[_address].releaseRate; uint _tmpRateAll = 0; uint _count = 0; for(uint _a=1;_a<=_rate;_a++){ if(now >= _time){ _count = _a; _tmpRateAll = safeAdd(_tmpRateAll,_tmpRate); _time = safeAdd(_time,lposition[_address].lockTime); } } uint _tmp1 = safeSub(balances[_address],count); uint _tmp2 = safeSub(lposition[_address].count,safeDiv(lposition[_address].count*_tmpRateAll,100)); if(_count < _rate && _tmp1 < _tmp2 && now >= lposition[_address].time) revert(); } } function checkPosition1(address _address,uint count) private view { if(lposition1[_address].releaseRate1 < 100 && lposition1[_address].count > 0){ uint _tmpRateAll = 0; if(lposition1[_address].typ == 2 && now < lposition1[_address].time2){ if(now >= lposition1[_address].time1){ _tmpRateAll = lposition1[_address].releaseRate1; } } if(lposition1[_address].typ == 3 && now < lposition1[_address].time3){ if(now >= lposition1[_address].time1){ _tmpRateAll = lposition1[_address].releaseRate1; } if(now >= lposition1[_address].time2){ _tmpRateAll = safeAdd(lposition1[_address].releaseRate2,_tmpRateAll); } } if(lposition1[_address].typ == 4 && now < lposition1[_address].time4){ if(now >= lposition1[_address].time1){ _tmpRateAll = lposition1[_address].releaseRate1; } if(now >= lposition1[_address].time2){ _tmpRateAll = safeAdd(lposition1[_address].releaseRate2,_tmpRateAll); } if(now >= lposition1[_address].time3){ _tmpRateAll = safeAdd(lposition1[_address].releaseRate3,_tmpRateAll); } } uint _tmp1 = safeSub(balances[_address],count); uint _tmp2 = safeSub(lposition1[_address].count,safeDiv(lposition1[_address].count*_tmpRateAll,100)); if(_tmpRateAll > 0){ if(_tmp1 < _tmp2) revert(); } } } event _lockAccount(address _add); event _unlockAccount(address _add); function () public payable{ uint tokens; require(owner != msg.sender); require(now >= startTime && now < endTime); require(buyRate > 0); require(msg.value >= 0.1 ether && msg.value <= 1000 ether); tokens = safeDiv(msg.value,(1 ether * 1 wei / buyRate)); require(balances[owner] >= tokens * 10**uint(decimals)); balances[msg.sender] = safeAdd(balances[msg.sender], tokens * 10**uint(decimals)); balances[owner] = safeSub(balances[owner], tokens * 10**uint(decimals)); Transfer(owner,msg.sender,tokens * 10**uint(decimals)); } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function MyToken(uint _sellRate,uint _buyRate,string _symbo1,string _name,uint _startTime,uint _endTime) public payable { require(_sellRate >0 && _buyRate > 0); require(_startTime < _endTime); symbol = _symbo1; name = _name; decimals = 8; totalSupply = 2000000000 * 10**uint(decimals); balances[owner] = totalSupply; Transfer(address(0), owner, totalSupply); sellRate = _sellRate; buyRate = _buyRate; endTime = _endTime; startTime = _startTime; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public is_not_locked(msg.sender) validate_position(msg.sender,tokens) returns (bool success) { require(to != msg.sender); require(tokens > 0); require(balances[msg.sender] >= tokens); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public is_not_locked(msg.sender) is_not_locked(spender) validate_position(msg.sender,tokens) returns (bool success) { require(spender != msg.sender); require(tokens > 0); require(balances[msg.sender] >= tokens); allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public is_not_locked(msg.sender) is_not_locked(from) validate_position(from,tokens) returns (bool success) { require(transferFromCheck(from,to,tokens)); return true; } function transferFromCheck(address from,address to,uint tokens) private returns (bool success) { require(tokens > 0); require(from != msg.sender && msg.sender != to && from != to); require(balances[from] >= tokens && allowed[from][msg.sender] >= tokens); balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Sall a token from a contract // ------------------------------------------------------------------------ function sellCoin(address seller, uint amount) public onlyOwner is_not_locked(seller) validate_position(seller,amount* 10**uint(decimals)) { require(balances[seller] >= safeMul(amount,10**uint(decimals))); require(sellRate > 0); require(seller != msg.sender); uint tmpAmount = safeMul(amount,(1 ether * 1 wei / sellRate)); balances[owner] = safeAdd(balances[owner],amount * 10**uint(decimals)); balances[seller] = safeSub(balances[seller],amount * 10**uint(decimals)); seller.transfer(tmpAmount); TransferSell(seller, amount * 10**uint(decimals), tmpAmount); } // set rate function setConfig(uint _buyRate,uint _sellRate,string _symbol,string _name,uint _startTime,uint _endTime) public onlyOwner { require((_buyRate == 0 && _sellRate == 0) || (_buyRate < _sellRate && _buyRate > 0 && _sellRate > 0) || (_buyRate < sellRate && _buyRate > 0 && _sellRate == 0) || (buyRate < _sellRate && _buyRate == 0 && _sellRate > 0)); if(_buyRate > 0){ buyRate = _buyRate; } if(sellRate > 0){ sellRate = _sellRate; } if(_startTime > 0){ startTime = _startTime; } if(_endTime > 0){ endTime = _endTime; } symbol = _symbol; name = _name; } // lockAccount function lockStatus(address _add,bool _success) public validate_address(_add) is_admin { lockedAccounts[_add] = _success; _lockAccount(_add); } // setIsAdmin function setIsAdmin(address _add,bool _success) public validate_address(_add) onlyOwner { isAdmin[_add] = _success; if(_success == true){ admins[admins.length++] = _add; }else{ for (uint256 i;i < admins.length;i++){ if(admins[i] == _add){ delete admins[i]; } } } } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } //set lock position function setLockPostion(address _add,uint _count,uint _time,uint _releaseRate,uint _lockTime) public is_not_locked(_add) onlyOwner { require(lposition1[_add].count == 0); require(balances[_add] >= safeMul(_count,10**uint(decimals))); require(_time > now); require(_count > 0 && _lockTime > 0); require(_releaseRate > 0 && _releaseRate < 100); require(_releaseRate == 2 || _releaseRate == 4 || _releaseRate == 5 || _releaseRate == 10 || _releaseRate == 20 || _releaseRate == 25 || _releaseRate == 50); lposition[_add].time = _time; lposition[_add].count = _count * 10**uint(decimals); lposition[_add].releaseRate = _releaseRate; lposition[_add].lockTime = _lockTime; } //get lockPosition info function getLockPosition(address _add) public view returns(uint time,uint count,uint rate,uint scount,uint _lockTime) { return (lposition[_add].time,lposition[_add].count,lposition[_add].releaseRate,positionScount(_add),lposition[_add].lockTime); } function positionScount(address _add) private view returns (uint count){ uint _rate = safeDiv(100,lposition[_add].releaseRate); uint _time = lposition[_add].time; uint _tmpRate = lposition[_add].releaseRate; uint _tmpRateAll = 0; for(uint _a=1;_a<=_rate;_a++){ if(now >= _time){ _tmpRateAll = safeAdd(_tmpRateAll,_tmpRate); _time = safeAdd(_time,lposition[_add].lockTime); } } return (lposition[_add].count - safeDiv(lposition[_add].count*_tmpRateAll,100)); } //set lock position function setLockPostion1(address _add,uint _count,uint8 _typ,uint _time1,uint8 _releaseRate1,uint _time2,uint8 _releaseRate2,uint _time3,uint8 _releaseRate3,uint _time4,uint8 _releaseRate4) public is_not_locked(_add) onlyOwner { require(_count > 0); require(_time1 > now); require(_releaseRate1 > 0); require(_typ >= 1 && _typ <= 4); require(balances[_add] >= safeMul(_count,10**uint(decimals))); require(safeAdd(safeAdd(_releaseRate1,_releaseRate2),safeAdd(_releaseRate3,_releaseRate4)) == 100); require(lposition[_add].count == 0); if(_typ == 1){ require(_time2 == 0 && _releaseRate2 == 0 && _time3 == 0 && _releaseRate3 == 0 && _releaseRate4 == 0 && _time4 == 0); } if(_typ == 2){ require(_time2 > _time1 && _releaseRate2 > 0 && _time3 == 0 && _releaseRate3 == 0 && _releaseRate4 == 0 && _time4 == 0); } if(_typ == 3){ require(_time2 > _time1 && _releaseRate2 > 0 && _time3 > _time2 && _releaseRate3 > 0 && _releaseRate4 == 0 && _time4 == 0); } if(_typ == 4){ require(_time2 > _time1 && _releaseRate2 > 0 && _releaseRate3 > 0 && _time3 > _time2 && _time4 > _time3 && _releaseRate4 > 0); } lockPostion1Add(_typ,_add,_count,_time1,_releaseRate1,_time2,_releaseRate2,_time3,_releaseRate3,_time4,_releaseRate4); } function lockPostion1Add(uint8 _typ,address _add,uint _count,uint _time1,uint8 _releaseRate1,uint _time2,uint8 _releaseRate2,uint _time3,uint8 _releaseRate3,uint _time4,uint8 _releaseRate4) private { lposition1[_add].typ = _typ; lposition1[_add].count = _count * 10**uint(decimals); lposition1[_add].time1 = _time1; lposition1[_add].releaseRate1 = _releaseRate1; lposition1[_add].time2 = _time2; lposition1[_add].releaseRate2 = _releaseRate2; lposition1[_add].time3 = _time3; lposition1[_add].releaseRate3 = _releaseRate3; lposition1[_add].time4 = _time4; lposition1[_add].releaseRate4 = _releaseRate4; } //get lockPosition1 info function getLockPosition1(address _add) public view returns(uint count,uint Scount,uint8 _typ,uint8 _rate1,uint8 _rate2,uint8 _rate3,uint8 _rate4) { return (lposition1[_add].count,positionScount1(_add),lposition1[_add].typ,lposition1[_add].releaseRate1,lposition1[_add].releaseRate2,lposition1[_add].releaseRate3,lposition1[_add].releaseRate4); } function positionScount1(address _address) private view returns (uint count){ uint _tmpRateAll = 0; if(lposition1[_address].typ == 2 && now < lposition1[_address].time2){ if(now >= lposition1[_address].time1){ _tmpRateAll = lposition1[_address].releaseRate1; } } if(lposition1[_address].typ == 3 && now < lposition1[_address].time3){ if(now >= lposition1[_address].time1){ _tmpRateAll = lposition1[_address].releaseRate1; } if(now >= lposition1[_address].time2){ _tmpRateAll = safeAdd(lposition1[_address].releaseRate2,_tmpRateAll); } } if(lposition1[_address].typ == 4 && now < lposition1[_address].time4){ if(now >= lposition1[_address].time1){ _tmpRateAll = lposition1[_address].releaseRate1; } if(now >= lposition1[_address].time2){ _tmpRateAll = safeAdd(lposition1[_address].releaseRate2,_tmpRateAll); } if(now >= lposition1[_address].time3){ _tmpRateAll = safeAdd(lposition1[_address].releaseRate3,_tmpRateAll); } } if((lposition1[_address].typ == 1 && now >= lposition1[_address].time1) || (lposition1[_address].typ == 2 && now >= lposition1[_address].time2) || (lposition1[_address].typ == 3 && now >= lposition1[_address].time3) || (lposition1[_address].typ == 4 && now >= lposition1[_address].time4)){ return 0; } if(_tmpRateAll > 0){ return (safeSub(lposition1[_address].count,safeDiv(lposition1[_address].count*_tmpRateAll,100))); }else{ return lposition1[_address].count; } } // batchTransfer function batchTransfer(address[] _adds,uint256 _tokens) public is_admin returns(bool success) { require(balances[msg.sender] >= safeMul(_adds.length,_tokens)); require(lposition[msg.sender].count == 0 && lposition1[msg.sender].count == 0); for (uint256 i = 0; i < _adds.length; i++) { uint256 _tmpTokens = _tokens; address _tmpAdds = _adds[i]; balances[msg.sender] = safeSub(balances[msg.sender], _tmpTokens); balances[_tmpAdds] = safeAdd(balances[_tmpAdds], _tmpTokens); Transfer(msg.sender,_tmpAdds,_tmpTokens); } return true; } }
get lockPosition1 info
function getLockPosition1(address _add) public view returns(uint count,uint Scount,uint8 _typ,uint8 _rate1,uint8 _rate2,uint8 _rate3,uint8 _rate4) { return (lposition1[_add].count,positionScount1(_add),lposition1[_add].typ,lposition1[_add].releaseRate1,lposition1[_add].releaseRate2,lposition1[_add].releaseRate3,lposition1[_add].releaseRate4); }
6,345,927