file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
./full_match/5/0x7d8C4cF34EAE2e7895D5988Df366DF7644053575/sources/contracts/Squad.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 { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function ceil(uint256 a, uint256 m) internal pure returns (uint256) { uint256 c = add(a, m); uint256 d = sub(c, 1); return mul(div(d, m), m); } }
1,877,588
[ 1, 24114, 1879, 348, 7953, 560, 1807, 30828, 5295, 598, 3096, 9391, 4271, 18, 27443, 5295, 316, 348, 7953, 560, 2193, 603, 9391, 18, 1220, 848, 17997, 563, 316, 22398, 16, 2724, 5402, 81, 414, 11234, 6750, 716, 392, 9391, 14183, 392, 555, 16, 1492, 353, 326, 4529, 6885, 316, 3551, 1801, 5402, 11987, 8191, 18, 1375, 9890, 10477, 68, 3127, 3485, 333, 509, 89, 608, 635, 15226, 310, 326, 2492, 1347, 392, 1674, 9391, 87, 18, 11637, 333, 5313, 3560, 434, 326, 22893, 5295, 19229, 4174, 392, 7278, 667, 434, 22398, 16, 1427, 518, 1807, 14553, 358, 999, 518, 3712, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 10477, 288, 203, 565, 445, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 3639, 2583, 12, 71, 1545, 279, 16, 315, 9890, 10477, 30, 2719, 9391, 8863, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 720, 12, 69, 16, 324, 16, 315, 9890, 10477, 30, 720, 25693, 9391, 8863, 203, 565, 289, 203, 203, 565, 445, 720, 12, 203, 3639, 2254, 5034, 279, 16, 203, 3639, 2254, 5034, 324, 16, 203, 3639, 533, 3778, 9324, 203, 565, 262, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 70, 1648, 279, 16, 9324, 1769, 203, 3639, 2254, 5034, 276, 273, 279, 300, 324, 31, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 3639, 2583, 12, 71, 342, 279, 422, 324, 16, 315, 9890, 10477, 30, 23066, 9391, 8863, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2 ]
pragma solidity ^0.4.24; import "./Exponential.sol"; import "./ErrorReporter.sol"; import "./CarefulMath.sol"; import "./InterestRateModel.sol"; /** * @title The Justpound Stable Coin Interest Rate Model * @author Justpound * @notice See Section 2.4 of the Justpound Whitepaper */ contract StableCoinInterestRateModel is Exponential { uint constant oneMinusSpreadBasisPoints = 8500; uint constant blocksPerYear = 2102400; enum IRError { NO_ERROR, FAILED_TO_ADD_CASH_PLUS_BORROWS, FAILED_TO_GET_EXP, FAILED_TO_MUL_PRODUCT_TIMES_BORROW_RATE } /* * @dev Calculates the utilization rate (borrows / (cash + borrows)) as an Exp */ function getUtilizationRate(uint cash, uint borrows) pure internal returns (IRError, Exp memory) { if (borrows == 0) { // Utilization rate is zero when there's no borrows return (IRError.NO_ERROR, Exp({mantissa: 0})); } (Error err0, uint cashPlusBorrows) = add(cash, borrows); if (err0 != Error.NO_ERROR) { return (IRError.FAILED_TO_ADD_CASH_PLUS_BORROWS, Exp({mantissa: 0})); } (Error err1, Exp memory utilizationRate) = getExp(borrows, cashPlusBorrows); if (err1 != Error.NO_ERROR) { return (IRError.FAILED_TO_GET_EXP, Exp({mantissa: 0})); } return (IRError.NO_ERROR, utilizationRate); } /* * @dev Calculates the utilization and borrow rates for use by get{Supply,Borrow}Rate functions */ function getUtilizationAndAnnualBorrowRate(uint cash, uint borrows) pure internal returns (IRError, Exp memory, Exp memory) { (IRError err0, Exp memory utilizationRate) = getUtilizationRate(cash, borrows); if (err0 != IRError.NO_ERROR) { return (err0, Exp({mantissa: 0}), Exp({mantissa: 0})); } // utilizationRate * 0.3 (30%), which is `rate * 3 / 10` (Error err1, Exp memory utilizationRateMuled) = mulScalar(utilizationRate, 3); // `mulScalar` only overflows when the product is >= 2^256. // utilizationRate is a real number on the interval [0,1], which means that // utilizationRate.mantissa is in the interval [0e18,1e18], which means that three times // that is in the interval [0e18,3e18]. That interval has no intersection with 2^256, and therefore // this can never overflow. As such, we assert. assert(err1 == Error.NO_ERROR); (Error err2, Exp memory utilizationRateScaled) = divScalar(utilizationRateMuled, 10); // 10 is a constant, and therefore cannot be zero, which is the only error case of divScalar. assert(err2 == Error.NO_ERROR); // Add the 10% for (10% + 30% * Ua) (Error err3, Exp memory annualBorrowRate) = addExp(utilizationRateScaled, Exp({mantissa: mantissaOneTenth})); // `addExp` only fails when the addition of mantissas overflow. // As per above, utilizationRateMuled is capped at 3e18 and when divided by 10, // utilizationRateScaled is capped at 3e17. mantissaOneTenth = 1e17, and thus the addition // is capped at 4e17, which is less than 2^256. assert(err3 == Error.NO_ERROR); return (IRError.NO_ERROR, utilizationRate, annualBorrowRate); } /** * @notice Gets the current supply interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param _asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the supply interest rate per block scaled by 10e18 */ function getSupplyRate(address _asset, uint cash, uint borrows) public view returns (uint, uint) { _asset; // pragma ignore unused argument (IRError err0, Exp memory utilizationRate0, Exp memory annualBorrowRate) = getUtilizationAndAnnualBorrowRate(cash, borrows); if (err0 != IRError.NO_ERROR) { return (uint(err0), 0); } // We're going to multiply the utilization rate by the spread's numerator (Error err1, Exp memory utilizationRate1) = mulScalar(utilizationRate0, oneMinusSpreadBasisPoints); // mulScalar only overflows when product is greater than or equal to 2^256. // utilization rate's mantissa is a number between [0e18,1e18]. That means that // utilizationRate1 is a value between [0e18,8.5e21]. This is strictly less than 2^256. assert(err1 == Error.NO_ERROR); // Next multiply this product times the borrow rate (Error err2, Exp memory supplyRate0) = mulExp(utilizationRate1, annualBorrowRate); // If the product of the mantissas for mulExp are both less than 2^256, // then this operation will never fail. TODO: Verify. // We know that borrow rate is in the interval [0, 4e17] from above. // We know that utilizationRate1 is in the interval [0, 8.5e21] from directly above. // As such, the multiplication is in the interval of [0, 3.4e39]. This is strictly // less than 2^256 (which is about 10e77). assert(err2 == Error.NO_ERROR); // And then divide down by the spread's denominator (basis points divisor) // as well as by blocks per year. (Error err3, Exp memory standardSupplyRate) = divScalar(supplyRate0, 10000 * blocksPerYear); // basis points * blocks per year // divScalar only fails when divisor is zero. This is clearly not the case. assert(err3 == Error.NO_ERROR); // Note: StableCoins interest rate should be much less than the standard rate for other tokens (Error err4, uint finalSupplyRate) = div(standardSupplyRate.mantissa, 2); assert(err4 == Error.NO_ERROR); return (uint(IRError.NO_ERROR), finalSupplyRate); } /** * @notice Gets the current borrow interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param _asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the borrow interest rate per block scaled by 10e18 */ function getBorrowRate(address _asset, uint cash, uint borrows) public view returns (uint, uint) { _asset; // pragma ignore unused argument (IRError err0, Exp memory _utilizationRate, Exp memory annualBorrowRate) = getUtilizationAndAnnualBorrowRate(cash, borrows); if (err0 != IRError.NO_ERROR) { return (uint(err0), 0); } // And then divide down by blocks per year. (Error err1, Exp memory standardBorrowRate) = divScalar(annualBorrowRate, blocksPerYear); // basis points * blocks per year // divScalar only fails when divisor is zero. This is clearly not the case. assert(err1 == Error.NO_ERROR); _utilizationRate; // pragma ignore unused variable // Note: StableCoins interest rate should be much less than the standard rate for other tokens (Error err2, uint finalBorrowRate) = div(standardBorrowRate.mantissa, 2); assert(err2 == Error.NO_ERROR); return (uint(IRError.NO_ERROR), finalBorrowRate); } }
Note: StableCoins interest rate should be much less than the standard rate for other tokens
(Error err4, uint finalSupplyRate) = div(standardSupplyRate.mantissa, 2);
918,431
[ 1, 8067, 30, 934, 429, 39, 9896, 16513, 4993, 1410, 506, 9816, 5242, 2353, 326, 4529, 4993, 364, 1308, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 261, 668, 393, 24, 16, 2254, 727, 3088, 1283, 4727, 13, 273, 3739, 12, 10005, 3088, 1283, 4727, 18, 81, 970, 21269, 16, 576, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xb5410de6FaeFCfA9B9162061C757fe08C44a0EB0/sources/Yuri.sol
Whatever balance left divide among 2 wallets 70/30
uint256 contractBal = address(this).balance;
9,203,855
[ 1, 2888, 14299, 11013, 2002, 12326, 17200, 576, 17662, 2413, 16647, 19, 5082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 6835, 38, 287, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x2d4b49d0C6d54AEB10fe5A503c55DbD9e8a7A8d7/sources/HOToken.sol
those methods are called by the legacy contract and they must ensure msg.sender to be the contract address
contract UpgradedStandardToken is StandardToken{ function transferByLegacy(address from, address to, uint value) public returns (bool); function transferFromByLegacy(address sender, address from, address spender, uint value) public returns (bool); function approveByLegacy(address from, address spender, uint value) public returns (bool); }
3,561,437
[ 1, 451, 2584, 2590, 854, 2566, 635, 326, 8866, 6835, 471, 2898, 1297, 3387, 1234, 18, 15330, 358, 506, 326, 6835, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1948, 19305, 8336, 1345, 353, 8263, 1345, 95, 203, 565, 445, 7412, 858, 12235, 12, 2867, 628, 16, 1758, 358, 16, 2254, 460, 13, 1071, 225, 1135, 261, 6430, 1769, 203, 565, 445, 7412, 1265, 858, 12235, 12, 2867, 5793, 16, 1758, 628, 16, 1758, 17571, 264, 16, 2254, 460, 13, 1071, 225, 1135, 261, 6430, 1769, 203, 565, 445, 6617, 537, 858, 12235, 12, 2867, 628, 16, 1758, 17571, 264, 16, 2254, 460, 13, 1071, 1135, 261, 6430, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.12; interface IWSFactory { 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; } // 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'); } } interface IWSPair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); 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 isLocked() external view returns (uint); function initialize(address _factory, address _token0, address _token1) external returns(bool); } // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } library WSLibrary { 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, 'WSLibrary: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'WSLibrary: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(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'c3269f83aca65422b68bd8f11bf7cda4d9cebe3d8813a38a34f97b042b8d5574' // init code hash )))); } // 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,) = IWSPair(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, 'WSLibrary: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'WSLibrary: 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, 'WSLibrary: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'WSLibrary: 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, 'WSLibrary: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'WSLibrary: 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, 'WSLibrary: 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, 'WSLibrary: 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); } } } interface IWSRouter { 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 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; function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view 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); } interface IWSERC20 { 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; } interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } interface IWSImplementation { function getImplementationType() external pure returns(uint256); } contract WSRouter is IWSRouter, IWSImplementation { using SafeMath for uint; bool private initialized; address public override factory; address public override WETH; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'WSRouter: EXPIRED'); _; } function initialize(address _factory, address _WETH) public returns(bool) { require(initialized == false, "WSRouter: Alredy initialized."); factory = _factory; WETH = _WETH; initialized = true; return true; } receive() external payable { } // **** 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 (IWSFactory(factory).getPair(tokenA, tokenB) == address(0)) { IWSFactory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = WSLibrary.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = WSLibrary.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'WSRouter: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = WSLibrary.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'WSRouter: 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 = WSLibrary.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IWSPair(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 = WSLibrary.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IWSPair(pair).mint(to); // 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 = WSLibrary.pairFor(factory, tokenA, tokenB); IWSERC20(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = IWSPair(pair).burn(to); (address token0,) = WSLibrary.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'WSRouter: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'WSRouter: 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 = WSLibrary.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; IWSERC20(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 = WSLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IWSERC20(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 = WSLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IWSERC20(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,) = WSLibrary.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 ? WSLibrary.pairFor(factory, output, path[i + 2]) : _to; IWSPair(WSLibrary.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 = WSLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'WSRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, WSLibrary.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 = WSLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'WSRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, WSLibrary.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, 'WSRouter: INVALID_PATH'); amounts = WSLibrary.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'WSRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(WSLibrary.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, 'WSRouter: INVALID_PATH'); amounts = WSLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'WSRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, WSLibrary.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, 'WSRouter: INVALID_PATH'); amounts = WSLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'WSRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, WSLibrary.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, 'WSRouter: INVALID_PATH'); amounts = WSLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'WSRouter: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(WSLibrary.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,) = WSLibrary.sortTokens(input, output); IWSPair pair = IWSPair(WSLibrary.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 = WSLibrary.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? WSLibrary.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, WSLibrary.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, 'WSRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { require(path[0] == WETH, 'WSRouter: INVALID_PATH'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(WSLibrary.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, 'WSRouter: 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, 'WSRouter: INVALID_PATH'); TransferHelper.safeTransferFrom( path[0], msg.sender, WSLibrary.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'WSRouter: 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 WSLibrary.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return WSLibrary.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return WSLibrary.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { return WSLibrary.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { return WSLibrary.getAmountsIn(factory, amountOut, path); } function getImplementationType() external pure override returns(uint256) { /// 3 is a router type return 3; } }
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, 'WSLibrary: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'WSLibrary: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; }
6,789,404
[ 1, 10822, 392, 810, 3844, 434, 392, 3310, 471, 3082, 400, 264, 3324, 16, 1135, 326, 4207, 876, 3844, 434, 326, 1308, 3310, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 24418, 1182, 12, 11890, 3844, 382, 16, 2254, 20501, 382, 16, 2254, 20501, 1182, 13, 2713, 16618, 1135, 261, 11890, 3844, 1182, 13, 288, 203, 3639, 2583, 12, 8949, 382, 405, 374, 16, 296, 2651, 9313, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 15934, 67, 2192, 51, 5321, 8284, 203, 3639, 2583, 12, 455, 6527, 382, 405, 374, 597, 20501, 1182, 405, 374, 16, 296, 2651, 9313, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 2053, 53, 3060, 4107, 8284, 203, 3639, 2254, 3844, 382, 1190, 14667, 273, 3844, 382, 18, 16411, 12, 2733, 27, 1769, 203, 3639, 2254, 16730, 273, 3844, 382, 1190, 14667, 18, 16411, 12, 455, 6527, 1182, 1769, 203, 3639, 2254, 15030, 273, 20501, 382, 18, 16411, 12, 18088, 2934, 1289, 12, 8949, 382, 1190, 14667, 1769, 203, 3639, 3844, 1182, 273, 16730, 342, 15030, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; contract Spineth { /// The states the game will transition through enum State { WaitingForPlayers, // the game has been created by a player and is waiting for an opponent WaitingForReveal, // someone has joined and also placed a bet, we are now waiting for the creator to their reveal bet Complete // the outcome of the game is determined and players can withdraw their earnings } /// All possible event types enum Event { Create, Cancel, Join, Reveal, Expire, Complete, Withdraw, StartReveal } // The game state associated with a single game between two players struct GameInstance { // Address for players of this game // player1 is always the creator address player1; address player2; // How much is being bet this game uint betAmountInWei; // The wheelBet for each player // For player1, the bet starts as a hash and is only changed to the real bet once revealed uint wheelBetPlayer1; uint wheelBetPlayer2; // The final wheel position after game is complete uint wheelResult; // The time by which the creator of the game must reveal his bet after an opponent joins // If the creator does not reveal in time, the opponent can expire the game, causing them to win the maximal amount of their bet uint expireTime; // Current state of the game State state; // Tracks whether each player has withdrawn their earnings yet bool withdrawnPlayer1; bool withdrawnPlayer2; } /// How many places there are on the wheel that a bet can be placed uint public constant WHEEL_SIZE = 19; /// What percentage of your opponent's bet a player wins for each place on /// the wheel they are closer to the result than their opponent /// i.e. If player1 distance from result = 4 and player2 distance from result = 6 /// then player1 earns (6-4) x WIN_PERCENT_PER_DISTANCE = 20% of player2's bet uint public constant WIN_PERCENT_PER_DISTANCE = 10; /// The percentage charged on earnings that are won uint public constant FEE_PERCENT = 2; /// The minimum amount that can be bet uint public minBetWei = 1 finney; /// The maximum amount that can be bet uint public maxBetWei = 10 ether; /// The amount of time creators have to reavel their bets before /// the game can be expired by an opponent uint public maxRevealSeconds = 3600 * 24; /// The account that will receive fees and can configure min/max bet options address public authority; /// Counters that tracks how many games have been created by each player /// This is used to generate a unique game id per player mapping(address => uint) private counterContext; /// Context for all created games mapping(uint => GameInstance) public gameContext; /// List of all currently open gameids uint[] public openGames; /// Indexes specific to each player mapping(address => uint[]) public playerActiveGames; mapping(address => uint[]) public playerCompleteGames; /// Event fired when a game's state changes event GameEvent(uint indexed gameId, address indexed player, Event indexed eventType); /// Create the contract and verify constant configurations make sense function Spineth() public { // Make sure that the maximum possible win distance (WHEEL_SIZE / 2) // multiplied by the WIN_PERCENT_PER_DISTANCE is less than 100% // If it's not, then a maximally won bet can't be paid out require((WHEEL_SIZE / 2) * WIN_PERCENT_PER_DISTANCE < 100); authority = msg.sender; } // Change authority // Can only be called by authority function changeAuthority(address newAuthority) public { require(msg.sender == authority); authority = newAuthority; } // Change min/max bet amounts // Can only be called by authority function changeBetLimits(uint minBet, uint maxBet) public { require(msg.sender == authority); require(maxBet >= minBet); minBetWei = minBet; maxBetWei = maxBet; } // Internal helper function to add elements to an array function arrayAdd(uint[] storage array, uint element) private { array.push(element); } // Internal helper function to remove element from an array function arrayRemove(uint[] storage array, uint element) private { for(uint i = 0; i < array.length; ++i) { if(array[i] == element) { array[i] = array[array.length - 1]; delete array[array.length - 1]; --array.length; break; } } } /// Get next game id to be associated with a player address function getNextGameId(address player) public view returns (uint) { uint counter = counterContext[player]; // Addresses are 160 bits so we can safely shift them up by (256 - 160 = 96 bits) // to make room for the counter in the bottom 96 bits // This means a single player cannot theoretically create more than 2^96 games // which should more than enough for the lifetime of any player. uint result = (uint(player) << 96) + counter; // Check that we didn't overflow the counter (this will never happen) require((result >> 96) == uint(player)); return result; } /// Used to calculate the bet hash given a wheel bet and a player secret. /// Used by a game creator to calculate their bet bash off chain first. /// When bet is revealed, contract will use this function to verify the revealed bet is valid function createWheelBetHash(uint gameId, uint wheelBet, uint playerSecret) public pure returns (uint) { require(wheelBet < WHEEL_SIZE); return uint(keccak256(gameId, wheelBet, playerSecret)); } /// Create and initialize a game instance with the sent bet amount. /// The creator will automatically become a participant of the game. /// gameId must be the return value of getNextGameId(...) for the sender /// wheelPositionHash should be calculated using createWheelBetHash(...) function createGame(uint gameId, uint wheelPositionHash) public payable { // Make sure the player passed the correct value for the game id require(getNextGameId(msg.sender) == gameId); // Get the game instance and ensure that it doesn't already exist GameInstance storage game = gameContext[gameId]; require(game.betAmountInWei == 0); // Must provide non-zero bet require(msg.value > 0); // Restrict betting amount // NOTE: Game creation can be disabled by setting min/max bet to 0 require(msg.value >= minBetWei && msg.value <= maxBetWei); // Increment the create game counter for this player counterContext[msg.sender] = counterContext[msg.sender] + 1; // Update game state // The creator becomes player1 game.state = State.WaitingForPlayers; game.betAmountInWei = msg.value; game.player1 = msg.sender; game.wheelBetPlayer1 = wheelPositionHash; // This game is now open to others and active for the player arrayAdd(openGames, gameId); arrayAdd(playerActiveGames[msg.sender], gameId); // Fire event for the creation of this game GameEvent(gameId, msg.sender, Event.Create); } /// Cancel a game that was created but never had another player join /// A creator can use this function if they have been waiting too long for another /// player and want to get their bet funds back. NOTE. Once someone joins /// the game can no longer be cancelled. function cancelGame(uint gameId) public { // Get the game instance and check that it exists GameInstance storage game = gameContext[gameId]; require(game.betAmountInWei > 0); // Can only cancel if we are still waiting for other participants require(game.state == State.WaitingForPlayers); // Is the sender the creator? require(game.player1 == msg.sender); // Update game state // Mark earnings as already withdrawn since we are returning the bet amount game.state = State.Complete; game.withdrawnPlayer1 = true; // This game is no longer open and no longer active for the player arrayRemove(openGames, gameId); arrayRemove(playerActiveGames[msg.sender], gameId); // Fire event for player canceling this game GameEvent(gameId, msg.sender, Event.Cancel); // Transfer the player's bet amount back to them msg.sender.transfer(game.betAmountInWei); } /// Join an open game instance /// Sender must provide an amount of wei equal to betAmountInWei /// After the second player has joined, the creator will have maxRevealSeconds to reveal their bet function joinGame(uint gameId, uint wheelBet) public payable { // Get the game instance and check that it exists GameInstance storage game = gameContext[gameId]; require(game.betAmountInWei > 0); // Only allowed to participate while we are waiting for players require(game.state == State.WaitingForPlayers); // Can't join a game that you created require(game.player1 != msg.sender); // Is there space available? require(game.player2 == 0); // Must pay the amount of the bet to play require(msg.value == game.betAmountInWei); // Make sure the wheelBet makes sense require(wheelBet < WHEEL_SIZE); // Update game state // The sender becomes player2 game.state = State.WaitingForReveal; game.player2 = msg.sender; game.wheelBetPlayer2 = wheelBet; game.expireTime = now + maxRevealSeconds; // After expireTime the game can be expired // This game is no longer open, and is now active for the joiner arrayRemove(openGames, gameId); arrayAdd(playerActiveGames[msg.sender], gameId); // Fire event for player joining this game GameEvent(gameId, msg.sender, Event.Join); // Fire event for creator, letting them know they need to reveal their bet now GameEvent(gameId, game.player1, Event.StartReveal); } /// This can be called by the joining player to force the game to end once the expire /// time has been reached. This is a safety measure to ensure the game can be completed /// in case where the creator decides to not to reveal their bet. In this case, the creator /// will lose the maximal amount of their bet function expireGame(uint gameId) public { // Get the game instance and check that it exists GameInstance storage game = gameContext[gameId]; require(game.betAmountInWei > 0); // Only expire from the WaitingForReveal state require(game.state == State.WaitingForReveal); // Has enough time passed to perform this action? require(now > game.expireTime); // Can only expire the game if you are the second player require(msg.sender == game.player2); // Player1 (creator) did not reveal bet in time // Complete the game in favor of player2 game.wheelResult = game.wheelBetPlayer2; game.wheelBetPlayer1 = (game.wheelBetPlayer2 + (WHEEL_SIZE / 2)) % WHEEL_SIZE; // This game is complete, the withdrawEarnings flow can now be invoked game.state = State.Complete; // Fire an event for the player forcing this game to end GameEvent(gameId, game.player1, Event.Expire); GameEvent(gameId, game.player2, Event.Expire); } /// Once a player has joined the game, the creator must reveal their bet /// by providing the same playerSecret that was passed to createGame(...) function revealBet(uint gameId, uint playerSecret) public { // Get the game instance and check that it exists GameInstance storage game = gameContext[gameId]; require(game.betAmountInWei > 0); // We can only reveal bets during the revealing bets state require(game.state == State.WaitingForReveal); // Only the creator does this require(game.player1 == msg.sender); uint i; // Loop counter used below // Find the wheelBet the player made by enumerating the hash // possibilities. It is done this way so the player only has to // remember their secret in order to revel the bet for(i = 0; i < WHEEL_SIZE; ++i) { // Find the bet that was provided in createGame(...) if(createWheelBetHash(gameId, i, playerSecret) == game.wheelBetPlayer1) { // Update the bet to the revealed value game.wheelBetPlayer1 = i; break; } } // Make sure we successfully revealed the bet, otherwise // the playerSecret was invalid require(i < WHEEL_SIZE); // Fire an event for the revealing of the bet GameEvent(gameId, msg.sender, Event.Reveal); // Use the revealed bets to calculate the wheelResult // NOTE: Neither player knew the unrevealed state of both bets when making their // bet, so the combination can be used to generate a random number neither player could anticipate. // This algorithm was tested for good outcome distribution for arbitrary hash values uint256 hashResult = uint256(keccak256(gameId, now, game.wheelBetPlayer1, game.wheelBetPlayer2)); uint32 randomSeed = uint32(hashResult >> 0) ^ uint32(hashResult >> 32) ^ uint32(hashResult >> 64) ^ uint32(hashResult >> 96) ^ uint32(hashResult >> 128) ^ uint32(hashResult >> 160) ^ uint32(hashResult >> 192) ^ uint32(hashResult >> 224); uint32 randomNumber = randomSeed; randomNumber ^= (randomNumber >> 11); randomNumber ^= (randomNumber << 7) & 0x9D2C5680; randomNumber ^= (randomNumber << 15) & 0xEFC60000; randomNumber ^= (randomNumber >> 18); // Update game state game.wheelResult = randomNumber % WHEEL_SIZE; game.state = State.Complete; // Fire an event for the completion of the game GameEvent(gameId, game.player1, Event.Complete); GameEvent(gameId, game.player2, Event.Complete); } /// A utility function to get the minimum distance between two selections /// on a wheel of WHEEL_SIZE wrapping around at 0 function getWheelDistance(uint value1, uint value2) private pure returns (uint) { // Make sure the values are within range require(value1 < WHEEL_SIZE && value2 < WHEEL_SIZE); // Calculate the distance of value1 with respect to value2 uint dist1 = (WHEEL_SIZE + value1 - value2) % WHEEL_SIZE; // Calculate the distance going the other way around the wheel uint dist2 = WHEEL_SIZE - dist1; // Whichever distance is shorter is the wheel distance return (dist1 < dist2) ? dist1 : dist2; } /// Once the game is complete, use this function to get the results of /// the game. Returns: /// - the amount of wei charged for the fee /// - the amount of wei to be paid out to player1 /// - the amount of wei to be paid out to player2 /// The sum of all the return values is exactly equal to the contributions /// of both player bets. i.e. /// feeWei + weiPlayer1 + weiPlayer2 = 2 * betAmountInWei function calculateEarnings(uint gameId) public view returns (uint feeWei, uint weiPlayer1, uint weiPlayer2) { // Get the game instance and check that it exists GameInstance storage game = gameContext[gameId]; require(game.betAmountInWei > 0); // It doesn't make sense to call this function when the game isn't complete require(game.state == State.Complete); uint distancePlayer1 = getWheelDistance(game.wheelBetPlayer1, game.wheelResult); uint distancePlayer2 = getWheelDistance(game.wheelBetPlayer2, game.wheelResult); // Outcome if there is a tie feeWei = 0; weiPlayer1 = game.betAmountInWei; weiPlayer2 = game.betAmountInWei; uint winDist = 0; uint winWei = 0; // Player one was closer, so they won if(distancePlayer1 < distancePlayer2) { winDist = distancePlayer2 - distancePlayer1; winWei = game.betAmountInWei * (winDist * WIN_PERCENT_PER_DISTANCE) / 100; feeWei = winWei * FEE_PERCENT / 100; weiPlayer1 += winWei - feeWei; weiPlayer2 -= winWei; } // Player two was closer, so they won else if(distancePlayer2 < distancePlayer1) { winDist = distancePlayer1 - distancePlayer2; winWei = game.betAmountInWei * (winDist * WIN_PERCENT_PER_DISTANCE) / 100; feeWei = winWei * FEE_PERCENT / 100; weiPlayer2 += winWei - feeWei; weiPlayer1 -= winWei; } // Same distance, so it was a tie (see above) } /// Once the game is complete, each player can withdraw their earnings /// A fee is charged on winnings only and provided to the contract authority function withdrawEarnings(uint gameId) public { // Get the game instance and check that it exists GameInstance storage game = gameContext[gameId]; require(game.betAmountInWei > 0); require(game.state == State.Complete); var (feeWei, weiPlayer1, weiPlayer2) = calculateEarnings(gameId); bool payFee = false; uint withdrawAmount = 0; if(game.player1 == msg.sender) { // Can't have already withrawn require(game.withdrawnPlayer1 == false); game.withdrawnPlayer1 = true; // They can't withdraw again // If player1 was the winner, they will pay the fee if(weiPlayer1 > weiPlayer2) { payFee = true; } withdrawAmount = weiPlayer1; } else if(game.player2 == msg.sender) { // Can't have already withrawn require(game.withdrawnPlayer2 == false); game.withdrawnPlayer2 = true; // If player2 was the winner, they will pay the fee if(weiPlayer2 > weiPlayer1) { payFee = true; } withdrawAmount = weiPlayer2; } else { // The sender isn't a participant revert(); } // This game is no longer active for this player, and now moved to complete for this player arrayRemove(playerActiveGames[msg.sender], gameId); arrayAdd(playerCompleteGames[msg.sender], gameId); // Fire an event for the withdrawing of funds GameEvent(gameId, msg.sender, Event.Withdraw); // Pay the fee, if necessary if(payFee == true) { authority.transfer(feeWei); } // Transfer sender their outcome msg.sender.transfer(withdrawAmount); } }
Create and initialize a game instance with the sent bet amount. The creator will automatically become a participant of the game. gameId must be the return value of getNextGameId(...) for the sender wheelPositionHash should be calculated using createWheelBetHash(...) Make sure the player passed the correct value for the game id Get the game instance and ensure that it doesn't already exist Must provide non-zero bet Restrict betting amount NOTE: Game creation can be disabled by setting min/max bet to 0 Increment the create game counter for this player Update game state The creator becomes player1 This game is now open to others and active for the player Fire event for the creation of this game
function createGame(uint gameId, uint wheelPositionHash) public payable { require(getNextGameId(msg.sender) == gameId); GameInstance storage game = gameContext[gameId]; require(game.betAmountInWei == 0); require(msg.value > 0); require(msg.value >= minBetWei && msg.value <= maxBetWei); counterContext[msg.sender] = counterContext[msg.sender] + 1; game.state = State.WaitingForPlayers; game.betAmountInWei = msg.value; game.player1 = msg.sender; game.wheelBetPlayer1 = wheelPositionHash; arrayAdd(openGames, gameId); arrayAdd(playerActiveGames[msg.sender], gameId); GameEvent(gameId, msg.sender, Event.Create); }
15,831,880
[ 1, 1684, 471, 4046, 279, 7920, 791, 598, 326, 3271, 2701, 3844, 18, 1021, 11784, 903, 6635, 12561, 279, 14188, 434, 326, 7920, 18, 7920, 548, 1297, 506, 326, 327, 460, 434, 6927, 12496, 548, 5825, 13, 364, 326, 5793, 19100, 2555, 2310, 1410, 506, 8894, 1450, 752, 59, 11648, 38, 278, 2310, 5825, 13, 4344, 3071, 326, 7291, 2275, 326, 3434, 460, 364, 326, 7920, 612, 968, 326, 7920, 791, 471, 3387, 716, 518, 3302, 1404, 1818, 1005, 6753, 5615, 1661, 17, 7124, 2701, 1124, 5792, 2701, 1787, 3844, 5219, 30, 14121, 6710, 848, 506, 5673, 635, 3637, 1131, 19, 1896, 2701, 358, 374, 17883, 326, 752, 7920, 3895, 364, 333, 7291, 2315, 7920, 919, 1021, 11784, 12724, 7291, 21, 1220, 7920, 353, 2037, 1696, 358, 10654, 471, 2695, 364, 326, 7291, 10151, 871, 364, 326, 6710, 434, 333, 7920, 2, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 12496, 12, 11890, 7920, 548, 16, 2254, 19100, 2555, 2310, 13, 1071, 8843, 429, 203, 565, 288, 203, 3639, 2583, 12, 588, 2134, 12496, 548, 12, 3576, 18, 15330, 13, 422, 7920, 548, 1769, 203, 203, 3639, 14121, 1442, 2502, 7920, 273, 7920, 1042, 63, 13957, 548, 15533, 203, 3639, 2583, 12, 13957, 18, 70, 278, 6275, 382, 3218, 77, 422, 374, 1769, 7010, 540, 203, 3639, 2583, 12, 3576, 18, 1132, 405, 374, 1769, 203, 540, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 1131, 38, 278, 3218, 77, 597, 1234, 18, 1132, 1648, 943, 38, 278, 3218, 77, 1769, 203, 203, 3639, 3895, 1042, 63, 3576, 18, 15330, 65, 273, 3895, 1042, 63, 3576, 18, 15330, 65, 397, 404, 31, 203, 203, 3639, 7920, 18, 2019, 273, 3287, 18, 15946, 1290, 1749, 3907, 31, 203, 3639, 7920, 18, 70, 278, 6275, 382, 3218, 77, 273, 1234, 18, 1132, 31, 203, 3639, 7920, 18, 14872, 21, 273, 1234, 18, 15330, 31, 203, 3639, 7920, 18, 21344, 38, 278, 12148, 21, 273, 19100, 2555, 2310, 31, 203, 540, 203, 3639, 526, 986, 12, 3190, 43, 753, 16, 7920, 548, 1769, 203, 3639, 526, 986, 12, 14872, 3896, 43, 753, 63, 3576, 18, 15330, 6487, 7920, 548, 1769, 203, 203, 3639, 14121, 1133, 12, 13957, 548, 16, 1234, 18, 15330, 16, 2587, 18, 1684, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.6; interface I{ function transfer(address to, uint value) external returns(bool); function balanceOf(address) external view returns(uint); function genesisBlock() external view returns(uint); } contract Treasury { address private _governance; struct Beneficiary { uint128 amount; uint128 emission; uint lastClaim; } mapping (address => Beneficiary) public bens; struct Poster { uint128 amount; uint128 lastClaim; } mapping (address => Poster) public posters; struct AirdropRecepient { uint128 amount; uint128 lastClaim; } mapping (address => AirdropRecepient) public airdrops; struct Refund { uint128 amount; uint128 lastClaim; uint emission; } mapping (address => Refund) public refunds; address private _oracle; address private _letToken; address private _founding; uint public totalPosters; uint public totalAirdrops; uint public totalRefundsEmission; uint public totBenEmission; uint public epochBlock; bool private _init; function init() public { require(_init == false); _init = true; _governance = 0x5C8403A2617aca5C86946E32E14148776E37f72A; _letToken =0x7DA2331C522D4EDFAf545d2F5eF61406D9d637A9; _founding =0xAE6ba0D4c93E529e273c8eD48484EA39129AaEdc; //erase refunds from storage to re-add as airdrop and don't fuck up the storage during upgrade //GENESIS POSTERS: //poster address //rewards address /*0x7624286abCC6844820a865985B812e1491C27eB9,0x590F71c02F34c712725D21EC489B9A49a5744618*/ addAirdrop(0x298016db488516E9FdB860E12424366f47E3Df2a,8409276891862e9);//1355445099002e9+4763008208587e9+2290823484273e9 /*0xb2b969406c7B5CD78F38F886546E03b29732c868,0xCA62CEB6b303CcaE7e93DBFAD9b2C5226ECBcD9a*/ addAirdrop(0x5C8403A2617aca5C86946E32E14148776E37f72A,9973652395879e9);//4578569433e9+9748217040355e9+220856786091e9//mine /*0xb22a07aa77B86A480d9A1e58115e2f51454A57Ce,0xb95c6E794B24f6d6eaA711f1a56970EFb1Cf28f4*/ addAirdrop(0xb22a07aa77B86A480d9A1e58115e2f51454A57Ce,2942054105290e9);//1659912275574e9+693508225838e9+588633603878e9 /*0xA7cfC2C4821e61738a3cd78ECD519E125811c22d,0x37EaE1f5C83d9d762823D679b927740bf2CBB1f3*/ addAirdrop(0xCd148Bc79B0E415161d9d6Df1BFB2DF545B509DA,971636504326e9);//509886791340e9+683763199e9+461065949787e9 /*0x1429c66c47BC802AE3A7DF0C572f7b8F3763bC68*/ addAirdrop(0xb8824771aF976B78A75af75746860ae5B4Bb8d21,4354120598847e9); /*0x712092Da547D45535935f25F31eA77dbDcaAF0C9*/ addAirdrop(0xA2543A9A96Cc4b35B4dCEb8AA85450fA1884D96F,1186385207e10); /*0x8c5a463EE76F337B768CAbB00331aF5F435DfDBE*/ addAirdrop(0x6890a4813DCE1769a068F8616c696D106c632eb2,15423007691e10); /*0x93Eb0bdd70030A93086a22Cbdfae5B50EB9BA35C*/ addAirdrop(0xc693A445BA97F2c46Adf33f122d25ee47510bf47,2707934055083e9); /*0xcedABfd6CC2EE45218E01b16Fb11B3e80c29f3d6*/ addAirdrop(0xe161fb51737770d1908235683d479c2DAfbC3aF8,8839870288e9); /*0x14c811580D8cea36a3217FE1e458CeeAa4E85d7c*/ addAirdrop(0xca4ed1a1f03345a24bAa6D39E8886f99Aca7Bf59,10677466863e9); /*0xb400aaa2Ec0068a42CFC95B63Fee82B7106DB945*/ addAirdrop(0xAA5a65D14df735b3bc39f9e639847160402a40eD,51736798994e9); /*0x1575Cfad1210043020CF960de07FDFeB0f37374d*/ addAirdrop(0xc660215CDcDEbA3Ca2d016f47C1B6890314Da6AF,65786360224e9); /*0x0e332b84DdDB17F5cE436254bD72949C96dB573A*/ addAirdrop(0x18FE7625B6B0dd30bEaAfFDEEA63F386bE84Ab76,111520209458e9); /*0x1A6A64EC952935cE597a20D89Ed1155472239920*/ addAirdrop(0x0a2Cce3b5caa3A505e69A36e140FfdAC90b93A8d,1182405602245e9); /*0xD9ED523eA4A620521110761262101b3Db6c1C7B9*/ addAirdrop(0xa8aA887c2480A5095A0984aB6c8b038866f429cf,4539166729113e9);//4225307291525e9+313859437588e9 /*0x480f8676dE082A30E990bCA70b9a96584b78Bb03*/ addAirdrop(0xC5757Cb3A85E67C5dc6648B9520B970a6b2e23A5,677251634281e9); /*0x1b910114ac08aBD123625DeA2485BF1B2EA2D6F0*/ addAirdrop(0xCeCe87a0Cc16Ed7a41Ffd9D74158ED06E74Bf041,8304696449e10); /*0x2529D7333B0840867A86FC1891eedc991b8A0744*/ addAirdrop(0x9900749C03B45970Be0365d8084F95CD17C5D580,3954534393434e9); /*0xa94c1dF74D251A52F2F0969dB35Dd6ED02D79163*/ addAirdrop(0x09E5A998b548eaAfd4346933d1C8231576740EEa,2372770414e10); /*0xA6559801FE3Dd11dB5e09BDAa74663bd5830c67d*/ addAirdrop(0xCAd88b9aA4bdEE0333707A88b8D4DDaD1bd1688a,30690330354e9); /*0x1a76C2CEB00e41e9308960E837325E357E8DAf46*/ addAirdrop(0x438Bd153F138a45751576ecA0960eB0155a54ac2,41589363588e9); /*0x26bB046B581Fb0C926cF37B9Ba8184C4c42049BE*/ addAirdrop(0xA4fbe3b21D0eF250E7781B2d9440dAF4fEbD6E7C,129431472998e9); /*0xB9C29Fb11fd9b17294D224C14330d9eAFC55D7F6*/ addAirdrop(0x56228eCE4Ed037B739F89e157AF5393F27C7217a,322024735262e9); /*0x85970790F2f25217f159dE74648fD34Fae90f952*/ addAirdrop(0xc95EB2A57ed8B1ae2093cA8Fa95E35a222DCF396,307395770522e9); /*0x651934252d730A373022a00DDacC86d46974A2Dc*/ addAirdrop(0x579759B2D158cacc3483d7916E56B8AE8441192c,261056386199e10); /*0x0D444402c072a3c903f62F83DB090b4B70017983*/ addAirdrop(0xA90e227E8D9BdC3811Fdfe1D074A7663232bA1C1,204247509266e9); /*0x6F4b03e8884B02Ac1698842a12C3fcB0Ba27A413*/ addAirdrop(0x1feC87F1B172fF535C7b680F07E052BA5B946d5f,98033705286e9); /*0xd3b4dC7e5ff0420DeaD3d29088eA79615Ac73bf6*/ addAirdrop(0xA6E23236b01B67c96784098e25566804c9D190b5,366463696192e9);//328193399965e9+38270296227e9 /*0xc1446C4804e35175CF823Bb4C24083B8694ce2C6*/ addAirdrop(0xbDecBB867b37908B4B216FC5bd164aeD5DefBa78,246838514749e9); /*0x66939EC5fDf8DC8906998ef0b10c35a7DE5F5CB6*/ addAirdrop(0x63FEeB2fe03100692ca05D2caA9E03c79e033d2c,2735052795e10); /*0xA7993e5e6A76D597Ae4014DBbc6070215E6a32C5*/ addAirdrop(0xB733bE65e4E15c8b074945Cf8d86fafD3A5e39C7,60986989751e9); /*0xF27B5f220410E8eA10aFA05D4951bA3F5d581218*/ addAirdrop(0xCd35Bd176364e553D0f7BDc21C88aEC21F3d3ec9,683763199e9); /*0x219d1484CC5Fd8C4f227320f306c935415F0F0c6*/ addAirdrop(0xB021a13Bbc3eeA6B2988F5BfF773a55c4845eB2B,793084572588e9);//384868079496e9+408216493092e9 /*0x0FFFAa813b8840bEaDCaC70108c65F1e412fbF0A*/ addAirdrop(0xbB18b2aD3082Dc8E1c18fD5438fFb3E7ef5Af2D6,3418815994e9); /*0x2eA08727073011B9EFDEBa3fBdA13b200FC47571*/ addAirdrop(0x5CEbA48722A6549235a009Dc45aBB31ae065Db58,85812281443e9); /*0xa1Da338c757F58a71c8388Cf3322ad2f1e04aebE*/ addAirdrop(0x9d6718f99bF4e292f9037c7221F71fb295d0a1cE,6837631988e9); /*0xad0d8CFc84187e13d1ebD669973773412E53c88A*/ addAirdrop(0xa9aA6A7B2e9A7C2ad628E096C5EFa148a6754F89,6837631988e9); /*0xde2DCA33BA591dD7124d693c6ea1fCEDA7340A9a*/ addAirdrop(0x0783462Aec2C07Ffb26ff222b56CeFA56CFDD8b9,3418815994e9); /*0x0e61824d96ae257Ad5697c2A02D49198417d4251*/ addAirdrop(0xC20B282d6d26a05DDD2FFD26c643459246520889,12572288306e10); /*0xC20B282d6d26a05DDD2FFD26c643459246520889*/ addAirdrop(0xC20B282d6d26a05DDD2FFD26c643459246520889,799453229e10); /*0xff6160Ce01F6B7c85e8aD577659C88de44633024*/ addAirdrop(0x481D26A19e7014acFbF30491Fd54b004D7D05109,899025626350e9);//363241479166e9+535784147184e9 /*0x882f165c1bD1dD3c13Aa2c29E4BAa7CDBEEc2C71*/ addAirdrop(0xA8FA8CefeEa10Dd5EfbE020C479aC18Df8aB9A4D,125381557715e9);//23327434442e9+102054123273e9 //IF YOU SEE THAT YOUR REWARDS ADDRESS IS SET INCORRECTLY OR YOUR ADDRESS IS MISSING, DO NOT HESITATE TO REACH OUT /*0xA27a4FE9a98Def35CCa53A04fc24192f55D63d52*/ addAirdrop(0xA27a4FE9a98Def35CCa53A04fc24192f55D63d52,13050237277e10); /*0xD1c4D9487a29302531E4358A631368AA9c6b580d*/ addAirdrop(0xD1c4D9487a29302531E4358A631368AA9c6b580d,9491081656e9); /*0x43F04314eC5e18Be5D1708717EC5C7c78e2dD5Fc*/ addAirdrop(0x43F04314eC5e18Be5D1708717EC5C7c78e2dD5Fc,249140893471e9); /*0x9CbFBc68B8938032E07564084A88b1da1E27a95a*/ addAirdrop(0x9CbFBc68B8938032E07564084A88b1da1E27a95a,1186385207e10); /*0x8afE8Ef93D3d2b5DF49c07465f6FF23d1Dce9b86*/ addAirdrop(0x8afE8Ef93D3d2b5DF49c07465f6FF23d1Dce9b86,17795778105e9); /*0xB0ffEdF10fEeE57Ec4e89aA3fA149059010f8164*/ addAirdrop(0xB0ffEdF10fEeE57Ec4e89aA3fA149059010f8164,136434298805e9); /*0xC51bCa9db7Cf91F0341143D1d51FDE645ca1b383*/ addAirdrop(0xC51bCa9db7Cf91F0341143D1d51FDE645ca1b383,10703476785e9); /*0x3e16541ecADB2D8B5b3480FdE2823baF39EE2303*/ addAirdrop(0x3e16541ecADB2D8B5b3480FdE2823baF39EE2303,90979552668e9); /*0x444053c2a9f4FE79869ada8fd403DE1835983aF3*/ addAirdrop(0x444053c2a9f4FE79869ada8fd403DE1835983aF3,10703476785e9); /*0x302e9d4ee70f5393dff11d3bc87dB58034Db0F95*/ addAirdrop(0x302e9d4ee70f5393dff11d3bc87dB58034Db0F95,153426778881e9); /*0x65A9bf405184c71445Ce166Ee0c6f6599032c944*/ addAirdrop(0x65A9bf405184c71445Ce166Ee0c6f6599032c944,16055215177e9); /*0x7158287A38a9528Df52d7171189dA80a0604d834*/ addAirdrop(0x7158287A38a9528Df52d7171189dA80a0604d834,341881599e9); /*0xCfe64Ad9595C8E23D1161945d5088b68B85f3138*/ addAirdrop(0xCfe64Ad9595C8E23D1161945d5088b68B85f3138,1006465190904e9); /*0xaeEafd0383Ada3ef89E79c606Fc551eaa88f1361*/ addAirdrop(0xaeEafd0383Ada3ef89E79c606Fc551eaa88f1361,84961007842e9);//80004092284e9+4956914558e9 /*0x1fd22bB198000743af6C97c4eB64bcEAd0678576*/ addAirdrop(0x1fd22bB198000743af6C97c4eB64bcEAd0678576,41915086344e9); /*0xC7d46CB56F732354819624556Fb4Ae1905DCAc13*/ addAirdrop(0xC7d46CB56F732354819624556Fb4Ae1905DCAc13,47140257455e9); /*0xA6D8416548ac7A49ABC1FE4f69037BdEd89f7b92*/ addAirdrop(0xA6D8416548ac7A49ABC1FE4f69037BdEd89f7b92,61961431987e9); /*0x543af6FF1c1195e56bdB91B4422A1bbd0dC4A945*/ addAirdrop(0x543af6FF1c1195e56bdB91B4422A1bbd0dC4A945,44539335228e9); //dev fund addBen(0x5C8403A2617aca5C86946E32E14148776E37f72A,1e23,0,7e22); //addBen(0xD6980B8f28d0b6Fa89b7476841E341c57508a3F6,1e23,0,1e22);//change addy //addBen(0x1Fd92A677e862fCcE9CFeF75ABAD79DF18B88d51,1e23,0,5e21);// change addy //added without arrays, so the code is representative //Fantom //first one: addAirdrop(0x76b60dCf71dA2294f8aA034432D925D1eED8cf68,5); addAirdrop(0x6718EB204A15601BCE38b6695816D6206F8207AB,52); addAirdrop(0x4B254c5F0014487fB6DB637835a123667cc6e08b,500); addAirdrop(0x679B4172E1698579d562D1d8b4774968305b80b2,100); addAirdrop(0xa25e3A5F8268538c3726CcEc9624056973b71d2F,500); addAirdrop(0xEC2e79b2df2fF15Bf74dC6FD2dbA4eEd348Aa677,40); addAirdrop(0x3a2Fe85E391D75ed31133A6b91D1AA1a7BF47D79,10); addAirdrop(0x62581E22530F7D4Af5bbAAA62e5364d8B44F9A84,10); addAirdrop(0xe5936d9De1527832d39d05F9F9f7EC88cc2755Ed,101); addAirdrop(0xC0D35857e87F5ADe6055714706fb4dFD96DE087E,1); addAirdrop(0x2D8e1Ef6B2b5F6Bae1D47aa61c3BE3Bf413A34C3,20); addAirdrop(0x5C8403A2617aca5C86946E32E14148776E37f72A,1); addAirdrop(0x1f3236F64Cb6878F164e3A281c2a9393e19A6D00,50); addAirdrop(0x08539431F4d59a02D0347588F6fBdb7d69aAd2c3,1000); addAirdrop(0xd517970724351D1c3A676D45B79634DDe2a2899b,50); addAirdrop(0x9253ced0fdFb7BD4E505CD5E2a5C8712F3251d69,10); addAirdrop(0xC04d40CCD06f85Efd7A760a85D7aA42355DB00D5,10); addAirdrop(0xB7DC6A421bE69A53F1A6db51808bD3080e54aDfB,250); addAirdrop(0x79be773e584954205b6533708c2f33ae5827b790,10); addAirdrop(0xc6C8AeCb1d9cA59A09d691cDa8539992655dbfB3,600); addAirdrop(0x6e32a45cce1e03Fc13D49E73DdC329dB99A1364a,1); addAirdrop(0x9b090761223bF884AE902C66C0373e5920F567Aa,50); addAirdrop(0x57a99f34721418E3c4A054E0F7356a1bC712b8e9,10); addAirdrop(0x1e62A12D4981e428D3F4F28DF261fdCB2CE743Da,1000); addAirdrop(0x1F2bC22E55fBD7853A49421C8e038d1f2025dC3c,500); addAirdrop(0xffC4C7896526105338742f74f91667D94199C1E8,2); addAirdrop(0x185269516c6a37af244B94bE962C9B33A3Cbd52B,40); addAirdrop(0x0A5aec13f9cF73d848f6B03E4F7Ee6D888cD924e,1000); addAirdrop(0x61edd22e98c32ccf986CBf406297423D95bD3cA3,250); //second one: //manual migration addAirdrop(0x62172b838724a9Ad965F278f1d2438BB2Ab20ea2,10); addAirdrop(0xb83C10E1a1a713f60Ce847528D44F66aCC767f05,50); addAirdrop(0x1924eb636F5b7949656BB3a089ea7715849bd724,207); addAirdrop(0xd517970724351D1c3A676D45B79634DDe2a2899b,10); addAirdrop(0x91ddEb35264287785762e666B5fba5Da9E83b5C8,10); addAirdrop(0x61edd22e98c32ccf986CBf406297423D95bD3cA3,77); //addAirdrop(0xA8FA8CefeEa10Dd5EfbE020C479aC18Df8aB9A4D,4.5); addAirdrop(0x39E24A5024b44a9350cc43f7e1bf59427ba79B87,20); addAirdrop(0x49d8b33c50e0fA7fcDF78C5bd0c1B01238390E4d,1); addAirdrop(0x0a5B57FbaC6e432c01555edD74deCC232b174d07,1); //addAirdrop(0x0a5B57FbaC6e432c01555edD74deCC232b174d07,37.96); addAirdrop(0xabCa5C6C22C69e27D1C7Cc3b8Cbd2E7D9bBB3666,1); addAirdrop(0xa8b5dD12e943a1AC67F17E3d1273e9B02beF8483,50); addAirdrop(0xA407496f8eFBE5aC9baA834f833084dc3d2cB14d,594); addAirdrop(0x707A29e6593406E6444C4A465f535aD44962cEf6,400); addAirdrop(0x298016db488516E9FdB860E12424366f47E3Df2a,500); addAirdrop(0x13E5C4425502c2a0De10Fe0eA16b5Ec74C504c5d,3); addAirdrop(0x5C8403A2617aca5C86946E32E14148776E37f72A,250); addAirdrop(0x13E5C4425502c2a0De10Fe0eA16b5Ec74C504c5d,27); //contributions addAirdrop(0x7E13b262daB598Dd9d4e11a5Bc61c3097aF73088,300); addAirdrop(0xffC4C7896526105338742f74f91667D94199C1E8,10); addAirdrop(0xbECc7a18CA0718939dd2Bf03D49F38ed7D91AbCE,10); addAirdrop(0x5C8403A2617aca5C86946E32E14148776E37f72A,100); addAirdrop(0x73A74B1E90C8301813379d7b77a2cfbD90D8B277,1000); addAirdrop(0x54fd4Fcaa9e47580FFB7F937633F84166ab4E5DA,1); addAirdrop(0xC04d40CCD06f85Efd7A760a85D7aA42355DB00D5,15); //addAirdrop(0xBFd271EcC7a54f0950f7021E3A0A81a39bF7434a,22.5); addAirdrop(0x5C8403A2617aca5C86946E32E14148776E37f72A,50); addAirdrop(0xBFd271EcC7a54f0950f7021E3A0A81a39bF7434a,30); addAirdrop(0xBFd271EcC7a54f0950f7021E3A0A81a39bF7434a,100); addAirdrop(0x25eC428481C715f54C9c4219605Fb4DF446850E2,10); addAirdrop(0x13E5C4425502c2a0De10Fe0eA16b5Ec74C504c5d,12); //addAirdrop(0x8f1bF7072f3772509f863c659A9d5e2Fb0a56971,0.01); addAirdrop(0x8976b2FDE745D8857D7b953D9C85F011094A1838,10); addAirdrop(0x8976b2FDE745D8857D7b953D9C85F011094A1838,20); addAirdrop(0xe61d4CfB4e0C97fE896064849917Ffd867a1DBFA,1); addAirdrop(0x5C8403A2617aca5C86946E32E14148776E37f72A,30); addAirdrop(0x3c1acE375b585d21382AD64cdDA174283b96A8EC,108); addAirdrop(0xf9bA2F51Def499979Bfdb66996ac19DE956B3F0D,1); addAirdrop(0x8592d6527DA473d4686Dd84805E6e94DD5Da2609,500); //addAirdrop(0xbDF3a518341F8DC49f14c644665Fa35034DA41Fa,1.5); addAirdrop(0x42c1905bbE243cc125Cc7426381309748091F250,20); //addAirdrop(0x1d8B28a0Fdb71De81280E6a254707c4006476428,0.1); addAirdrop(0x12F0da4056A8d22a0F605cDF80d6771adb0e79Cc,1); //addAirdrop(0xf077eC872d3cA323Ae3aEf0F53Fbe36cdd8924A8,73.9826); addAirdrop(0x89778fDB388A0CC83b19B51F0b50E78100540B43,500); addAirdrop(0xBFd271EcC7a54f0950f7021E3A0A81a39bF7434a,50); addAirdrop(0xBFd271EcC7a54f0950f7021E3A0A81a39bF7434a,40); addAirdrop(0x5C8403A2617aca5C86946E32E14148776E37f72A,50); //95% withdrawals missing other 5% //addAirdrop(0xAf2B13bdF7071208071F083572205b53776e445E,2.5); //addAirdrop(0xA8FA8CefeEa10Dd5EfbE020C479aC18Df8aB9A4D,0.02); //addAirdrop(0x19495E77e394077e45820AaA589283aF2C6A84eE,4.5); //ETHEREUM //Ethereum ratio 1 ether = 1000 fantom addAirdrop(0xbCB28129b40105b1B38eB1F4e759c358Be892D19,238); addAirdrop(0x298016db488516E9FdB860E12424366f47E3Df2a,10); addAirdrop(0x119840f12E9D21F1c37097e3f65d3Cc1AC084646,3000); addAirdrop(0x3F73Ea32dcD34a0B5CDc16EAF9b95bf3b3C8F44a,140); addAirdrop(0x56228eCE4Ed037B739F89e157AF5393F27C7217a,250); addAirdrop(0x9E0dffC8134BC73cE08Cce55259774674B701C2b,50); addAirdrop(0xb44FC936577C8929541C52C76e1d642E7B393EA4,263); addAirdrop(0xAb769309EbCEEDa984E666ab727b36211bA02A8a,20); addAirdrop(0x19c41f73416d68590e953868505F4bb8239Cefb5,85); addAirdrop(0xBf26925f736E90E1715ce4E04cD9c289dD1bc002,1000); addAirdrop(0x1Fd92A677e862fCcE9CFeF75ABAD79DF18B88d51,100); addAirdrop(0xB6d3aa0B6D3b47BE1736F277eCBc7e03A6fB91d7,10); addAirdrop(0xD5e4a02aF646B5466Ab9984d49890ED30d4d47Eb,20); addAirdrop(0x0e979995e1dFB7546904E087c712DA6dd117F066,100); addAirdrop(0x3b7c23B91eAad19aF4f085C99E36bBaaf8E66741,40); } function genesis(uint block) public { require(msg.sender == 0xAE6ba0D4c93E529e273c8eD48484EA39129AaEdc); epochBlock = block; } function setGov(address a)external{ require(msg.sender==_governance); _governance=a; } function setOracle(address a)external{ require(msg.sender==_governance); _oracle=a; } function _getRate() internal view returns(uint){ uint rate = 31e14; uint quarter = block.number/28e6; if (quarter>0) { for (uint i=0;i<quarter;i++) { rate=rate*4/5; } } return rate; } // ADD function addBen(address a, uint amount, uint lastClaim, uint emission) public { require(msg.sender == _governance && bens[a].amount == 0 && totBenEmission <=1e23); if(lastClaim < block.number) { lastClaim = block.number; } uint lc = bens[a].lastClaim; if (lc == 0) { bens[a].lastClaim = uint64(lastClaim); } if (bens[a].amount == 0 && lc != 0) { bens[a].lastClaim = uint64(lastClaim); } bens[a].amount = uint128(amount); bens[a].emission = uint128(emission); totBenEmission+=emission; } function addAirdropBulk(address[] memory r,uint[] memory amounts) external { require(msg.sender == _governance); for(uint i = 0;i<r.length;i++) { uint prevA = airdrops[r[i]].amount; airdrops[r[i]].amount += uint128(amounts[i]); if(prevA<1e20&&airdrops[r[i]].amount>=1e20){ totalAirdrops+=1; } if(airdrops[r[i]].lastClaim==0){ airdrops[r[i]].lastClaim=uint128(block.number); } } } function addAirdrop(address r,uint amount) public { require(msg.sender == _governance); uint prevA = airdrops[r].amount; airdrops[r].amount += uint128(amount); if(prevA<1e20&&airdrops[r].amount>=1e20){ totalAirdrops+=1; } if(airdrops[r].lastClaim==0){ airdrops[r].lastClaim=uint128(block.number); } } function addPosters(address[] memory r, uint[] memory amounts) external{ require(msg.sender == _oracle); for(uint i = 0;i<r.length;i++) { uint prevA = posters[r[i]].amount; posters[r[i]].amount += uint128(amounts[i]); if(prevA<1e20&&posters[r[i]].amount>=1e20){ totalPosters+=1; } if(posters[r[i]].lastClaim==0){ posters[r[i]].lastClaim=uint128(block.number); } } } // CLAIM function getRewards(address a,uint amount) external{ //for staking require(epochBlock != 0 && msg.sender == 0x0FaCF0D846892a10b1aea9Ee000d7700992B64f8);//staking I(0x7DA2331C522D4EDFAf545d2F5eF61406D9d637A9).transfer(a,amount);//token } function claimBenRewards() external returns(uint){ uint lastClaim = bens[msg.sender].lastClaim; if (lastClaim < epochBlock) { lastClaim = epochBlock; } require(epochBlock != 0 && block.number>lastClaim); uint rate = _getRate(); rate = rate*bens[msg.sender].emission/1e23; uint toClaim = (block.number - lastClaim)*rate; if(toClaim>bens[msg.sender].amount){ toClaim=bens[msg.sender].amount; } if(toClaim>I(0x7DA2331C522D4EDFAf545d2F5eF61406D9d637A9).balanceOf(address(this))){//this check was supposed to be added on protocol upgrade, emission was so slow, that it could not possibly trigger overflow toClaim=I(0x7DA2331C522D4EDFAf545d2F5eF61406D9d637A9).balanceOf(address(this)); } bens[msg.sender].lastClaim = uint64(block.number); bens[msg.sender].amount -= uint128(toClaim); I(0x944B79AD758c86Df6d004A14F2f79B25B40a4229).transfer(msg.sender, toClaim); return toClaim; } function claimAirdrop()external { uint lastClaim = airdrops[msg.sender].lastClaim; if(epochBlock>lastClaim){ lastClaim=epochBlock; } airdrops[msg.sender].lastClaim=uint128(block.number); require(airdrops[msg.sender].amount>0&&epochBlock!=0&&block.number>lastClaim); uint toClaim; if(airdrops[msg.sender].amount>=1e20){ uint rate =_getRate()*2; toClaim = (block.number-lastClaim)*rate/totalAirdrops; if(toClaim>airdrops[msg.sender].amount){ toClaim=airdrops[msg.sender].amount; } if(toClaim>I(0x7DA2331C522D4EDFAf545d2F5eF61406D9d637A9).balanceOf(address(this))){ toClaim=I(0x7DA2331C522D4EDFAf545d2F5eF61406D9d637A9).balanceOf(address(this)); } airdrops[msg.sender].amount -= uint128(toClaim); if(airdrops[msg.sender].amount<1e20){ totalAirdrops-=1; if(airdrops[msg.sender].amount==0){ delete airdrops[msg.sender]; } } } else { toClaim = airdrops[msg.sender].amount; delete airdrops[msg.sender]; } I(0x7DA2331C522D4EDFAf545d2F5eF61406D9d637A9).transfer(msg.sender, toClaim); } function claimPosterRewards()external { uint lastClaim = posters[msg.sender].lastClaim; if(epochBlock>lastClaim){ lastClaim=epochBlock; } posters[msg.sender].lastClaim=uint128(block.number); require(posters[msg.sender].amount>0&&epochBlock!=0&&block.number>lastClaim); uint rate=31e14;rate*=2; uint toClaim =(block.number-lastClaim)*rate/totalPosters; if(toClaim>posters[msg.sender].amount){toClaim=posters[msg.sender].amount;} if(toClaim>I(0x7DA2331C522D4EDFAf545d2F5eF61406D9d637A9).balanceOf(address(this))){ toClaim=I(0x7DA2331C522D4EDFAf545d2F5eF61406D9d637A9).balanceOf(address(this)); } posters[msg.sender].amount-=uint128(toClaim); I(0x7DA2331C522D4EDFAf545d2F5eF61406D9d637A9).transfer(msg.sender, toClaim); if(posters[msg.sender].amount==0){ totalPosters-=1; posters[msg.sender].lastClaim==0; } } // IN CASE OF ANY ISSUE function removeAirdrops(address[] memory r) external{ require(msg.sender == _governance); for(uint i = 0;i<r.length;i++) { if(airdrops[r[i]].amount>=1e20){ totalAirdrops -=1; } delete airdrops[r[i]]; } } function removePosters(address[] memory r) external{ require(msg.sender == _oracle); for(uint i = 0;i<r.length;i++) { if(airdrops[r[i]].amount>=1e20){ totalPosters -=1; } delete posters[r[i]]; } } function removeBen(address a) public { require(msg.sender == _governance); totBenEmission-=bens[a].emission; delete bens[a]; } function removeRefunds(address[] memory r) external{ require(msg.sender == _governance); for(uint i = 0;i<r.length;i++) { if(refunds[r[i]].emission>=totalRefundsEmission){refunds[r[i]].emission=totalRefundsEmission;}totalRefundsEmission -= refunds[r[i]].emission; delete refunds[r[i]]; } } function removeRefund(address a) public{ require(msg.sender == _governance); if(refunds[a].emission>=totalRefundsEmission){refunds[a].emission=totalRefundsEmission;}totalRefundsEmission -= refunds[a].emission; delete refunds[a]; } }
IN CASE OF ANY ISSUE
function removeAirdrops(address[] memory r) external{ require(msg.sender == _governance); for(uint i = 0;i<r.length;i++) { if(airdrops[r[i]].amount>=1e20){ totalAirdrops -=1; } delete airdrops[r[i]]; } for(uint i = 0;i<r.length;i++) { if(airdrops[r[i]].amount>=1e20){ totalAirdrops -=1; } delete airdrops[r[i]]; } }
13,116,494
[ 1, 706, 18403, 15932, 16743, 467, 1260, 1821, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 1206, 37, 6909, 16703, 12, 2867, 8526, 3778, 436, 13, 3903, 95, 203, 202, 202, 6528, 12, 3576, 18, 15330, 422, 389, 75, 1643, 82, 1359, 1769, 203, 202, 202, 1884, 12, 11890, 277, 273, 374, 31, 77, 32, 86, 18, 2469, 31, 77, 27245, 288, 203, 1082, 202, 430, 12, 1826, 9005, 1121, 63, 86, 63, 77, 65, 8009, 8949, 34, 33, 21, 73, 3462, 15329, 203, 9506, 202, 4963, 37, 6909, 16703, 3947, 21, 31, 203, 1082, 202, 97, 203, 1082, 202, 3733, 279, 6909, 16703, 63, 86, 63, 77, 13563, 31, 203, 202, 202, 97, 203, 202, 202, 1884, 12, 11890, 277, 273, 374, 31, 77, 32, 86, 18, 2469, 31, 77, 27245, 288, 203, 1082, 202, 430, 12, 1826, 9005, 1121, 63, 86, 63, 77, 65, 8009, 8949, 34, 33, 21, 73, 3462, 15329, 203, 9506, 202, 4963, 37, 6909, 16703, 3947, 21, 31, 203, 1082, 202, 97, 203, 1082, 202, 3733, 279, 6909, 16703, 63, 86, 63, 77, 13563, 31, 203, 202, 202, 97, 203, 202, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x5870dA524635D1310Dc0e6F256Ce331012C9C19E/sources/contracts/contract/minipool/RocketMinipoolQueue.sol
Get the length of a queue Returns 0 for invalid queues
function getLength(MinipoolDeposit _depositType) override external view returns (uint256) { return 0; }
9,203,102
[ 1, 967, 326, 769, 434, 279, 2389, 2860, 374, 364, 2057, 11897, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9888, 12, 2930, 625, 1371, 758, 1724, 389, 323, 1724, 559, 13, 3849, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 374, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; /* This is the Revolution smart contract from the culottes project. Its copyrights (2019) belong to its authors including Jean Millerat (siggg at akasig dot org). It is distributed under the GNU Affero General Public License version 3 or later (AGPL v.3 or later). You can find a copy of this license with the full source code of this project at https://github.com/siggg/culottes */ contract Revolution { address public owner = msg.sender; // Criteria the citizen should match to win votes // e.g. : "a sans-culotte" string public criteria; // Hashtag to be used for discussing this contract // e.g. : "#SansCulottesRevolution" string public hashtag; // Minimum number of blocks before next cake distribution from the Revolution uint public distributionBlockPeriod; // Amount of WEI to be distributed to each citizen matching criteria uint public distributionAmount; // Number of the block at last distribution uint lastDistributionBlockNumber; // Are we running in testing mode ? bool public testingMode; // Is this Revolution irreversibly locked (end of life) ? bool public locked; // For a given citizen, let's put all positive (or negative) votes // received into a positive (or negative) justice scale. struct JusticeScale { address payable [] voters; mapping (address => uint) votes; uint amount; } // This the revolutionary trial for a given citizen struct Trial { address payable citizen; JusticeScale sansculotteScale; JusticeScale privilegedScale; uint lastClosingAttemptBlock; bool opened; bool matchesCriteria; } // Citizens known at this Revolution address payable [] public citizens; // Trials known at this Revolution mapping (address => Trial) private trials; // This is the amount of cakes in the Bastille uint public bastilleBalance; // Start of new trial for a given citizen event TrialOpened(string indexed _eventName, address indexed _citizen); // End of trial for a given citizen event TrialClosed(string indexed _eventName, address indexed _citizen); // New cake-vote received for a given citizen event VoteReceived(string indexed _eventName, address _from, address indexed _citizen, bool _vote, uint indexed _amount); // event Distribution(string indexed _eventName, address indexed _citizen, uint _distributionAmount); constructor(string memory _criteria, string memory _hashtag, uint _distributionBlockPeriod, uint _distributionAmount, bool _testingMode) public{ criteria = _criteria; hashtag = _hashtag; distributionBlockPeriod = _distributionBlockPeriod; distributionAmount = _distributionAmount; lastDistributionBlockNumber = block.number; testingMode = _testingMode; locked = false; } function lock() public { // will irreversibly lock this Revolution // only contract owner can lock require(msg.sender == owner); locked = true; } function vote(bool _vote, address payable _citizen) public payable { require(locked == false || bastilleBalance > 0); Trial storage trial = trials[_citizen]; trial.opened = true; if (trial.citizen == address(0x0) ) { // this is a new trial, emit an event emit TrialOpened('TrialOpened', _citizen); citizens.push(_citizen); trial.citizen = _citizen; } JusticeScale storage scale = trial.sansculotteScale; if (_vote == false) { scale = trial.privilegedScale; } scale.voters.push(msg.sender); scale.votes[msg.sender] += msg.value; scale.amount+= msg.value; emit VoteReceived('VoteReceived', msg.sender, _citizen, _vote, msg.value); if(testingMode == false) { closeTrial(_citizen); distribute(); } } function closeTrial(address payable _citizen) public { // check the closing lottery bool shouldClose = closingLottery(_citizen); // update attempt block number Trial storage trial = trials[_citizen]; trial.lastClosingAttemptBlock = block.number; if(shouldClose == false) { // no luck this time, won't close yet, retry later return; } // let's close the trial now emit TrialClosed('TrialClosed', _citizen); // Mark the trial as closed trial.opened = false; // Issue a verdict : is this citizen a sans-culotte or a privileged ? // By default, citizens are seen as privileged... JusticeScale storage winnerScale = trial.privilegedScale; JusticeScale storage loserScale = trial.sansculotteScale; trial.matchesCriteria = false; // .. unless they get more votes on their sans-culotte scale than on their privileged scale. if (trial.sansculotteScale.amount > trial.privilegedScale.amount) { winnerScale = trial.sansculotteScale; loserScale = trial.privilegedScale; trial.matchesCriteria = true; } // Compute Bastille virtual vote uint bastilleVote = winnerScale.amount - loserScale.amount; // Distribute cakes to winners as rewards // Side note : the reward scheme slightly differs from the culottes board game rules // regarding the way decimal fractions of cakes to be given as rewards to winners are managed. // The board game stipulates that fractions are rounded to the nearest integer and reward cakes // are given in the descending order of winners (bigger winners first). But the code below // states that only the integer part of reward cakes is taken into account. And the remaining // reward cakes are put back into the Bastille. This slightly lessens the number of cakes // rewarded to winners and slightly increases the number of cakes given to the Bastille. // The main advantage is that it simplifies the algorithm a bit. // But this rounding difference should not matter when dealing with Weis instead of real cakes. uint remainingRewardCakes = loserScale.amount; for (uint i = 0; i < winnerScale.voters.length; i++) { address payable voter = winnerScale.voters[i]; // First distribute cakes from the winner scale, also known as winning cakes // How many cakes did this voter put on the winnerScale ? uint winningCakes = winnerScale.votes[voter]; // Send them back winnerScale.votes[voter]=0; // FIXME : handle the case of failure to send winningCakes voter.send(winningCakes); // How many cakes from the loser scale are to be rewarded to this winner citizen ? // Rewards should be a share of the lost cakes that is proportionate to the fraction of // winning cakes that were voted by this voting citizen, pretending that the Bastille // itself took part in the vote. uint rewardCakes = loserScale.amount * winningCakes / ( winnerScale.amount + bastilleVote ); // Send their fair share of lost cakes as reward. // FIXME : handle the failure of sending rewardCakes voter.send(rewardCakes); remainingRewardCakes -= rewardCakes; } // distribute cakes to the Bastille bastilleBalance += remainingRewardCakes; // Empty the winner scale winnerScale.amount = 0; // Empty the loser scale for (uint i = 0; i < loserScale.voters.length; i++) { address payable voter = loserScale.voters[i]; loserScale.votes[voter]=0; } loserScale.amount = 0; } function closingLottery(address payable _citizen) private view returns (bool) { if (testingMode == true) { // always close when testing return true; } // returns true with a 30% probability // weighted by the time spent during that this distribution period since the last closing attempt // returns false otherwise uint randomHash = uint(keccak256(abi.encodePacked(block.difficulty,block.timestamp))); uint million = 1000000; // random inteeger between 0 and 999999 uint randomInt = randomHash % million; Trial storage trial = trials[_citizen]; uint blocksSince = block.number - trial.lastClosingAttemptBlock; if (blocksSince < distributionBlockPeriod) { randomInt *= blocksSince / distributionBlockPeriod; } if(randomInt < million * 30 / 100) { return true; } return false; } function distribute() public { // Did the last distribution happen long enough ago ? if (block.number - lastDistributionBlockNumber < distributionBlockPeriod) { return; } // For each citizen trial for (uint i = 0; i < citizens.length; i++) { address payable citizen = citizens[i]; Trial memory trial = trials[citizen]; // Is the trial closed ? // and Was the verdict "sans-culotte" (citizen does match criteria according to winners) ? // and Does the Bastille have more cakes left than the amount to be distributed ? if (trial.opened == false && trial.matchesCriteria == true ) { uint distributed = 0; if (bastilleBalance >= distributionAmount) { distributed = distributionAmount; } else { if (locked == true) { distributed = bastilleBalance; } } // Then send this sans-culotte its fair share of Bastille cakes. if (distributed > 0) { if (citizen.send(distributed)) { bastilleBalance -= distributed; emit Distribution('Distribution', citizen, distributed); } else { // sending failed, maybe citizen is a smart contract with an expensive fallback function ? emit Distribution('Distribution', citizen, 0); } } } } // Remember when this distribution happened. lastDistributionBlockNumber = block.number; } function getScaleAmount(bool _vote, address _citizen) public view returns (uint){ Trial storage trial = trials[_citizen]; if (_vote == true) return trial.sansculotteScale.amount; else return trial.privilegedScale.amount; } function trialStatus(address _citizen) public view returns(bool opened, bool matchesCriteria, uint sansculotteScale, uint privilegedScale) { Trial memory trial = trials[_citizen]; return (trial.opened, trial.matchesCriteria, trial.sansculotteScale.amount, trial.privilegedScale.amount); } function() payable external { require(locked == false); bastilleBalance += msg.value; } }
Compute Bastille virtual vote
uint bastilleVote = winnerScale.amount - loserScale.amount;
7,299,083
[ 1, 7018, 605, 689, 14120, 5024, 12501, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 324, 689, 14120, 19338, 273, 5657, 1224, 5587, 18, 8949, 300, 437, 550, 5587, 18, 8949, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4 .24; import "./Ownable.sol"; import "./HelperFunctions.sol"; import "./Farmer.sol"; //@Dev to ask contract Expertise is Ownable, HelperFunctions { //@Dev represents lab results struct LabResults { string Name; string location; string Manufacturer; string Harvest; string LabConclusion; uint256 index; } //@Dev represents an ExpertiseObject struct ExpertiseObject { address labaddress; uint256 DataAccessIndex; //@Dev keeps track of the amount of data that has been requested by user N.B. have to fix this in the other contracts to match this comment uint256 dataIndex; //@Dev Keeps track of the amount of data we have stored in the Data Mapping bool Activated; //@Dev Indicates whether the RawMaterial is active or not mapping(uint256 => LabResults) StoredData; //@Dev represents all the data related to a Lab } //@Dev stores data at the specified byte32 index mapping(address => ExpertiseObject) ExpertiseData; //@Dev called when Expertise data is requested event FarmerData(string name, string labaddress, string manufacturer, string harvest, string conclusion, bool found); //@Dev called when the GetExpertise method is called and passes all prerequisites event GetExpertiseDataLogger(string HarvestName, string FarmerName, string FarmerLocation, string message); //@Dev represents the Farmer contract Farmer InternalFarmer; constructor(address internalFarmerAddress) public { require(internalFarmerAddress != address(0)); InternalFarmer = Farmer(internalFarmerAddress); } // @Dev stores data using the given paramters to the data mapping //To revise //check whether the string being added is not null or empty function StoreExpertiseData(string name, string labaddress, string manufacturer, string harvest, string conclusion) public onlyOwner returns(string message) { if (isStringNullorEmpty(name) || isStringNullorEmpty(labaddress) || isStringNullorEmpty(manufacturer) || isStringNullorEmpty(harvest) || isStringNullorEmpty(conclusion)) { message = "Invalid Data"; emit GeneralLogger(message); return message; } if (msg.sender == address(0)) { message = "Invalid lab address"; emit GeneralLogger(message); return message; } if (ExpertiseData[msg.sender].Activated) { ExpertiseData[msg.sender].StoredData[ExpertiseData[msg.sender].dataIndex] = LabResults(name, labaddress, manufacturer, harvest, conclusion, ExpertiseData[msg.sender].dataIndex); ExpertiseData[msg.sender].dataIndex++; } else { ExpertiseData[msg.sender] = ExpertiseObject(msg.sender, 0, 0, true); ExpertiseData[msg.sender].StoredData[ExpertiseData[msg.sender].dataIndex] = LabResults(name, labaddress, manufacturer, harvest, conclusion, ExpertiseData[msg.sender].dataIndex); ExpertiseData[msg.sender].dataIndex++; } message = "Successfully stored Expertise data"; emit GeneralLogger(message); return message; } //@Dev Gets Lab data function GetLabData() public returns(string name, string labaddress, string manufacturer, string harvest, string conclusion, bool found) { if (msg.sender == address(0)) { emit GeneralLogger("Invalid sender address"); return (name, labaddress, manufacturer, harvest, conclusion, false); } if (!ExpertiseData[msg.sender].Activated) { emit GeneralLogger("No Lab data for specified user"); return (name, labaddress, manufacturer, harvest, conclusion, false); } name = ExpertiseData[msg.sender].StoredData[ExpertiseData[msg.sender].DataAccessIndex].Name; labaddress = ExpertiseData[msg.sender].StoredData[ExpertiseData[msg.sender].DataAccessIndex].location; manufacturer = ExpertiseData[msg.sender].StoredData[ExpertiseData[msg.sender].DataAccessIndex].Manufacturer; harvest = ExpertiseData[msg.sender].StoredData[ExpertiseData[msg.sender].DataAccessIndex].Harvest; conclusion = ExpertiseData[msg.sender].StoredData[ExpertiseData[msg.sender].DataAccessIndex++].LabConclusion; found = true; emit GeneralLogger("Lab data Found"); emit FarmerData(name, labaddress, manufacturer, harvest, conclusion, true); return (name, labaddress, manufacturer, harvest, conclusion, true); } //@Dev variation of the GetLabdata function returns the name and harvest name and farm location only function GetExpertiseData() public returns(string HarvestName, string FarmerName, string FarmerLocation, string message) { if (msg.sender == address(0)) { message = "Invalid sender address"; emit GeneralLogger(message); emit GetExpertiseDataLogger("", "", "", message); return ("", "", "", message); } bytes32 name = ""; bytes32 location = ""; bool found = false; (name, location, found) = InternalFarmer.GetDetails(); if (!found || !ExpertiseData[msg.sender].Activated) { emit GeneralLogger("Farmer details not found or no data associated to give Ethereum address found"); message = "Farmer details not found"; return ("", "", "", message); } message="Farmer details Found"; HarvestName=ExpertiseData[msg.sender].StoredData[ExpertiseData[msg.sender].DataAccessIndex].Name; FarmerName=bytes32ToString(name); FarmerLocation=bytes32ToString(location); emit GeneralLogger(message); emit GetExpertiseDataLogger(HarvestName,FarmerName,FarmerLocation,message); return (HarvestName,FarmerName,FarmerLocation,message); } }
@Dev called when Expertise data is requested
event FarmerData(string name, string labaddress, string manufacturer, string harvest, string conclusion, bool found);
13,106,754
[ 1, 36, 8870, 2566, 1347, 1312, 672, 784, 501, 353, 3764, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 478, 4610, 264, 751, 12, 1080, 508, 16, 533, 11814, 2867, 16, 533, 23803, 16, 533, 17895, 26923, 16, 533, 356, 15335, 16, 1426, 1392, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.7; import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import "./strings.sol"; contract HistoricalPriceConsumer is ChainlinkClient { using Chainlink for Chainlink.Request; using strings for *; uint256 constant private PHASE_OFFSET = 64; AggregatorV3Interface internal priceFeed; address private proxyAddress; address private oracle; bytes32 private jobId; uint256 private fee; uint private searchTimestamp; uint80 public answerRound; uint80 public previousRound; uint80 public nextRound; int public priceAnswer; uint public priceTimestamp; int public previousPrice; uint public previousPriceTimestamp; int public nextPrice; uint public nextPriceTimestamp; constructor() public { setPublicChainlinkToken(); //set oracle and jobId to the deployed adapter and job run by LinkRiver oracle = 0xF405B99ACa8578B9eb989ee2b69D518aaDb90c1F; jobId = "cc69bee28b51437197ef15387645236e"; fee = 0; // 0.1 * 10 ** 18; // 0.1 LINK } /** * Returns historical price for a unix epoch time and proxy address * "aggregatorAddress": "0x9326BFA02ADD2366b30bacB125260Af641031331", "unixDateTime": 1612137600, "ISODateTime": "2021-02-01 00:00:00" */ function getHistoricalPrice(address _proxyAddress, uint _unixTime) public returns (bytes32 requestId) { Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.singleResponseFulfill.selector); // Set the URL to perform the GET request on request.add("proxyAddress", addressToString(_proxyAddress)); request.add("unixDateTime", uint2str(_unixTime)); //set the timestamp being searched, we will use it for verification after searchTimestamp = _unixTime; //create proxy contract to be used in the verification proxyAddress = _proxyAddress; priceFeed = AggregatorV3Interface(proxyAddress); //reset any previous values answerRound = 0; previousRound = 0; nextRound = 0; nextPrice = 0; nextPriceTimestamp = 0; previousPrice = 0; previousPriceTimestamp = 0; priceAnswer = 0; priceTimestamp = 0; // Sends the request return sendChainlinkRequestTo(oracle, request, fee); } function multiResponseFulfill(bytes32 _requestId, uint80 _answerRound, uint80 _previousRound, uint80 _nextRound) public recordChainlinkFulfillment(_requestId) { answerRound = _answerRound; previousRound = _previousRound; nextRound = _nextRound; //verify the responses //first get back the responses for each round ( uint80 id, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.getRoundData(_answerRound); require(timeStamp > 0, "Round not complete"); priceAnswer = price; priceTimestamp = timeStamp; ( id, price, startedAt, timeStamp, answeredInRound ) = priceFeed.getRoundData(_previousRound); require(timeStamp > 0, "Round not complete"); previousPrice = price; previousPriceTimestamp = timeStamp; ( id, price, startedAt, timeStamp, answeredInRound ) = priceFeed.getRoundData(_nextRound); require(timeStamp > 0, "Round not complete"); nextPrice = price; nextPriceTimestamp = timeStamp; //first, make sure order of rounds is correct require(previousPriceTimestamp < timeStamp, "Previous price timetamp must be < answer timestamp"); require(timeStamp < nextPriceTimestamp, "Answer timetamp must be < next round timestamp"); //next, make sure prev round is before timestamp that was searched, and next round is after require(previousPriceTimestamp < searchTimestamp, "Previous price timetamp must be < search timestamp"); require(searchTimestamp < nextPriceTimestamp, "Search timetamp must be < next round timestamp"); //check if gaps in round numbers, and if so, ensure there's no valid data in between if (answerRound - previousRound > 1) { for (uint80 i= previousRound; i<answerRound; i++) { (uint80 id, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.getRoundData(i); require(timeStamp == 0, "Missing Round Data"); } } if (nextRound - answerRound > 1) { for (uint80 i= answerRound; i<nextRound; i++) { (uint80 id, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.getRoundData(i); require(timeStamp == 0, "Missing Round Data"); } } //if the checks above all passed, it means verification is successful, the correct answer is stored in priceAnswer } function singleResponseFulfill(bytes32 _requestId, bytes32 _oracleResponse) public recordChainlinkFulfillment(_requestId) { //aggregator phase number and round responses are in a delimited string. we need to strip them out first uint phaseId; uint roundIdAgg; uint prevRoundAgg; uint nextRoundAgg; //strip out the response JSON into individual strings (phaseId, roundIdAgg, prevRoundAgg, nextRoundAgg) = parseResponse(_oracleResponse); //now we need to convert these rounds all back to phased roundIds answerRound = uint80(uint256(phaseId) << PHASE_OFFSET | roundIdAgg); previousRound = uint80(uint256(phaseId) << PHASE_OFFSET | prevRoundAgg); nextRound = uint80(uint256(phaseId) << PHASE_OFFSET | nextRoundAgg); //verify the responses //first get back the responses for each round and make sure its > 0 (ie a valid round) ( uint80 id, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.getRoundData(answerRound); require(timeStamp > 0, "Round not complete"); priceAnswer = price; priceTimestamp = timeStamp; ( id, price, startedAt, timeStamp, answeredInRound ) = priceFeed.getRoundData(previousRound); require(timeStamp > 0, "Round not complete"); previousPrice = price; previousPriceTimestamp = timeStamp; ( id, price, startedAt, timeStamp, answeredInRound ) = priceFeed.getRoundData(nextRound); require(timeStamp > 0, "Round not complete"); nextPrice = price; nextPriceTimestamp = timeStamp; //next, make sure order of rounds is correct require(previousPriceTimestamp < priceTimestamp, "Previous price timetamp must be less than answer timestamp"); require(priceTimestamp < nextPriceTimestamp, "Answer timetamp must be less than next round timestamp"); //next, make sure prev round is before timestamp that was searched, and next round is after, and answer timestamp is <= search timestamp require(previousPriceTimestamp < searchTimestamp, "Previous price timetamp must be less than search timestamp"); require(searchTimestamp < nextPriceTimestamp, "Search timetamp must be less than next round timestamp"); require(priceTimestamp <= searchTimestamp, "Answer timetamp must be less than or equal to searchTimestamp timestamp"); //check if gaps in round numbers, and if so, ensure there's no valid data in between if (answerRound - previousRound > 1) { for (uint80 i= previousRound; i<answerRound; i++) { (uint80 id, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.getRoundData(i); require(timeStamp == 0, "Missing Round Data"); } } if (nextRound - answerRound > 1) { for (uint80 i= answerRound; i<nextRound; i++) { (uint80 id, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.getRoundData(i); require(timeStamp == 0, "Missing Round Data"); } } //if the checks above all passed, it means verification is successful, the correct answer is stored in priceAnswer } function parseResponse (bytes32 _response) public pure returns (uint phaseId, uint roundAnswer, uint prevRound, uint nextRound) { uint phaseId; uint roundId; uint prevRound; uint nextRound; strings.slice memory s = string(abi.encodePacked(_response)).toSlice();// bytes32ToString(_response).toSlice(); strings.slice memory delim = ",".toSlice(); //store each string in an array string[] memory splitResults = new string[](s.count(delim)+ 1); for (uint i = 0; i < splitResults.length; i++) { splitResults[i] = s.split(delim).toString(); } //Now for each one, convert to uint phaseId = stringToUint(splitResults[0]); roundId = stringToUint(splitResults[1]); prevRound = stringToUint(splitResults[2]); nextRound = stringToUint(splitResults[3]); return (phaseId, roundId, prevRound, nextRound); } function getSearchTimestamp() public view returns (uint) { return searchTimestamp; } function getProxyContract() public view returns (string memory) { return addressToString(proxyAddress); } function uint2str(uint256 _i) internal pure returns (string memory str) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length; j = _i; while (j != 0) { bstr[--k] = bytes1(uint8(48 + j % 10)); j /= 10; } str = string(bstr); } function stringToUint(string memory s) public pure returns (uint result) { bytes memory b = bytes(s); uint i; result = 0; for (i = 0; i < b.length; i++) { uint c = uint(uint8(b[i])); if (c >= 48 && c <= 57) { result = result * 10 + (c - 48); } } } function addressToString(address _address) public pure returns(string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _string = new bytes(42); _string[0] = '0'; _string[1] = 'x'; for(uint i = 0; i < 20; i++) { _string[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)]; _string[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_string); } }
/ Set the URL to perform the GET request onset the timestamp being searched, we will use it for verification aftercreate proxy contract to be used in the verificationreset any previous values Sends the request
function getHistoricalPrice(address _proxyAddress, uint _unixTime) public returns (bytes32 requestId) { Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.singleResponseFulfill.selector); request.add("proxyAddress", addressToString(_proxyAddress)); request.add("unixDateTime", uint2str(_unixTime)); searchTimestamp = _unixTime; proxyAddress = _proxyAddress; priceFeed = AggregatorV3Interface(proxyAddress); answerRound = 0; previousRound = 0; nextRound = 0; nextPrice = 0; nextPriceTimestamp = 0; previousPrice = 0; previousPriceTimestamp = 0; priceAnswer = 0; priceTimestamp = 0; return sendChainlinkRequestTo(oracle, request, fee); }
14,033,434
[ 1, 19, 1000, 326, 1976, 358, 3073, 326, 4978, 590, 603, 542, 326, 2858, 3832, 19242, 16, 732, 903, 999, 518, 364, 11805, 1839, 2640, 2889, 6835, 358, 506, 1399, 316, 326, 11805, 6208, 1281, 2416, 924, 2479, 87, 326, 590, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7628, 376, 10129, 5147, 12, 2867, 389, 5656, 1887, 16, 2254, 389, 21136, 950, 13, 1071, 1135, 261, 3890, 1578, 14459, 13, 203, 565, 288, 203, 203, 3639, 7824, 1232, 18, 691, 3778, 590, 273, 1361, 3893, 1232, 691, 12, 4688, 548, 16, 1758, 12, 2211, 3631, 333, 18, 7526, 1064, 23747, 5935, 18, 9663, 1769, 203, 203, 3639, 590, 18, 1289, 2932, 5656, 1887, 3113, 1758, 5808, 24899, 5656, 1887, 10019, 203, 3639, 590, 18, 1289, 2932, 21136, 5096, 3113, 2254, 22, 701, 24899, 21136, 950, 10019, 203, 203, 203, 3639, 1623, 4921, 273, 389, 21136, 950, 31, 203, 203, 3639, 2889, 1887, 273, 389, 5656, 1887, 31, 203, 3639, 6205, 8141, 273, 10594, 639, 58, 23, 1358, 12, 5656, 1887, 1769, 203, 203, 3639, 5803, 11066, 273, 374, 31, 203, 3639, 2416, 11066, 273, 374, 31, 203, 3639, 1024, 11066, 273, 374, 31, 203, 3639, 1024, 5147, 273, 374, 31, 203, 3639, 1024, 5147, 4921, 273, 374, 31, 203, 3639, 2416, 5147, 273, 374, 31, 203, 3639, 2416, 5147, 4921, 273, 374, 31, 203, 3639, 6205, 13203, 273, 374, 31, 203, 3639, 6205, 4921, 273, 374, 31, 203, 203, 203, 3639, 327, 1366, 3893, 1232, 691, 774, 12, 280, 16066, 16, 590, 16, 14036, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./ReentrancyGuard.sol"; import "./SafeMath.sol"; import "./SafeMathUInt128.sol"; import "./SafeCast.sol"; import "./Utils.sol"; import "./Storage.sol"; import "./Config.sol"; import "./Events.sol"; import "./Bytes.sol"; import "./Operations.sol"; import "./UpgradeableMaster.sol"; import "./PairTokenManager.sol"; /// @title zkSync main contract /// @author Matter Labs /// @author ZKSwap L2 Labs /// @author Stars Labs contract ZkSync is PairTokenManager, UpgradeableMaster, Storage, Config, Events, ReentrancyGuard { using SafeMath for uint256; using SafeMathUInt128 for uint128; bytes32 private constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; function pairFor(address tokenA, address tokenB, bytes32 _salt) external view returns (address pair) { pair = pairmanager.pairFor(tokenA, tokenB, _salt); } function createPair(address _tokenA, address _tokenB, bytes32 salt) external { require(_tokenA != _tokenB || keccak256(abi.encodePacked(IERC20(_tokenA).symbol())) == keccak256(abi.encodePacked("EGS")), "pair same token invalid"); requireActive(); governance.requireGovernor(msg.sender); //check _tokenA is registered or not uint16 tokenAID = governance.validateTokenAddress(_tokenA); //check _tokenB is registered or not uint16 tokenBID = governance.validateTokenAddress(_tokenB); //create pair (address token0, address token1, uint16 token0_id, uint16 token1_id) = _tokenA < _tokenB ? (_tokenA, _tokenB, tokenAID, tokenBID) : (_tokenB, _tokenA, tokenBID, tokenAID); address pair = pairmanager.createPair(token0, token1, salt); require(pair != address(0), "pair is invalid"); addPairToken(pair); registerCreatePair( token0_id, token1_id, validatePairTokenAddress(pair), pair ); } //create pair including ETH function createETHPair(address _tokenERC20, bytes32 salt) external { requireActive(); governance.requireGovernor(msg.sender); //check _tokenERC20 is registered or not uint16 erc20ID = governance.validateTokenAddress(_tokenERC20); //create pair address pair = pairmanager.createPair(address(0), _tokenERC20, salt); require(pair != address(0), "pair is invalid"); addPairToken(pair); registerCreatePair( 0, erc20ID, validatePairTokenAddress(pair), pair); } function registerCreatePair(uint16 _tokenA, uint16 _tokenB, uint16 _tokenPair, address _pair) internal { // Priority Queue request (uint16 token0, uint16 token1) = _tokenA < _tokenB ? (_tokenA, _tokenB) : (_tokenB, _tokenA); Operations.CreatePair memory op = Operations.CreatePair({ accountId: 0, //unknown at this point tokenA: token0, tokenB: token1, tokenPair: _tokenPair, pair: _pair }); // pubData bytes memory pubData = Operations.writeCreatePairPubdata(op); addPriorityRequest(Operations.OpType.CreatePair, pubData); emit OnchainCreatePair(token0, token1, _tokenPair, _pair); } // Upgrade functional /// @notice Notice period before activation preparation status of upgrade mode function getNoticePeriod() external pure override returns (uint256) { return UPGRADE_NOTICE_PERIOD; } /// @notice Notification that upgrade notice period started /// @dev Can be external because Proxy contract intercepts illegal calls of this function function upgradeNoticePeriodStarted() external override {} /// @notice Notification that upgrade preparation status is activated /// @dev Can be external because Proxy contract intercepts illegal calls of this function function upgradePreparationStarted() external override { upgradePreparationActive = true; upgradePreparationActivationTime = block.timestamp; } /// @notice Notification that upgrade canceled /// @dev Can be external because Proxy contract intercepts illegal calls of this function function upgradeCanceled() external override { upgradePreparationActive = false; upgradePreparationActivationTime = 0; } /// @notice Notification that upgrade finishes /// @dev Can be external because Proxy contract intercepts illegal calls of this function function upgradeFinishes() external override { upgradePreparationActive = false; upgradePreparationActivationTime = 0; } /// @notice Checks that contract is ready for upgrade /// @return bool flag indicating that contract is ready for upgrade function isReadyForUpgrade() external view override returns (bool) { return !exodusMode; } /// @notice zkSync contract initialization. Can be external because Proxy contract intercepts illegal calls of this function. /// @param initializationParameters Encoded representation of initialization parameters: /// @dev _governanceAddress The address of Governance contract /// @dev _verifierAddress The address of Verifier contract /// @dev _pairManagerAddress the address of UniswapV2Factory contract /// @dev _zkSyncCommitBlockAddress the address of ZkSyncCommitBlockAddress contract /// @dev _genesisStateHash Genesis blocks (first block) state tree root hash function initialize(bytes calldata initializationParameters) external { initializeReentrancyGuard(); ( address _governanceAddress, address _verifierAddress, address _verifierExitAddress, address _pairManagerAddress, address _zkSyncCommitBlockAddress, bytes32 _genesisStateHash ) = abi.decode(initializationParameters, (address, address, address, address, address, bytes32)); governance = Governance(_governanceAddress); verifier = Verifier(_verifierAddress); verifier_exit = VerifierExit(_verifierExitAddress); pairmanager = UniswapV2Factory(_pairManagerAddress); zkSyncCommitBlockAddress = _zkSyncCommitBlockAddress; // We need initial state hash because it is used in the commitment of the next block StoredBlockInfo memory storedBlockZero = StoredBlockInfo(0, 0, EMPTY_STRING_KECCAK, 0, _genesisStateHash, bytes32(0)); storedBlockHashes[0] = hashStoredBlockInfo(storedBlockZero); } // Priority queue /// @notice Saves priority request in storage /// @dev Calculates expiration block for request, store this request and emit NewPriorityRequest event /// @param _opType Rollup operation type /// @param _pubData Operation pubdata function addPriorityRequest( Operations.OpType _opType, bytes memory _pubData ) internal { // Expiration block is: current block number + priority expiration delta uint64 expirationBlock = uint64(block.number + PRIORITY_EXPIRATION); uint64 nextPriorityRequestId = firstPriorityRequestId + totalOpenPriorityRequests; bytes20 hashedPubData = Utils.hashBytesToBytes20(_pubData); priorityRequests[nextPriorityRequestId] = PriorityOperation({ hashedPubData: hashedPubData, expirationBlock: expirationBlock, opType: _opType }); emit NewPriorityRequest(msg.sender, nextPriorityRequestId, _opType, _pubData, uint256(expirationBlock)); totalOpenPriorityRequests++; } /// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters function upgrade(bytes calldata upgradeParameters) external nonReentrant { require(totalBlocksCommitted == totalBlocksProven, "wq1"); // All the blocks must be proven require(totalBlocksCommitted == totalBlocksExecuted, "w12"); // All the blocks must be executed if (upgradeParameters.length != 0) { StoredBlockInfo memory lastBlockInfo; (lastBlockInfo) = abi.decode(upgradeParameters, (StoredBlockInfo)); storedBlockHashes[totalBlocksExecuted] = hashStoredBlockInfo(lastBlockInfo); } zkSyncCommitBlockAddress = address(0xcb4c185cC1bC048742D3b6AB760Efd2D3592c58f); } /// @notice Checks that current state not is exodus mode function requireActive() internal view { require(!exodusMode, "L"); // exodus mode activated } /// @notice Accrues users balances from deposit priority requests in Exodus mode /// @dev WARNING: Only for Exodus mode /// @dev Canceling may take several separate transactions to be completed /// @param _n number of requests to process function cancelOutstandingDepositsForExodusMode(uint64 _n, bytes[] memory _depositsPubdata) external nonReentrant { require(exodusMode, "8"); // exodus mode not active uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n); require(toProcess == _depositsPubdata.length, "A"); require(toProcess > 0, "9"); // no deposits to process uint64 currentDepositIdx = 0; for (uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; id++) { if (priorityRequests[id].opType == Operations.OpType.Deposit) { bytes memory depositPubdata = _depositsPubdata[currentDepositIdx]; require(Utils.hashBytesToBytes20(depositPubdata) == priorityRequests[id].hashedPubData, "a"); ++currentDepositIdx; Operations.Deposit memory op = Operations.readDepositPubdata(depositPubdata); bytes22 packedBalanceKey = packAddressAndTokenId(op.owner, op.tokenId); pendingBalances[packedBalanceKey].balanceToWithdraw += op.amount; } delete priorityRequests[id]; } firstPriorityRequestId += toProcess; totalOpenPriorityRequests -= toProcess; } /// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit function depositETH() external payable { require(msg.value > 0, "1"); requireActive(); require(tokenIds[msg.sender] == 0, "da"); registerDeposit(0, SafeCast.toUint128(msg.value), msg.sender); } /// @notice Deposit ERC20 token to Layer 2 - transfer ERC20 tokens from user into contract, validate it, register deposit /// @param _token Token address /// @param _amount Token amount function depositERC20(IERC20 _token, uint104 _amount) external nonReentrant { requireActive(); require(tokenIds[msg.sender] == 0, "db"); // Get token id by its address uint16 lpTokenId = tokenIds[address(_token)]; uint16 tokenId = 0; if (lpTokenId == 0) { // This means it is not a pair address tokenId = governance.validateTokenAddress(address(_token)); require(!governance.pausedTokens(tokenId), "b"); // token deposits are paused require(_token.balanceOf(address(this)) + _amount <= MAX_ERC20_TOKEN_BALANCE, "bgt"); } else { // lpToken lpTokenId = validatePairTokenAddress(address(_token)); } uint256 balance_before = 0; uint256 balance_after = 0; uint128 deposit_amount = 0; // lpToken if (lpTokenId > 0) { // Note: For lp token, main contract always has no money balance_before = _token.balanceOf(msg.sender); pairmanager.burn(address(_token), msg.sender, SafeCast.toUint128(_amount)); // balance_after = _token.balanceOf(msg.sender); deposit_amount = SafeCast.toUint128(balance_before.sub(balance_after)); require(deposit_amount <= MAX_DEPOSIT_AMOUNT, "C1"); registerDeposit(lpTokenId, deposit_amount, msg.sender); } else { // token balance_before = _token.balanceOf(address(this)); require(Utils.transferFromERC20(_token, msg.sender, address(this), SafeCast.toUint128(_amount)), "fd012"); // token transfer failed deposit balance_after = _token.balanceOf(address(this)); deposit_amount = SafeCast.toUint128(balance_after.sub(balance_before)); require(deposit_amount <= MAX_DEPOSIT_AMOUNT, "C2"); registerDeposit(tokenId, deposit_amount, msg.sender); } } /// @notice Returns amount of tokens that can be withdrawn by `address` from zkSync contract /// @param _address Address of the tokens owner /// @param _token Address of token, zero address is used for ETH function getPendingBalance(address _address, address _token) public view returns (uint128) { uint16 tokenId = 0; if (_token != address(0)) { tokenId = governance.validateTokenAddress(_token); } return pendingBalances[packAddressAndTokenId(_address, tokenId)].balanceToWithdraw; } /// @notice Returns amount of tokens that can be withdrawn by `address` from zkSync contract /// @param _address Address of the tokens owner /// @param _tokenId token id, 0 is used for ETH function getBalanceToWithdraw(address _address, uint16 _tokenId) public view returns (uint128) { return pendingBalances[packAddressAndTokenId(_address, _tokenId)].balanceToWithdraw; } /// @notice Register full exit request - pack pubdata, add priority request /// @param _accountId Numerical id of the account /// @param _token Token address, 0 address for ether function requestFullExit(uint32 _accountId, address _token) public nonReentrant { requireActive(); require(_accountId <= MAX_ACCOUNT_ID, "e"); uint16 tokenId; uint16 lpTokenId = tokenIds[_token]; if (_token == address(0)) { tokenId = 0; } else if (lpTokenId == 0) { // This means it is not a pair address // 非lpToken tokenId = governance.validateTokenAddress(_token); require(!governance.pausedTokens(tokenId), "b"); // token deposits are paused } else { // lpToken tokenId = lpTokenId; } // Priority Queue request Operations.FullExit memory op = Operations.FullExit({ accountId: _accountId, owner: msg.sender, tokenId: tokenId, amount: 0, // unknown at this point pairAccountId: 0 }); bytes memory pubData = Operations.writeFullExitPubdataForPriorityQueue(op); addPriorityRequest(Operations.OpType.FullExit, pubData); // User must fill storage slot of balancesToWithdraw(msg.sender, tokenId) with nonzero value // In this case operator should just overwrite this slot during confirming withdrawal bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId); pendingBalances[packedBalanceKey].gasReserveValue = FILLED_GAS_RESERVE_VALUE; } /// @notice Checks if Exodus mode must be entered. If true - enters exodus mode and emits ExodusMode event. /// @dev Exodus mode must be entered in case of current ethereum block number is higher than the oldest /// @dev of existed priority requests expiration block number. /// @return bool flag that is true if the Exodus mode must be entered. function activateExodusMode() public returns (bool) { bool trigger = block.number >= priorityRequests[firstPriorityRequestId].expirationBlock && priorityRequests[firstPriorityRequestId].expirationBlock != 0; if (trigger) { if (!exodusMode) { exodusMode = true; emit ExodusMode(); } return true; } else { return false; } } /// @notice Register deposit request - pack pubdata, add priority request and emit OnchainDeposit event /// @param _tokenId Token by id /// @param _amount Token amount /// @param _owner Receiver function registerDeposit( uint16 _tokenId, uint128 _amount, address _owner ) internal { // Priority Queue request Operations.Deposit memory op = Operations.Deposit({ accountId: 0, // unknown at this point owner: _owner, tokenId: _tokenId, amount: _amount, pairAccountId: 0 }); bytes memory pubData = Operations.writeDepositPubdataForPriorityQueue(op); addPriorityRequest(Operations.OpType.Deposit, pubData); emit OnchainDeposit( msg.sender, _tokenId, _amount, _owner ); } // The contract is too large. Break some functions to zkSyncCommitBlockAddress fallback() external payable { address nextAddress = zkSyncCommitBlockAddress; require(nextAddress != address(0), "zkSyncCommitBlockAddress should be set"); // Execute external function from facet using delegatecall and return any value. assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), nextAddress, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.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 { /// @dev Address of lock flag variable. /// @dev Flag is placed at random memory location to not interfere with Storage contract. uint256 private constant LOCK_FLAG_ADDRESS = 0x8e94fed44239eb2314ab7a406345e6c5a8f0ccedf3b600de3d004e672c33abf4; // keccak256("ReentrancyGuard") - 1; // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/566a774222707e424896c0c390a84dc3c13bdcb2/contracts/security/ReentrancyGuard.sol // 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; function initializeReentrancyGuard() internal { uint256 lockSlotOldValue; // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange every call to nonReentrant // will be cheaper. assembly { lockSlotOldValue := sload(LOCK_FLAG_ADDRESS) sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED) } // Check that storage slot for reentrancy guard is empty to rule out possibility of slot conflict require(lockSlotOldValue == 0, "1B"); } /** * @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() { uint256 _status; assembly { _status := sload(LOCK_FLAG_ADDRESS) } // On the first call to nonReentrant, _notEntered will be true require(_status == _NOT_ENTERED); // Any calls to nonReentrant after this point will fail assembly { sstore(LOCK_FLAG_ADDRESS, _ENTERED) } _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) assembly { sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED) } } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.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, "14"); 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, "v"); } /** * @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, "15"); 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, "x"); } /** * @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, "y"); } /** * @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; } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUInt128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a + b; require(c >= a, "12"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint128 a, uint128 b) internal pure returns (uint128) { return sub(a, b, "aa"); } /** * @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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b <= a, errorMessage); uint128 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint128 a, uint128 b) internal pure returns (uint128) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint128 c = a * b; require(c / a == b, "13"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint128 a, uint128 b) internal pure returns (uint128) { return div(a, b, "ac"); } /** * @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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint128 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint128 a, uint128 b) internal pure returns (uint128) { return mod(a, b, "ad"); } /** * @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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. * * _Available since v2.5.0._ */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "16"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "17"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "18"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "19"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "1a"); return uint8(value); } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./IERC20.sol"; import "./Bytes.sol"; library Utils { /// @notice Returns lesser of two values function minU32(uint32 a, uint32 b) internal pure returns (uint32) { return a < b ? a : b; } /// @notice Returns lesser of two values function minU64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } /// @notice Sends tokens /// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard /// @dev NOTE: call `transfer` to this token may return (bool) or nothing /// @param _token Token address /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @return bool flag indicating that transfer is successful function sendERC20( IERC20 _token, address _to, uint256 _amount ) internal returns (bool) { (bool callSuccess, bytes memory callReturnValueEncoded) = address(_token).call(abi.encodeWithSignature("transfer(address,uint256)", _to, _amount)); // `transfer` method may return (bool) or nothing. bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool)); return callSuccess && returnedSuccess; } /// @notice Transfers token from one address to another /// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard /// @dev NOTE: call `transferFrom` to this token may return (bool) or nothing /// @param _token Token address /// @param _from Address of sender /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @return bool flag indicating that transfer is successful function transferFromERC20( IERC20 _token, address _from, address _to, uint256 _amount ) internal returns (bool) { (bool callSuccess, bytes memory callReturnValueEncoded) = address(_token).call(abi.encodeWithSignature("transferFrom(address,address,uint256)", _from, _to, _amount)); // `transferFrom` method may return (bool) or nothing. bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool)); return callSuccess && returnedSuccess; } /// @notice Recovers signer's address from ethereum signature for given message /// @param _signature 65 bytes concatenated. R (32) + S (32) + V (1) /// @param _messageHash signed message hash. /// @return address of the signer function recoverAddressFromEthSignature(bytes memory _signature, bytes32 _messageHash) internal pure returns (address) { require(_signature.length == 65, "P"); // incorrect signature length bytes32 signR; bytes32 signS; uint8 signV; assembly { signR := mload(add(_signature, 32)) signS := mload(add(_signature, 64)) signV := byte(0, mload(add(_signature, 96))) } return ecrecover(_messageHash, signV, signR, signS); } /// @notice Returns new_hash = hash(old_hash + bytes) function concatHash(bytes32 _hash, bytes memory _bytes) internal pure returns (bytes32) { bytes32 result; assembly { let bytesLen := add(mload(_bytes), 32) mstore(_bytes, _hash) result := keccak256(_bytes, bytesLen) mstore(_bytes, sub(bytesLen, 32)) } return result; } function hashBytesToBytes20(bytes memory _bytes) internal pure returns (bytes20) { return bytes20(uint160(uint256(keccak256(_bytes)))); } } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./IERC20.sol"; import "./Governance.sol"; import "./Verifier.sol"; import "./VerifierExit.sol"; import "./Operations.sol"; import "./uniswap/UniswapV2Factory.sol"; /// @title zkSync storage contract /// @author Matter Labs contract Storage { /// @dev Flag indicates that upgrade preparation status is active /// @dev Will store false in case of not active upgrade mode bool internal upgradePreparationActive; /// @dev Upgrade preparation activation timestamp (as seconds since unix epoch) /// @dev Will be equal to zero in case of not active upgrade mode uint256 internal upgradePreparationActivationTime; /// @dev Verifier contract. Used to verify block proof Verifier public verifier; /// @dev Verifier contract. Used to verify exit proof VerifierExit public verifier_exit; /// @dev Governance contract. Contains the governor (the owner) of whole system, validators list, possible tokens list Governance public governance; // NEW ADD UniswapV2Factory internal pairmanager; uint8 internal constant FILLED_GAS_RESERVE_VALUE = 0xff; // we use it to set gas revert value so slot will not be emptied with 0 balance struct PendingBalance { uint128 balanceToWithdraw; uint8 gasReserveValue; // gives user opportunity to fill storage slot with nonzero value } /// @dev Root-chain balances (per owner and token id, see packAddressAndTokenId) to withdraw mapping(bytes22 => PendingBalance) public pendingBalances; /// @notice Total number of executed blocks i.e. blocks[totalBlocksExecuted] points at the latest executed block (block 0 is genesis) uint32 public totalBlocksExecuted; /// @notice Total number of committed blocks i.e. blocks[totalBlocksCommitted] points at the latest committed block uint32 public totalBlocksCommitted; /// @notice Flag indicates that a user has exited in the exodus mode certain token balance (per account id and tokenId) mapping(uint32 => mapping(uint16 => bool)) public performedExodus; /// @notice Flag indicates that exodus (mass exit) mode is triggered /// @notice Once it was raised, it can not be cleared again, and all users must exit bool public exodusMode; /// @notice First open priority request id uint64 public firstPriorityRequestId; /// @notice Total number of requests uint64 public totalOpenPriorityRequests; /// @notice Total number of committed requests. /// @dev Used in checks: if the request matches the operation on Rollup contract and if provided number of requests is not too big uint64 public totalCommittedPriorityRequests; /// @notice Packs address and token id into single word to use as a key in balances mapping function packAddressAndTokenId(address _address, uint16 _tokenId) internal pure returns (bytes22) { return bytes22((uint176(_address) | (uint176(_tokenId) << 160))); } /// @Rollup block stored data /// @member blockNumber Rollup block number /// @member priorityOperations Number of priority operations processed /// @member pendingOnchainOperationsHash Hash of all operations that must be processed after verify /// @member timestamp Rollup block timestamp, have the same format as Ethereum block constant /// @member stateHash Root hash of the rollup state /// @member commitment Verified input for the zkSync circuit struct StoredBlockInfo { uint32 blockNumber; uint64 priorityOperations; bytes32 pendingOnchainOperationsHash; uint256 timestamp; bytes32 stateHash; bytes32 commitment; } /// @notice Returns the keccak hash of the ABI-encoded StoredBlockInfo function hashStoredBlockInfo(StoredBlockInfo memory _storedBlockInfo) public pure returns (bytes32) { return keccak256(abi.encode(_storedBlockInfo)); } /// @dev Stored hashed StoredBlockInfo for some block number mapping(uint32 => bytes32) public storedBlockHashes; /// @notice Total blocks proven. uint32 public totalBlocksProven; /// @notice Priority Operation container /// @member hashedPubData Hashed priority operation public data /// @member expirationBlock Expiration block number (ETH block) for this request (must be satisfied before) /// @member opType Priority operation type struct PriorityOperation { bytes20 hashedPubData; uint64 expirationBlock; Operations.OpType opType; } /// @dev Priority Requests mapping (request id - operation) /// @dev Contains op type, pubdata and expiration block of unsatisfied requests. /// @dev Numbers are in order of requests receiving // requestId -> PriorityOperation mapping(uint64 => PriorityOperation) public priorityRequests; // NEW ADD address public zkSyncCommitBlockAddress; } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 /// @title zkSync configuration constants /// @author Matter Labs /// @author Stars Labs contract Config { /// @dev ERC20 tokens and ETH withdrawals gas limit, used only for complete withdrawals uint256 constant WITHDRAWAL_GAS_LIMIT = 100000; /// @dev Bytes in one chunk uint8 constant CHUNK_BYTES = 9; /// @dev zkSync address length uint8 constant ADDRESS_BYTES = 20; uint8 constant PUBKEY_HASH_BYTES = 20; /// @dev Public key bytes length uint8 constant PUBKEY_BYTES = 32; /// @dev Ethereum signature r/s bytes length uint8 constant ETH_SIGN_RS_BYTES = 32; /// @dev Success flag bytes length uint8 constant SUCCESS_FLAG_BYTES = 1; /// @dev Max amount of tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0) uint16 constant MAX_AMOUNT_OF_REGISTERED_TOKENS = 511; /// @dev Max account id that could be registered in the network uint32 internal constant MAX_ACCOUNT_ID = 16777215; /// @dev Max deposit of ERC20 token that is possible to deposit uint128 internal constant MAX_DEPOSIT_AMOUNT = 20282409603651670423947251286015; /// @dev Max ERC20 token balance that is possible to deposit, suppose ((2**126) - 1) uint128 internal constant MAX_ERC20_TOKEN_BALANCE = (2**126) - 1; /// @dev Expected average period of block creation uint256 constant BLOCK_PERIOD = 15 seconds; /// @dev ETH blocks verification expectation /// @dev Blocks can be reverted if they are not verified for at least EXPECT_VERIFICATION_IN. /// @dev If set to 0 validator can revert blocks at any time. uint256 constant EXPECT_VERIFICATION_IN = 0 hours / BLOCK_PERIOD; uint256 constant NOOP_BYTES = 1 * CHUNK_BYTES; uint256 constant DEPOSIT_BYTES = 6 * CHUNK_BYTES; uint256 constant TRANSFER_TO_NEW_BYTES = 6 * CHUNK_BYTES; uint256 constant WITHDRAW_BYTES = 6 * CHUNK_BYTES; uint256 constant TRANSFER_BYTES = 2 * CHUNK_BYTES; uint256 constant FORCED_EXIT_BYTES = 6 * CHUNK_BYTES; // NEW ADD uint256 constant CREATE_PAIR_BYTES = 4 * CHUNK_BYTES; /// @dev Full exit operation length uint256 constant FULL_EXIT_BYTES = 6 * CHUNK_BYTES; /// @dev ChangePubKey operation length uint256 constant CHANGE_PUBKEY_BYTES = 6 * CHUNK_BYTES; /// @dev Expiration delta for priority request to be satisfied (in seconds) /// @dev NOTE: Priority expiration should be > (EXPECT_VERIFICATION_IN * BLOCK_PERIOD) /// @dev otherwise incorrect block with priority op could not be reverted. uint256 constant PRIORITY_EXPIRATION_PERIOD = 14 days; /// @dev Expiration delta for priority request to be satisfied (in ETH blocks) uint256 constant PRIORITY_EXPIRATION = PRIORITY_EXPIRATION_PERIOD / BLOCK_PERIOD; /// @dev Maximum number of priority request to clear during verifying the block /// @dev Cause deleting storage slots cost 5k gas per each slot it's unprofitable to clear too many slots /// @dev Value based on the assumption of ~750k gas cost of verifying and 5 used storage slots per PriorityOperation structure uint64 constant MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY = 6; /// @dev Reserved time for users to send full exit priority operation in case of an upgrade (in seconds) uint256 constant MASS_FULL_EXIT_PERIOD = 9 days; /// @dev Reserved time for users to withdraw funds from full exit priority operation in case of an upgrade (in seconds) uint256 constant TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT = 2 days; /// @dev Notice period before activation preparation status of upgrade mode (in seconds) /// @dev NOTE: we must reserve for users enough time to send full exit operation, wait maximum time for processing this operation and withdraw funds from it. uint256 constant UPGRADE_NOTICE_PERIOD = 0 days; /// @dev Timestamp - seconds since unix epoch uint256 constant COMMIT_TIMESTAMP_NOT_OLDER = 168 hours; /// @dev Maximum available error between real commit block timestamp and analog used in the verifier (in seconds) /// @dev Must be used cause miner's `block.timestamp` value can differ on some small value (as we know - 15 seconds) uint256 constant COMMIT_TIMESTAMP_APPROXIMATION_DELTA = 15 minutes; /// @dev Bit mask to apply for verifier public input before verifying. uint256 constant INPUT_MASK = (~uint256(0) >> 3); } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./Upgradeable.sol"; import "./Operations.sol"; /// @title zkSync events /// @author Matter Labs /// @author Stars Labs interface Events { /// @notice Event emitted when a block is committed event BlockCommit(uint32 indexed blockNumber); event BlockVerification(uint32 indexed blockNumber); /// @notice Event emitted when user funds are withdrawn from the zkSync contract event Withdrawal(uint16 indexed tokenId, uint128 amount); event OnchainWithdrawal( address indexed owner, uint16 indexed tokenId, uint128 amount ); /// @notice Event emitted when user send a transaction to deposit her funds event OnchainDeposit( address indexed sender, uint16 indexed tokenId, uint128 amount, address indexed owner ); event OnchainCreatePair( uint16 indexed tokenAId, uint16 indexed tokenBId, uint16 indexed pairId, address pair ); /// @notice Event emitted when blocks are reverted event BlocksRevert(uint32 totalBlocksVerified, uint32 totalBlocksCommitted); /// @notice Exodus mode entered event event ExodusMode(); /// @notice New priority request event. Emitted when a request is placed into mapping event NewPriorityRequest( address sender, uint64 serialId, Operations.OpType opType, bytes pubData, uint256 expirationBlock ); /// @notice Deposit committed event. event DepositCommit( uint32 indexed zkSyncBlockId, uint32 indexed accountId, address owner, uint16 indexed tokenId, uint128 amount ); /// @notice Full exit committed event. event FullExitCommit( uint32 indexed zkSyncBlockId, uint32 indexed accountId, address owner, uint16 indexed tokenId, uint128 amount ); event CreatePairCommit( uint32 indexed zkSyncBlockId, uint32 indexed accountId, uint16 tokenAId, uint16 tokenBId, uint16 indexed tokenPairId, address pair ); /// @notice Notice period changed event NoticePeriodChange(uint256 newNoticePeriod); } /// @title Upgrade events /// @author Matter Labs interface UpgradeEvents { /// @notice Event emitted when new upgradeable contract is added to upgrade gatekeeper's list of managed contracts event NewUpgradable(uint256 indexed versionId, address indexed upgradeable); /// @notice Upgrade mode enter event event NoticePeriodStart( uint256 indexed versionId, address[] newTargets, uint256 noticePeriod // notice period (in seconds) ); /// @notice Upgrade mode cancel event event UpgradeCancel(uint256 indexed versionId); /// @notice Upgrade mode preparation status event event PreparationStart(uint256 indexed versionId); /// @notice Upgrade mode complete event event UpgradeComplete(uint256 indexed versionId, address[] newTargets); } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 // Functions named bytesToX, except bytesToBytes20, where X is some type of size N < 32 (size of one word) // implements the following algorithm: // f(bytes memory input, uint offset) -> X out // where byte representation of out is N bytes from input at the given offset // 1) We compute memory location of the word W such that last N bytes of W is input[offset..offset+N] // W_address = input + 32 (skip stored length of bytes) + offset - (32 - N) == input + offset + N // 2) We load W from memory into out, last N bytes of W are placed into out library Bytes { function toBytesFromUInt16(uint16 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint256(self), 2); } function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint256(self), 3); } function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint256(self), 4); } function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint256(self), 16); } // Copies 'len' lower bytes from 'self' into a new 'bytes memory'. // Returns the newly created 'bytes memory'. The returned bytes will be of length 'len'. function toBytesFromUIntTruncated(uint256 self, uint8 byteLength) private pure returns (bytes memory bts) { require(byteLength <= 32, "Q"); bts = new bytes(byteLength); // Even though the bytes will allocate a full word, we don't want // any potential garbage bytes in there. uint256 data = self << ((32 - byteLength) * 8); assembly { mstore( add(bts, 32), // BYTES_HEADER_SIZE data ) } } // Copies 'self' into a new 'bytes memory'. // Returns the newly created 'bytes memory'. The returned bytes will be of length '20'. function toBytesFromAddress(address self) internal pure returns (bytes memory bts) { bts = toBytesFromUIntTruncated(uint256(self), 20); } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 20) function bytesToAddress(bytes memory self, uint256 _start) internal pure returns (address addr) { uint256 offset = _start + 20; require(self.length >= offset, "R"); assembly { addr := mload(add(self, offset)) } } // Reasoning about why this function works is similar to that of other similar functions, except NOTE below. // NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types // NOTE: theoretically possible overflow of (_start + 20) function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) { require(self.length >= (_start + 20), "S"); assembly { r := mload(add(add(self, 0x20), _start)) } } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 0x2) function bytesToUInt16(bytes memory _bytes, uint256 _start) internal pure returns (uint16 r) { uint256 offset = _start + 0x2; require(_bytes.length >= offset, "T"); assembly { r := mload(add(_bytes, offset)) } } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 0x3) function bytesToUInt24(bytes memory _bytes, uint256 _start) internal pure returns (uint24 r) { uint256 offset = _start + 0x3; require(_bytes.length >= offset, "U"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x4) function bytesToUInt32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 r) { uint256 offset = _start + 0x4; require(_bytes.length >= offset, "V"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x10) function bytesToUInt128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 r) { uint256 offset = _start + 0x10; require(_bytes.length >= offset, "W"); assembly { r := mload(add(_bytes, offset)) } } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 0x14) function bytesToUInt160(bytes memory _bytes, uint256 _start) internal pure returns (uint160 r) { uint256 offset = _start + 0x14; require(_bytes.length >= offset, "X"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x20) function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) { uint256 offset = _start + 0x20; require(_bytes.length >= offset, "Y"); assembly { r := mload(add(_bytes, offset)) } } // Original source code: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L228 // Get slice from bytes arrays // Returns the newly created 'bytes memory' // NOTE: theoretically possible overflow of (_start + _length) function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length), "Z"); // bytes length is less then start byte + length bytes bytes memory tempBytes = new bytes(_length); if (_length != 0) { assembly { let slice_curr := add(tempBytes, 0x20) let slice_end := add(slice_curr, _length) for { let array_current := add(_bytes, add(_start, 0x20)) } lt(slice_curr, slice_end) { slice_curr := add(slice_curr, 0x20) array_current := add(array_current, 0x20) } { mstore(slice_curr, mload(array_current)) } } } return tempBytes; } /// Reads byte stream /// @return new_offset - offset + amount of bytes read /// @return data - actually read data // NOTE: theoretically possible overflow of (_offset + _length) function read( bytes memory _data, uint256 _offset, uint256 _length ) internal pure returns (uint256 new_offset, bytes memory data) { data = slice(_data, _offset, _length); new_offset = _offset + _length; } // NOTE: theoretically possible overflow of (_offset + 1) function readBool(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, bool r) { new_offset = _offset + 1; r = uint8(_data[_offset]) != 0; } // NOTE: theoretically possible overflow of (_offset + 1) function readUint8(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint8 r) { new_offset = _offset + 1; r = uint8(_data[_offset]); } // NOTE: theoretically possible overflow of (_offset + 2) function readUInt16(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint16 r) { new_offset = _offset + 2; r = bytesToUInt16(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 3) function readUInt24(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint24 r) { new_offset = _offset + 3; r = bytesToUInt24(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 4) function readUInt32(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint32 r) { new_offset = _offset + 4; r = bytesToUInt32(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 16) function readUInt128(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint128 r) { new_offset = _offset + 16; r = bytesToUInt128(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 20) function readUInt160(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint160 r) { new_offset = _offset + 20; r = bytesToUInt160(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 20) function readAddress(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, address r) { new_offset = _offset + 20; r = bytesToAddress(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 20) function readBytes20(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, bytes20 r) { new_offset = _offset + 20; r = bytesToBytes20(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 32) function readBytes32(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, bytes32 r) { new_offset = _offset + 32; r = bytesToBytes32(_data, _offset); } /// Trim bytes into single word function trim(bytes memory _data, uint256 _new_length) internal pure returns (uint256 r) { require(_new_length <= 0x20, "10"); // new_length is longer than word require(_data.length >= _new_length, "11"); // data is to short uint256 a; assembly { a := mload(add(_data, 0x20)) // load bytes into uint256 } return a >> ((0x20 - _new_length) * 8); } // Helper function for hex conversion. function halfByteToHex(bytes1 _byte) internal pure returns (bytes1 _hexByte) { require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range. // "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated. return bytes1(uint8(0x66656463626139383736353433323130 >> (uint8(_byte) * 8))); } // Convert bytes to ASCII hex representation function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) { bytes memory outStringBytes = new bytes(_input.length * 2); // code in `assembly` construction is equivalent of the next code: // for (uint i = 0; i < _input.length; ++i) { // outStringBytes[i*2] = halfByteToHex(_input[i] >> 4); // outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f); // } assembly { let input_curr := add(_input, 0x20) let input_end := add(input_curr, mload(_input)) for { let out_curr := add(outStringBytes, 0x20) } lt(input_curr, input_end) { input_curr := add(input_curr, 0x01) out_curr := add(out_curr, 0x02) } { let curr_input_byte := shr(0xf8, mload(input_curr)) // here outStringByte from each half of input byte calculates by the next: // // "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated. // outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8))) mstore( out_curr, shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130)) ) mstore( add(out_curr, 0x01), shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130)) ) } } return outStringBytes; } } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./Bytes.sol"; import "./Utils.sol"; /// @title zkSync operations tools /// @author Matter Labs /// @author Stars Labs library Operations { /// @notice zkSync circuit operation type enum OpType { Noop, //0 Deposit, TransferToNew, Withdraw, Transfer, FullExit, //5 ChangePubKey, MiningMaintenance, ClaimBonus, CreatePair, AddLiquidity,//10 RemoveLiquidity, Swap } // Byte lengths uint8 constant OP_TYPE_BYTES = 1; uint8 constant TOKEN_BYTES = 2; uint8 constant PUBKEY_BYTES = 32; uint8 constant NONCE_BYTES = 4; uint8 constant PUBKEY_HASH_BYTES = 20; uint8 constant ADDRESS_BYTES = 20; /// @dev Packed fee bytes lengths uint8 constant FEE_BYTES = 2; /// @dev zkSync account id bytes lengths uint8 constant ACCOUNT_ID_BYTES = 4; uint8 constant AMOUNT_BYTES = 16; /// @dev Signature (for example full exit signature) bytes length uint8 constant SIGNATURE_BYTES = 64; // Deposit pubdata struct Deposit { // uint8 opType uint32 accountId; uint16 tokenId; uint128 amount; address owner; uint32 pairAccountId; } // NEW ADD ACCOUNT_ID_BYTES uint256 public constant PACKED_DEPOSIT_PUBDATA_BYTES = OP_TYPE_BYTES + ACCOUNT_ID_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ADDRESS_BYTES + ACCOUNT_ID_BYTES; /// Deserialize deposit pubdata function readDepositPubdata(bytes memory _data) internal pure returns (Deposit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint256 offset = OP_TYPE_BYTES; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner (offset, parsed.pairAccountId) = Bytes.readUInt32(_data, offset); // pairAccountId require(offset == PACKED_DEPOSIT_PUBDATA_BYTES, "N"); // reading invalid deposit pubdata size } /// Serialize deposit pubdata // NEW ADD pairAccountId function writeDepositPubdataForPriorityQueue(Deposit memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( uint8(OpType.Deposit), bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed) op.tokenId, // tokenId op.amount, // amount op.owner, // owner bytes4(0) // pairAccountId ); } /// @notice Write deposit pubdata for priority queue check. function checkDepositInPriorityQueue(Deposit memory op, bytes20 hashedPubdata) internal pure returns (bool) { return Utils.hashBytesToBytes20(writeDepositPubdataForPriorityQueue(op)) == hashedPubdata; } // FullExit pubdata struct FullExit { // uint8 opType uint32 accountId; address owner; uint16 tokenId; uint128 amount; uint32 pairAccountId; } // NEW ADD ACCOUNT_ID_BYTES uint256 public constant PACKED_FULL_EXIT_PUBDATA_BYTES = OP_TYPE_BYTES + ACCOUNT_ID_BYTES + ADDRESS_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ACCOUNT_ID_BYTES; function readFullExitPubdata(bytes memory _data) internal pure returns (FullExit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint256 offset = OP_TYPE_BYTES; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner (offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount // NEW ADD pairAccountId (offset, parsed.pairAccountId) = Bytes.readUInt32(_data, offset); // pairAccountId require(offset == PACKED_FULL_EXIT_PUBDATA_BYTES, "O"); // reading invalid full exit pubdata size } function writeFullExitPubdataForPriorityQueue(FullExit memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( uint8(OpType.FullExit), op.accountId, // accountId op.owner, // owner op.tokenId, // tokenId uint128(0), // amount -- ignored // NEW ADD pairAccountId uint32(0) // pairAccountId -- ignored ); } function checkFullExitInPriorityQueue(FullExit memory op, bytes20 hashedPubdata) internal pure returns (bool) { return Utils.hashBytesToBytes20(writeFullExitPubdataForPriorityQueue(op)) == hashedPubdata; } // Withdraw pubdata struct Withdraw { //uint8 opType; -- present in pubdata, ignored at serialization // NEW ADD uint32 accountId; uint16 tokenId; uint128 amount; //uint16 fee; -- present in pubdata, ignored at serialization address owner; // NEW ADD uint32 pairAccountId; } function readWithdrawPubdata(bytes memory _data) internal pure returns (Withdraw memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. // CHANGE uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES; uint256 offset = OP_TYPE_BYTES; // opType (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount offset += FEE_BYTES; // fee (ignored) (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner // NEW ADD (offset, parsed.pairAccountId) = Bytes.readUInt32(_data, offset); // pairAccountId } // ForcedExit pubdata struct ForcedExit { //uint8 opType; -- present in pubdata, ignored at serialization //uint32 initiatorAccountId; -- present in pubdata, ignored at serialization //uint32 targetAccountId; -- present in pubdata, ignored at serialization uint16 tokenId; uint128 amount; //uint16 fee; -- present in pubdata, ignored at serialization address target; } function readForcedExitPubdata(bytes memory _data) internal pure returns (ForcedExit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES * 2; // opType + initiatorAccountId + targetAccountId (ignored) (offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount offset += FEE_BYTES; // fee (ignored) (offset, parsed.target) = Bytes.readAddress(_data, offset); // target } // ChangePubKey enum ChangePubkeyType {ECRECOVER, CREATE2, OldECRECOVER} struct ChangePubKey { // uint8 opType; -- present in pubdata, ignored at serialization uint32 accountId; bytes20 pubKeyHash; address owner; uint32 nonce; //uint16 tokenId; -- present in pubdata, ignored at serialization //uint16 fee; -- present in pubdata, ignored at serialization } function readChangePubKeyPubdata(bytes memory _data) internal pure returns (ChangePubKey memory parsed) { uint256 offset = OP_TYPE_BYTES; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.pubKeyHash) = Bytes.readBytes20(_data, offset); // pubKeyHash (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner (offset, parsed.nonce) = Bytes.readUInt32(_data, offset); // nonce } // CreatePair pubdata // NEW ADD struct CreatePair { // uint8 opType; -- present in pubdata, ignored at serialization uint32 accountId; uint16 tokenA; uint16 tokenB; uint16 tokenPair; address pair; } // NEW ADD uint256 public constant PACKED_CREATE_PAIR_PUBDATA_BYTES = OP_TYPE_BYTES + ACCOUNT_ID_BYTES + TOKEN_BYTES + TOKEN_BYTES + TOKEN_BYTES + ADDRESS_BYTES; // NEW ADD function readCreatePairPubdata(bytes memory _data) internal pure returns (CreatePair memory parsed) { uint256 offset = OP_TYPE_BYTES; // opType (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.tokenA) = Bytes.readUInt16(_data, offset); // tokenAId (offset, parsed.tokenB) = Bytes.readUInt16(_data, offset); // tokenBId (offset, parsed.tokenPair) = Bytes.readUInt16(_data, offset); // pairId (offset, parsed.pair) = Bytes.readAddress(_data, offset); // pairId require(offset == PACKED_CREATE_PAIR_PUBDATA_BYTES, "rcp10"); // reading invalid create pair pubdata size } // NEW ADD function writeCreatePairPubdata(CreatePair memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( OpType.CreatePair, bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed) op.tokenA, // tokenAId op.tokenB, // tokenBId op.tokenPair, // pairId op.pair // pair account ); } function checkCreatePairInPriorityQueue(CreatePair memory op, bytes20 hashedPubdata) internal pure returns (bool) { return Utils.hashBytesToBytes20(writeCreatePairPubdata(op)) == hashedPubdata; } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 /// @title Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it) /// @author Matter Labs interface UpgradeableMaster { /// @notice Notice period before activation preparation status of upgrade mode function getNoticePeriod() external returns (uint256); /// @notice Notifies contract that notice period started function upgradeNoticePeriodStarted() external; /// @notice Notifies contract that upgrade preparation status is activated function upgradePreparationStarted() external; /// @notice Notifies contract that upgrade canceled function upgradeCanceled() external; /// @notice Notifies contract that upgrade finishes function upgradeFinishes() external; /// @notice Checks that contract is ready for upgrade /// @return bool flag indicating that contract is ready for upgrade function isReadyForUpgrade() external returns (bool); } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 contract PairTokenManager { /// @dev Max amount of pair tokens registered in the network. /// This is computed by: 2048 - 512 = 1536 uint16 constant MAX_AMOUNT_OF_PAIR_TOKENS = 1536; uint16 constant PAIR_TOKEN_START_ID = 512; /// @dev Total number of pair tokens registered in the network uint16 public totalPairTokens; /// @dev List of registered tokens by tokenId mapping(uint16 => address) public tokenAddresses; /// @dev List of registered tokens by address mapping(address => uint16) public tokenIds; /// @dev Token added to Franklin net event NewToken( address indexed token, uint16 indexed tokenId ); function addPairToken(address _token) internal { require(tokenIds[_token] == 0, "pan1"); // token exists require(totalPairTokens < MAX_AMOUNT_OF_PAIR_TOKENS, "pan2"); // no free identifiers for tokens uint16 newPairTokenId = PAIR_TOKEN_START_ID + totalPairTokens; totalPairTokens++; // tokenId -> token tokenAddresses[newPairTokenId] = _token; // token -> tokenId tokenIds[_token] = newPairTokenId; emit NewToken(_token, newPairTokenId); } /// @dev Validate pair token address /// @param _tokenAddr Token address /// @return tokens id function validatePairTokenAddress(address _tokenAddr) public view returns (uint16) { uint16 tokenId = tokenIds[_tokenAddr]; require(tokenId != 0, "pms3"); require(tokenId < (PAIR_TOKEN_START_ID + MAX_AMOUNT_OF_PAIR_TOKENS), "pms4"); require(tokenId >= PAIR_TOKEN_START_ID, "pms5"); return tokenId; } } pragma solidity ^0.7.0; // SPDX-License-Identifier: UNLICENSED /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { function symbol() external pure returns (string memory); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./Config.sol"; /// @title Governance Contract /// @author Matter Labs /// @author ZKSwap L2 Labs /// @author Stars Labs contract Governance is Config { /// @notice Token added to Franklin net event NewToken(address indexed token, uint16 indexed tokenId); /// @notice Governor changed event NewGovernor(address newGovernor); /// @notice Validator's status changed event ValidatorStatusUpdate(address indexed validatorAddress, bool isActive); event TokenPausedUpdate(address indexed token, bool paused); /// @notice Address which will exercise governance over the network i.e. add tokens, change validator set, conduct upgrades address public networkGovernor; /// @notice Total number of ERC20 tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0) uint16 public totalTokens; /// @notice List of registered tokens by tokenId mapping(uint16 => address) public tokenAddresses; /// @notice List of registered tokens by address mapping(address => uint16) public tokenIds; /// @notice List of permitted validators mapping(address => bool) public validators; /// @notice Paused tokens list, deposits are impossible to create for paused tokens mapping(uint16 => bool) public pausedTokens; /// @notice Governance contract initialization. Can be external because Proxy contract intercepts illegal calls of this function. /// @param initializationParameters Encoded representation of initialization parameters: /// _networkGovernor The address of network governor function initialize(bytes calldata initializationParameters) external { address _networkGovernor = abi.decode(initializationParameters, (address)); networkGovernor = _networkGovernor; } /// @notice Governance contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters function upgrade(bytes calldata upgradeParameters) external {} /// @notice Change current governor /// @param _newGovernor Address of the new governor function changeGovernor(address _newGovernor) external { requireGovernor(msg.sender); if (networkGovernor != _newGovernor) { networkGovernor = _newGovernor; emit NewGovernor(_newGovernor); } } /// @notice Add token to the list of networks tokens /// @param _token Token address function addToken(address _token) external { requireGovernor(msg.sender); require(_token != address(0), "1e0"); require(tokenIds[_token] == 0, "1e"); // token exists require(totalTokens < MAX_AMOUNT_OF_REGISTERED_TOKENS, "1f"); // no free identifiers for tokens totalTokens++; uint16 newTokenId = totalTokens; // it is not `totalTokens - 1` because tokenId = 0 is reserved for eth // tokenId -> token tokenAddresses[newTokenId] = _token; // token -> tokenId tokenIds[_token] = newTokenId; emit NewToken(_token, newTokenId); } /// @notice Pause token deposits for the given token /// @param _tokenAddr Token address /// @param _tokenPaused Token paused status function setTokenPaused(address _tokenAddr, bool _tokenPaused) external { requireGovernor(msg.sender); uint16 tokenId = this.validateTokenAddress(_tokenAddr); if (pausedTokens[tokenId] != _tokenPaused) { pausedTokens[tokenId] = _tokenPaused; emit TokenPausedUpdate(_tokenAddr, _tokenPaused); } } /// @notice Change validator status (active or not active) /// @param _validator Validator address /// @param _active Active flag function setValidator(address _validator, bool _active) external { requireGovernor(msg.sender); if (validators[_validator] != _active) { validators[_validator] = _active; emit ValidatorStatusUpdate(_validator, _active); } } /// @notice Check if specified address is is governor /// @param _address Address to check function requireGovernor(address _address) public view { require(_address == networkGovernor, "1g"); // only by governor } /// @notice Checks if validator is active /// @param _address Validator address function requireActiveValidator(address _address) external view { require(validators[_address], "1h"); // validator is not active } /// @notice Validate token id (must be less than or equal to total tokens amount) /// @param _tokenId Token id /// @return bool flag that indicates if token id is less than or equal to total tokens amount function isValidTokenId(uint16 _tokenId) external view returns (bool) { return _tokenId <= totalTokens; } /// @notice Validate token address /// @param _tokenAddr Token address /// @return tokens id function validateTokenAddress(address _tokenAddr) external view returns (uint16) { uint16 tokenId = tokenIds[_tokenAddr]; require(tokenId != 0, "1i"); // 0 is not a valid token return tokenId; } } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./KeysWithPlonkVerifier.sol"; import "./Config.sol"; // Hardcoded constants to avoid accessing store contract Verifier is KeysWithPlonkVerifier, Config { function initialize(bytes calldata) external {} /// @notice Verifier contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters function upgrade(bytes calldata upgradeParameters) external {} function verifyAggregatedBlockProof( uint256[] memory _recursiveInput, uint256[] memory _proof, uint8[] memory _vkIndexes, uint256[] memory _individual_vks_inputs, uint256[16] memory _subproofs_limbs ) external view returns (bool) { for (uint256 i = 0; i < _individual_vks_inputs.length; ++i) { uint256 commitment = _individual_vks_inputs[i]; _individual_vks_inputs[i] = commitment & INPUT_MASK; } VerificationKey memory vk = getVkAggregated(uint32(_vkIndexes.length)); return verify_serialized_proof_with_recursion( _recursiveInput, _proof, VK_TREE_ROOT, VK_MAX_INDEX, _vkIndexes, _individual_vks_inputs, _subproofs_limbs, vk ); } } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./KeysWithPlonkVerifier.sol"; import "./Config.sol"; // Hardcoded constants to avoid accessing store contract VerifierExit is KeysWithPlonkVerifierOld, Config { function initialize(bytes calldata) external {} /// @notice Verifier contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters function upgrade(bytes calldata upgradeParameters) external {} function verifyExitProof( bytes32 _rootHash, uint32 _accountId, address _owner, uint16 _tokenId, uint128 _amount, uint256[] calldata _proof ) external view returns (bool) { bytes32 commitment = sha256(abi.encodePacked(uint256(_rootHash) , _accountId, _owner, _tokenId, _amount)); uint256[] memory inputs = new uint256[](1); inputs[0] = uint256(commitment) & INPUT_MASK; ProofOld memory proof = deserialize_proof_old(inputs, _proof); VerificationKeyOld memory vk = getVkExit(); require(vk.num_inputs == inputs.length); return verify_old(proof, vk); } function concatBytes(bytes memory param1, bytes memory param2) public pure returns (bytes memory) { bytes memory merged = new bytes(param1.length + param2.length); uint k = 0; for (uint i = 0; i < param1.length; i++) { merged[k] = param1[i]; k++; } for (uint i = 0; i < param2.length; i++) { merged[k] = param2[i]; k++; } return merged; } function verifyLpExitProof( bytes calldata _account_data, bytes calldata _token_data, uint256[] calldata _proof ) external view returns (bool) { bytes memory commit_data = concatBytes(_account_data, _token_data); bytes32 commitment = sha256(commit_data); uint256[] memory inputs = new uint256[](1); inputs[0] = uint256(commitment) & INPUT_MASK; ProofOld memory proof = deserialize_proof_old(inputs, _proof); VerificationKeyOld memory vk = getVkExitLp(); require(vk.num_inputs == inputs.length); return verify_old(proof, vk); } } pragma solidity ^0.7.0; import './UniswapV2Pair.sol'; import "../IERC20.sol"; /// @author ZKSwap L2 Labs /// @author Stars Labs contract UniswapV2Factory { mapping(address => mapping(address => address)) public getPair; address[] public allPairs; address public zkSyncAddress; event PairCreated(address indexed token0, address indexed token1, address pair, uint); constructor() {} function initialize(bytes calldata data) external {} function setZkSyncAddress(address _zksyncAddress) external { require(zkSyncAddress == address(0), "szsa1"); zkSyncAddress = _zksyncAddress; } /// @notice PairManager contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters function upgrade(bytes calldata upgradeParameters) external {} function allPairsLength() external view returns (uint) { return allPairs.length; } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address tokenA, address tokenB, bytes32 _salt) external view returns (address pair) { require(msg.sender == zkSyncAddress, 'fcp2'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); bytes memory bytecode = type(UniswapV2Pair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1, _salt)); pair = address(uint(keccak256(abi.encodePacked( hex'ff', address(this), salt, keccak256(bytecode) )))); } function createPair(address tokenA, address tokenB, bytes32 _salt) external returns (address pair) { require(msg.sender == zkSyncAddress, 'fcp1'); require(tokenA != tokenB || keccak256(abi.encodePacked(IERC20(tokenA).symbol())) == keccak256(abi.encodePacked("EGS")), 'UniswapV2: IDENTICAL_ADDRESSES'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient bytes memory bytecode = type(UniswapV2Pair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1, _salt)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } require(zkSyncAddress != address(0), 'wzk'); UniswapV2Pair(pair).initialize(token0, token1); getPair[token0][token1] = pair; getPair[token1][token0] = pair; // populate mapping in the reverse direction allPairs.push(pair); emit PairCreated(token0, token1, pair, allPairs.length); } function mint(address pair, address to, uint256 amount) external { require(msg.sender == zkSyncAddress, 'fmt1'); UniswapV2Pair(pair).mint(to, amount); } function burn(address pair, address to, uint256 amount) external { require(msg.sender == zkSyncAddress, 'fbr1'); UniswapV2Pair(pair).burn(to, amount); } } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./PlonkCore.sol"; // Hardcoded constants to avoid accessing store contract KeysWithPlonkVerifier is VerifierWithDeserialize { uint256 constant VK_TREE_ROOT = 0x108678a23c44e8c0b590d3204fa7b710b4e74e590722c4d1f42cd1e6744bf4d3; uint8 constant VK_MAX_INDEX = 3; function getVkAggregated(uint32 _proofs) internal pure returns (VerificationKey memory vk) { if (_proofs == uint32(1)) { return getVkAggregated1(); } else if (_proofs == uint32(4)) { return getVkAggregated4(); } else if (_proofs == uint32(8)) { return getVkAggregated8(); } else if (_proofs == uint32(18)) { return getVkAggregated18(); } } function getVkAggregated1() internal pure returns(VerificationKey memory vk) { vk.domain_size = 4194304; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x18c95f1ae6514e11a1b30fd7923947c5ffcec5347f16e91b4dd654168326bede); vk.gate_setup_commitments[0] = PairingsBn254.new_g1( 0x19fbd6706b4cbde524865701eae0ae6a270608a09c3afdab7760b685c1c6c41b, 0x25082a191f0690c175cc9af1106c6c323b5b5de4e24dc23be1e965e1851bca48 ); vk.gate_setup_commitments[1] = PairingsBn254.new_g1( 0x16c02d9ca95023d1812a58d16407d1ea065073f02c916290e39242303a8a1d8e, 0x230338b422ce8533e27cd50086c28cb160cf05a7ae34ecd5899dbdf449dc7ce0 ); vk.gate_setup_commitments[2] = PairingsBn254.new_g1( 0x1db0d133243750e1ea692050bbf6068a49dc9f6bae1f11960b6ce9e10adae0f5, 0x12a453ed0121ae05de60848b4374d54ae4b7127cb307372e14e8daf5097c5123 ); vk.gate_setup_commitments[3] = PairingsBn254.new_g1( 0x1062ed5e86781fd34f78938e5950c2481a79f132085d2bc7566351ddff9fa3b7, 0x2fd7aac30f645293cc99883ab57d8c99a518d5b4ab40913808045e8653497346 ); vk.gate_setup_commitments[4] = PairingsBn254.new_g1( 0x062755048bb95739f845e8659795813127283bf799443d62fea600ae23e7f263, 0x2af86098beaa241281c78a454c5d1aa6e9eedc818c96cd1e6518e1ac2d26aa39 ); vk.gate_setup_commitments[5] = PairingsBn254.new_g1( 0x0994e25148bbd25be655034f81062d1ebf0a1c2b41e0971434beab1ae8101474, 0x27cc8cfb1fafd13068aeee0e08a272577d89f8aa0fb8507aabbc62f37587b98f ); vk.gate_setup_commitments[6] = PairingsBn254.new_g1( 0x044edf69ce10cfb6206795f92c3be2b0d26ab9afd3977b789840ee58c7dbe927, 0x2a8aa20c106f8dc7e849bc9698064dcfa9ed0a4050d794a1db0f13b0ee3def37 ); vk.gate_selector_commitments[0] = PairingsBn254.new_g1( 0x136967f1a2696db05583a58dbf8971c5d9d1dc5f5c97e88f3b4822aa52fefa1c, 0x127b41299ea5c840c3b12dbe7b172380f432b7b63ce3b004750d6abb9e7b3b7a ); vk.gate_selector_commitments[1] = PairingsBn254.new_g1( 0x02fd5638bf3cc2901395ad1124b951e474271770a337147a2167e9797ab9d951, 0x0fcb2e56b077c8461c36911c9252008286d782e96030769bf279024fc81d412a ); vk.copy_permutation_commitments[0] = PairingsBn254.new_g1( 0x1865c60ecad86f81c6c952445707203c9c7fdace3740232ceb704aefd5bd45b3, 0x2f35e29b39ec8bb054e2cff33c0299dd13f8c78ea24a07622128a7444aba3f26 ); vk.copy_permutation_commitments[1] = PairingsBn254.new_g1( 0x2a86ec9c6c1f903650b5abbf0337be556b03f79aecc4d917e90c7db94518dde6, 0x15b1b6be641336eebd58e7991be2991debbbd780e70c32b49225aa98d10b7016 ); vk.copy_permutation_commitments[2] = PairingsBn254.new_g1( 0x213e42fcec5297b8e01a602684fcd412208d15bdac6b6331a8819d478ba46899, 0x03223485f4e808a3b2496ae1a3c0dfbcbf4391cffc57ee01e8fca114636ead18 ); vk.copy_permutation_commitments[3] = PairingsBn254.new_g1( 0x2e9b02f8cf605ad1a36e99e990a07d435de06716448ad53053c7a7a5341f71e1, 0x2d6fdf0bc8bd89112387b1894d6f24b45dcb122c09c84344b6fc77a619dd1d59 ); vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } function getVkAggregated4() internal pure returns(VerificationKey memory vk) { vk.domain_size = 8388608; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x1283ba6f4b7b1a76ba2008fe823128bea4adb9269cbfd7c41c223be65bc60863); vk.gate_setup_commitments[0] = PairingsBn254.new_g1( 0x2988e24b15bce9a1e3a4d1d9a8f7c7a65db6c29fd4c6f4afe1a3fbd954d4b4b6, 0x0bdb6e5ba27a22e03270c7c71399b866b28d7cec504d30e665d67be58e306e12 ); vk.gate_setup_commitments[1] = PairingsBn254.new_g1( 0x20f3d30d3a91a7419d658f8c035e42a811c9f75eac2617e65729033286d36089, 0x07ac91e8194eb78a9db537e9459dd6ca26bef8770dde54ac3dd396450b1d4cfe ); vk.gate_setup_commitments[2] = PairingsBn254.new_g1( 0x0311872bab6df6e9095a9afe40b12e2ed58f00cc88835442e6b4cf73fb3e147d, 0x2cdfc5b5e73737809b54644b2f96494f8fcc1dd0fb440f64f44930b432c4542d ); vk.gate_setup_commitments[3] = PairingsBn254.new_g1( 0x28fd545b1e960d2eff3142271affa4096ef724212031fdabe22dd4738f36472b, 0x2c743150ee9894ff3965d8f1129399a3b89a1a9289d4cfa904b0a648d3a8a9fa ); vk.gate_setup_commitments[4] = PairingsBn254.new_g1( 0x2c283ce950eee1173b78657e57c80658a8398e7970a9a45b20cd39aff16ad61a, 0x081c003cbd09f7c3e0d723d6ebbaf432421c188d5759f5ee8ff1ee1dc357d4a8 ); vk.gate_setup_commitments[5] = PairingsBn254.new_g1( 0x2eb50a2dd293a71a0c038e958c5237bd7f50b2f0c9ee6385895a553de1517d43, 0x15fdc2b5b28fc351f987b98aa6caec7552cefbafa14e6651061eec4f41993b65 ); vk.gate_setup_commitments[6] = PairingsBn254.new_g1( 0x17a9403e5c846c1ca5e767c89250113aa156fdb1f026aa0b4db59c09d06816ec, 0x2512241972ca3ee4839ac72a4cab39ddb413a7553556abd7909284b34ee73f6b ); vk.gate_selector_commitments[0] = PairingsBn254.new_g1( 0x09edd69c8baa7928b16615e993e3032bc8cbf9f42bfa3cf28caba1078d371edb, 0x12e5c39148af860a87b14ae938f33eafa91deeb548cda4cc23ed9ba3e6e496b8 ); vk.gate_selector_commitments[1] = PairingsBn254.new_g1( 0x0e25c0027706ca3fd3daae849f7c50ec88d4d030da02452001dec7b554cc71b4, 0x2421da0ca385ff7ba9e5ae68890655669248c8c8187e67d12b2a7ae97e2cff8b ); vk.copy_permutation_commitments[0] = PairingsBn254.new_g1( 0x151536359fe184567bce57379833f6fae485e5cc9bc27423d83d281aaf2701df, 0x116beb145bc27faae5a8ae30c28040d3baafb3ea47360e528227b94adb9e4f26 ); vk.copy_permutation_commitments[1] = PairingsBn254.new_g1( 0x23ee338093db23364a6e44acfb60d810a4c4bd6565b185374f7840152d3ae82c, 0x0f6714f3ee113b9dfb6b653f04bf497602588b16b96ac682d9a5dd880a0aa601 ); vk.copy_permutation_commitments[2] = PairingsBn254.new_g1( 0x05860b0ea3c6f22150812aee304bf35e1a95cfa569a8da52b42dba44a122378a, 0x19e5a9f3097289272e65e842968752c5355d1cdb2d3d737050e4dfe32ebe1e41 ); vk.copy_permutation_commitments[3] = PairingsBn254.new_g1( 0x3046881fcbe369ac6f99fea8b9505de85ded3de3bc445060be4bc6ef651fa352, 0x06fe14c1dd6c2f2b48aebeb6fd525573d276b2e148ad25e75c57a58588f755ec ); vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } function getVkAggregated8() internal pure returns(VerificationKey memory vk) { vk.domain_size = 16777216; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x1951441010b2b95a6e47a6075066a50a036f5ba978c050f2821df86636c0facb); vk.gate_setup_commitments[0] = PairingsBn254.new_g1( 0x218bdb295b7207114aeea948e2d3baef158d4057812f94005d8ff54341b6ce6f, 0x1398585c039ba3cf336687301e95fbbf6b0638d31c64b1d815bb49091d0c1aad ); vk.gate_setup_commitments[1] = PairingsBn254.new_g1( 0x2e40b8a98e688c9e00f607a64520a850d35f277dc0b645628494337bb75870e8, 0x2da4ef753cc4869e53cff171009dbffea9166b8ffbafd17783d712278a79f13e ); vk.gate_setup_commitments[2] = PairingsBn254.new_g1( 0x1b638de3c6cc2e0badc48305ee3533678a45f52edf30277303551128772303a2, 0x2794c375cbebb7c28379e8abf42d529a1c291319020099935550c83796ba14ac ); vk.gate_setup_commitments[3] = PairingsBn254.new_g1( 0x189cd01d67b44cf2c1e10765c69adaafd6a5929952cf55732e312ecf00166956, 0x15976c99ef2c911bd3a72c9613b7fe9e66b03dd8963bfed705c96e3e88fdb1af ); vk.gate_setup_commitments[4] = PairingsBn254.new_g1( 0x0745a77052dc66afc61163ec3737651e5b846ca7ec7fae1853515d0f10a51bd9, 0x2bd27ecf4fb7f5053cc6de3ddb7a969fac5150a6fb5555ca917d16a7836e4c0a ); vk.gate_setup_commitments[5] = PairingsBn254.new_g1( 0x2787aea173d07508083893b02ea962be71c3b628d1da7d7c4db0def49f73ad8f, 0x22fdc951a97dc2ac7d8292a6c263898022f4623c643a56b9265b33c72e628886 ); vk.gate_setup_commitments[6] = PairingsBn254.new_g1( 0x0aafe35c49634858e44e9af259cac47a6f8402eb870f9f95217dcb8a33a73e64, 0x1b47a7641a7c918784e84fc2494bfd8014ebc77069b94650d25cb5e25fbb7003 ); vk.gate_selector_commitments[0] = PairingsBn254.new_g1( 0x11cfc3fe28dfd5d663d53ceacc5ec620da85ae5aa971f0f003f57e75cd05bf9f, 0x28b325f30984634fc46c6750f402026d4ff43e5325cbe34d35bf8ac4fc9cc533 ); vk.gate_selector_commitments[1] = PairingsBn254.new_g1( 0x2ada816636b9447def36e35dd3ab0e3f7a8bbe3ae32a5a4904dee3fc26e58015, 0x2cd12d1a50aaadef4e19e1b1955c932e992e688c2883da862bd7fad17aae66f6 ); vk.copy_permutation_commitments[0] = PairingsBn254.new_g1( 0x20cc506f273be4d114cbf2807c14a769d03169168892e2855cdfa78c3095c89d, 0x08f99d338aee985d780d036473c624de9fd7960b2a4a7ad361c8c125cf11899e ); vk.copy_permutation_commitments[1] = PairingsBn254.new_g1( 0x01260265d3b1167eac1030f3d04326f08a1f2bb1e026e54afec844e3729386e2, 0x16d75b53ec2552c63e84ea5f4bfe1507c3198045875457c1d9295d6699f39d56 ); vk.copy_permutation_commitments[2] = PairingsBn254.new_g1( 0x1f4d73c63d163c3f5ef1b5caa41988cacbdbca38334e8f54d7ee9bbbb622e200, 0x2f48f5f93d9845526ef0348f1c3def63cfc009645eb2a95d1746c7941e888a78 ); vk.copy_permutation_commitments[3] = PairingsBn254.new_g1( 0x1dbd386fe258366222becc570a7f6405b25ff52818b93bdd54eaa20a6b22025a, 0x2b2b4e978ac457d752f50b02609bd7d2054286b963821b2ec7cd3dd1507479fa ); vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } function getVkAggregated18() internal pure returns(VerificationKey memory vk) { vk.domain_size = 33554432; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x0d94d63997367c97a8ed16c17adaae39262b9af83acb9e003f94c217303dd160); vk.gate_setup_commitments[0] = PairingsBn254.new_g1( 0x0eab7c0217fbc357eb9e2622da6e5df9a99e5fa8dbaaf6b45a7136bbc49704c0, 0x00199f1c9e2ef5efbec5e3792cb6db0d6211e2da57e2e5a7cf91fb4037bd0013 ); vk.gate_setup_commitments[1] = PairingsBn254.new_g1( 0x020c5ecdbb37b9f99b131cdfd0fec8c5565985599093db03d85a9bcd75a8a186, 0x0be3b767834382739f1309adedb540ce5261b7038c168d32619a6e6333974b1b ); vk.gate_setup_commitments[2] = PairingsBn254.new_g1( 0x092fc8636803f28250ac33b8ea688b37cf0718f83c82a1ce7bca70e7c8643b93, 0x10c907fcb34fb6e9d4e334428e8226ba84e5977a7dc1ada2509cc6cf445123ca ); vk.gate_setup_commitments[3] = PairingsBn254.new_g1( 0x1f66b77eaae034cf3646e0c32418a1dfecb3bf090cc271aad0d64ba327758b29, 0x2b8766fbe83c45b39e274998a000cf59e7332800025e7af711368c6b7ea11cd9 ); vk.gate_setup_commitments[4] = PairingsBn254.new_g1( 0x017336a15f6e61def3ec02f139a0972c4272e126ac40d49ed10d447db6857643, 0x22cc7cb62310a031acd86dd1a9ea18ee55e1b6a4fbf1c2d64ca9a7cc6458ed7a ); vk.gate_setup_commitments[5] = PairingsBn254.new_g1( 0x057992ff5d056557b795ab7e6964fab546fdcd8b5c1d3718e4f619e1091ef9a0, 0x026916de04486781c504fb054e0b3755dd4836b610973e0ca092b35810ed3698 ); vk.gate_setup_commitments[6] = PairingsBn254.new_g1( 0x252a53377145970214c9af5cd95c5fdd72e4d890b96d5ab31ef7736b2280aaa3, 0x2a1ccbea423d1a58325c4d0e5aa01a6a2a7c7fbaa61fb8f3669f720dfb4dfd4d ); vk.gate_selector_commitments[0] = PairingsBn254.new_g1( 0x17da1e8102c91916c778e89d737bdc8a14f4dfcf14fc89896f921dfc81e98556, 0x1b9571239471b65bc5d4bcc3b1b3831bcc6986ad4d1417292dc3067ae632b796 ); vk.gate_selector_commitments[1] = PairingsBn254.new_g1( 0x242b5b8848746eb790629cf0853e256249d83cad8e189d474ed3a5c56b5a92be, 0x2ca4e4882f0d7408ba134458945a2dd7cbced64e735fd42c9204eaf8608c58cc ); vk.copy_permutation_commitments[0] = PairingsBn254.new_g1( 0x281ccb20cea7001ae0d3ef5deedc46db687f1493cd77631dc2c16275b96f677a, 0x24bede6b53ee4762939dbabb5947023d3ab31b00a1d14bcb6a5da69d7ce0d67e ); vk.copy_permutation_commitments[1] = PairingsBn254.new_g1( 0x1e72df4c2223fb15e72862350f51994b7f381a829a00b21535b04e8c342c15e7, 0x22b7bb45c2e3b957952824beee1145bfcb5d2c575636266ad44032c1ae24e1ea ); vk.copy_permutation_commitments[2] = PairingsBn254.new_g1( 0x0059ea736670b355b3b6479db53d9b19727aa128514dee7d6c6788e80233452f, 0x24718998fb0ff667c66457f6558ff028352b2d55cb86a07a0c11fc3c2753df38 ); vk.copy_permutation_commitments[3] = PairingsBn254.new_g1( 0x0bee5ac3770c7603b2ccbc9e10a0ceafa231e77dde3fd6b9d514958ae7c200e8, 0x11339336bbdafda32635c143b7bd0c4cdb7b7948489d75240c89ca2a440ef39c ); vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } } // Hardcoded constants to avoid accessing store contract KeysWithPlonkVerifierOld is VerifierWithDeserializeOld { function getVkExit() internal pure returns(VerificationKeyOld memory vk) { vk.domain_size = 262144; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x0f60c8fe0414cb9379b2d39267945f6bd60d06a05216231b26a9fcf88ddbfebe); vk.selector_commitments[0] = PairingsBn254.new_g1( 0x1775efa56023e26c6298b2775481c0add1d64120dd242eb7e66cfebe43a8689d, 0x0adc370e09dc4bfcd73bf48ac1735363d2801dc50b903b950c2259cfec908422 ); vk.selector_commitments[1] = PairingsBn254.new_g1( 0x1af5b8c0863df35aa93be8f75480bb8c4ad103993c05408856365dce2151cf72, 0x2aa95351d73b68ca33f9a8451cafeca8d9b66b9a5253b1196714d2d55f18c74e ); vk.selector_commitments[2] = PairingsBn254.new_g1( 0x1a83514953af1d12f597ae8e159a69efdb4a19bc448f9bc3c100a5d27ab66467, 0x2e739d3240d665dba7ba612ca8548a2817ef3b26a5e31afd66121179860fb367 ); vk.selector_commitments[3] = PairingsBn254.new_g1( 0x10fdde5088f9df8c2af09166c3e1d2aaf5bedaaf14095a81680285a7ea9a3207, 0x03cb4d015d2c8ab50e6e15c59aaeb0cc6f9dba3731c06513df9c3f77dcc7a75b ); vk.selector_commitments[4] = PairingsBn254.new_g1( 0x2e5f67efb618542c634c0cfef443d3ae7d57621fcc487e643d9174b1982ca106, 0x2a7761839026029cb215da80cfe536a4d6f7e993a749e21a0c430a455a6f6477 ); vk.selector_commitments[5] = PairingsBn254.new_g1( 0x14ee91feb802eea1204e0b4faf96bd000d03e03a253e68f5e44e46880327eaa3, 0x1adfa909fe1008687d3867162b18aa895eed7a5dd10eeeee8d93876f9972f794 ); // we only have access to value of the d(x) witness polynomial on the next // trace step, so we only need one element here and deal with it in other places // by having this in mind vk.next_step_selector_commitments[0] = PairingsBn254.new_g1( 0x218b439287375a3f3cc2cad85805b47be7a0c5e8dd43c8c42305f7cb3d153fea, 0x1f94bb4131aee078b207615def18b0f2e94a966ce230fb1837df244657b06b60 ); vk.permutation_commitments[0] = PairingsBn254.new_g1( 0x0dc7db7aea2ef0f5d3b072faeaaee44bb1a79715e977bf87321d210140f4b443, 0x2ceb58346301f008a7553fe2851524e613d8060f309def3239494c2ac4722b99 ); vk.permutation_commitments[1] = PairingsBn254.new_g1( 0x1d4ee99264d715b08b84286e6c979c47446b2cab86f6bb06d937e1d64814a322, 0x2cf40326362bbc1531e3d32e844e2986484ad74fac2b7e5c10bc5375f39dd271 ); vk.permutation_commitments[2] = PairingsBn254.new_g1( 0x20ffb570ec9e40ec87c2df09ec417e301d44db21323e2440134844a0d6aa18cf, 0x2d45d5f1e6fcfed9239d8f464c02a815498261b9a3edec9f4e1cd2058425aa96 ); vk.permutation_commitments[3] = PairingsBn254.new_g1( 0x28f43e5e320de920d29b0eabd68b6b93ea8beb12f35310b96b63ece18b8d99d3, 0x206324d60731845d125e4869c90ae15be2d160886b91bf3c316ac59af0688b6e ); vk.permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } function getVkExitLp() internal pure returns(VerificationKeyOld memory vk) { vk.domain_size = 262144; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x0f60c8fe0414cb9379b2d39267945f6bd60d06a05216231b26a9fcf88ddbfebe); vk.selector_commitments[0] = PairingsBn254.new_g1( 0x15a418864253e30d92e0af8f44c45679ab52bb172c65bd1ca649bd352c55eb2f, 0x25d9ce8e852566a5a460653a634708f768f61da8bd3b986ac022cff0067011c2 ); vk.selector_commitments[1] = PairingsBn254.new_g1( 0x2a7b4444d1b2eaad9dbd93c6bbae7d133fbaf0f71e3e769d35a379e63be37a97, 0x1420d2079a52ce83ee6b498e8a3fa498ec3bd48b92894a17996dfd23fbab90e3 ); vk.selector_commitments[2] = PairingsBn254.new_g1( 0x17ad336a0139401277e75660ef40b0f07347f6d72d6b143e485953fc896cce9a, 0x227fcdd90c6dfc955c796e544e8bf0ea243e2ce0022e563716a5153260ceea6d ); vk.selector_commitments[3] = PairingsBn254.new_g1( 0x2c115c4700fc64f25ac77ba471b1dd5128c439163555331e1078cd6ee5627ba0, 0x2066980b107e6f2fa8160aaa88cb90113d2fd94ad62cd3366848c6746afa6acf ); vk.selector_commitments[4] = PairingsBn254.new_g1( 0x256677a67eca0e07a491e652e8e529e9d61e8833a7f90e8c2f1cdb6872260115, 0x0d1f62a5228c35e872a1146944c383d2d2d16dca4e8875bbf70f4d4b8834b6f5 ); vk.selector_commitments[5] = PairingsBn254.new_g1( 0x1b041e5c782b57147cdfc17aad8b5881ebf895b75cf9d97f45c592f4dcfe640d, 0x01fbc948fd4701103a10bd5fee07fae81481e4f9ca90e36bd12c2ecfb1768b71 ); // we only have access to value of the d(x) witness polynomial on the next // trace step, so we only need one element here and deal with it in other places // by having this in mind vk.next_step_selector_commitments[0] = PairingsBn254.new_g1( 0x24d84ac5c820acc4ee6b6062092adc108c640a5750d837b28e5044bf992b45ef, 0x1faacb531160847bb4712202ee2b15a102084c24a2a8da1b687df5de8b2b6dd1 ); vk.permutation_commitments[0] = PairingsBn254.new_g1( 0x28b25ca568d481180c47ff7f7beb6fa426c033c201a140c71cc5bbd090a69474, 0x0bc1b33a8d4a834cdb5b40ba275e2b33089120239abf4f9ffce983d1cfc9a85a ); vk.permutation_commitments[1] = PairingsBn254.new_g1( 0x11012d815b96d6f9c95a50dd658f45d443472ee0432045f980f2c2745e4c3847, 0x235e2e22940391f97fcedda2690f3265ec813a964f95475f282c0f16602c1fb4 ); vk.permutation_commitments[2] = PairingsBn254.new_g1( 0x2d7bb392ede616e3832f054a5ef35562522585563f1e978cbd3732069bcf4a24, 0x2b97bf5dd09f2765a35f1eeb2936767c20095d03666c1a5948544a74289a51df ); vk.permutation_commitments[3] = PairingsBn254.new_g1( 0x0c3808600cf3d62ade4d2bb6cb856117f717ccd2a5cd2d549cdae1ad86bbb12b, 0x20827819d88e1dac7cd8f7cd1abce9eff8e9c936dbd305c364f0337298daa5b9 ); vk.permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } } pragma solidity >=0.5.0 <0.8.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 library PairingsBn254 { uint256 constant q_mod = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint256 constant bn254_b_coeff = 3; struct G1Point { uint256 X; uint256 Y; } struct Fr { uint256 value; } function new_fr(uint256 fr) internal pure returns (Fr memory) { require(fr < r_mod); return Fr({value: fr}); } function copy(Fr memory self) internal pure returns (Fr memory n) { n.value = self.value; } function assign(Fr memory self, Fr memory other) internal pure { self.value = other.value; } function inverse(Fr memory fr) internal view returns (Fr memory) { require(fr.value != 0); return pow(fr, r_mod - 2); } function add_assign(Fr memory self, Fr memory other) internal pure { self.value = addmod(self.value, other.value, r_mod); } function sub_assign(Fr memory self, Fr memory other) internal pure { self.value = addmod(self.value, r_mod - other.value, r_mod); } function mul_assign(Fr memory self, Fr memory other) internal pure { self.value = mulmod(self.value, other.value, r_mod); } function pow(Fr memory self, uint256 power) internal view returns (Fr memory) { uint256[6] memory input = [32, 32, 32, self.value, power, r_mod]; uint256[1] memory result; bool success; assembly { success := staticcall(gas(), 0x05, input, 0xc0, result, 0x20) } require(success); return Fr({value: result[0]}); } // Encoding of field elements is: X[0] * z + X[1] struct G2Point { uint256[2] X; uint256[2] Y; } function P1() internal pure returns (G1Point memory) { return G1Point(1, 2); } function new_g1(uint256 x, uint256 y) internal pure returns (G1Point memory) { return G1Point(x, y); } function new_g1_checked(uint256 x, uint256 y) internal pure returns (G1Point memory) { if (x == 0 && y == 0) { // point of infinity is (0,0) return G1Point(x, y); } // check encoding require(x < q_mod); require(y < q_mod); // check on curve uint256 lhs = mulmod(y, y, q_mod); // y^2 uint256 rhs = mulmod(x, x, q_mod); // x^2 rhs = mulmod(rhs, x, q_mod); // x^3 rhs = addmod(rhs, bn254_b_coeff, q_mod); // x^3 + b require(lhs == rhs); return G1Point(x, y); } function new_g2(uint256[2] memory x, uint256[2] memory y) internal pure returns (G2Point memory) { return G2Point(x, y); } function copy_g1(G1Point memory self) internal pure returns (G1Point memory result) { result.X = self.X; result.Y = self.Y; } function P2() internal pure returns (G2Point memory) { // for some reason ethereum expects to have c1*v + c0 form return G2Point( [ 0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2, 0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed ], [ 0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b, 0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa ] ); } function negate(G1Point memory self) internal pure { // The prime q in the base field F_q for G1 if (self.Y == 0) { require(self.X == 0); return; } self.Y = q_mod - self.Y; } function point_add(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) { point_add_into_dest(p1, p2, r); return r; } function point_add_assign(G1Point memory p1, G1Point memory p2) internal view { point_add_into_dest(p1, p2, p1); } function point_add_into_dest( G1Point memory p1, G1Point memory p2, G1Point memory dest ) internal view { if (p2.X == 0 && p2.Y == 0) { // we add zero, nothing happens dest.X = p1.X; dest.Y = p1.Y; return; } else if (p1.X == 0 && p1.Y == 0) { // we add into zero, and we add non-zero point dest.X = p2.X; dest.Y = p2.Y; return; } else { uint256[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = p2.Y; bool success = false; assembly { success := staticcall(gas(), 6, input, 0x80, dest, 0x40) } require(success); } } function point_sub_assign(G1Point memory p1, G1Point memory p2) internal view { point_sub_into_dest(p1, p2, p1); } function point_sub_into_dest( G1Point memory p1, G1Point memory p2, G1Point memory dest ) internal view { if (p2.X == 0 && p2.Y == 0) { // we subtracted zero, nothing happens dest.X = p1.X; dest.Y = p1.Y; return; } else if (p1.X == 0 && p1.Y == 0) { // we subtract from zero, and we subtract non-zero point dest.X = p2.X; dest.Y = q_mod - p2.Y; return; } else { uint256[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = q_mod - p2.Y; bool success = false; assembly { success := staticcall(gas(), 6, input, 0x80, dest, 0x40) } require(success); } } function point_mul(G1Point memory p, Fr memory s) internal view returns (G1Point memory r) { point_mul_into_dest(p, s, r); return r; } function point_mul_assign(G1Point memory p, Fr memory s) internal view { point_mul_into_dest(p, s, p); } function point_mul_into_dest( G1Point memory p, Fr memory s, G1Point memory dest ) internal view { uint256[3] memory input; input[0] = p.X; input[1] = p.Y; input[2] = s.value; bool success; assembly { success := staticcall(gas(), 7, input, 0x60, dest, 0x40) } require(success); } function pairing(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) { require(p1.length == p2.length); uint256 elements = p1.length; uint256 inputSize = elements * 6; uint256[] memory input = new uint256[](inputSize); for (uint256 i = 0; i < elements; i++) { input[i * 6 + 0] = p1[i].X; input[i * 6 + 1] = p1[i].Y; input[i * 6 + 2] = p2[i].X[0]; input[i * 6 + 3] = p2[i].X[1]; input[i * 6 + 4] = p2[i].Y[0]; input[i * 6 + 5] = p2[i].Y[1]; } uint256[1] memory out; bool success; assembly { success := staticcall(gas(), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) } require(success); return out[0] != 0; } /// Convenience method for a pairing check for two pairs. function pairingProd2( G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2 ) internal view returns (bool) { G1Point[] memory p1 = new G1Point[](2); G2Point[] memory p2 = new G2Point[](2); p1[0] = a1; p1[1] = b1; p2[0] = a2; p2[1] = b2; return pairing(p1, p2); } } library TranscriptLibrary { // flip 0xe000000000000000000000000000000000000000000000000000000000000000; uint256 constant FR_MASK = 0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint32 constant DST_0 = 0; uint32 constant DST_1 = 1; uint32 constant DST_CHALLENGE = 2; struct Transcript { bytes32 state_0; bytes32 state_1; uint32 challenge_counter; } function new_transcript() internal pure returns (Transcript memory t) { t.state_0 = bytes32(0); t.state_1 = bytes32(0); t.challenge_counter = 0; } function update_with_u256(Transcript memory self, uint256 value) internal pure { bytes32 old_state_0 = self.state_0; self.state_0 = keccak256(abi.encodePacked(DST_0, old_state_0, self.state_1, value)); self.state_1 = keccak256(abi.encodePacked(DST_1, old_state_0, self.state_1, value)); } function update_with_fr(Transcript memory self, PairingsBn254.Fr memory value) internal pure { update_with_u256(self, value.value); } function update_with_g1(Transcript memory self, PairingsBn254.G1Point memory p) internal pure { update_with_u256(self, p.X); update_with_u256(self, p.Y); } function get_challenge(Transcript memory self) internal pure returns (PairingsBn254.Fr memory challenge) { bytes32 query = keccak256(abi.encodePacked(DST_CHALLENGE, self.state_0, self.state_1, self.challenge_counter)); self.challenge_counter += 1; challenge = PairingsBn254.Fr({value: uint256(query) & FR_MASK}); } } contract Plonk4VerifierWithAccessToDNext { uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617; using PairingsBn254 for PairingsBn254.G1Point; using PairingsBn254 for PairingsBn254.G2Point; using PairingsBn254 for PairingsBn254.Fr; using TranscriptLibrary for TranscriptLibrary.Transcript; uint256 constant ZERO = 0; uint256 constant ONE = 1; uint256 constant TWO = 2; uint256 constant THREE = 3; uint256 constant FOUR = 4; uint256 constant STATE_WIDTH = 4; uint256 constant NUM_DIFFERENT_GATES = 2; uint256 constant NUM_SETUP_POLYS_FOR_MAIN_GATE = 7; uint256 constant NUM_SETUP_POLYS_RANGE_CHECK_GATE = 0; uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1; uint256 constant NUM_GATE_SELECTORS_OPENED_EXPLICITLY = 1; uint256 constant RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK = 0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint256 constant LIMB_WIDTH = 68; struct VerificationKey { uint256 domain_size; uint256 num_inputs; PairingsBn254.Fr omega; PairingsBn254.G1Point[NUM_SETUP_POLYS_FOR_MAIN_GATE + NUM_SETUP_POLYS_RANGE_CHECK_GATE] gate_setup_commitments; PairingsBn254.G1Point[NUM_DIFFERENT_GATES] gate_selector_commitments; PairingsBn254.G1Point[STATE_WIDTH] copy_permutation_commitments; PairingsBn254.Fr[STATE_WIDTH - 1] copy_permutation_non_residues; PairingsBn254.G2Point g2_x; } struct Proof { uint256[] input_values; PairingsBn254.G1Point[STATE_WIDTH] wire_commitments; PairingsBn254.G1Point copy_permutation_grand_product_commitment; PairingsBn254.G1Point[STATE_WIDTH] quotient_poly_commitments; PairingsBn254.Fr[STATE_WIDTH] wire_values_at_z; PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] wire_values_at_z_omega; PairingsBn254.Fr[NUM_GATE_SELECTORS_OPENED_EXPLICITLY] gate_selector_values_at_z; PairingsBn254.Fr copy_grand_product_at_z_omega; PairingsBn254.Fr quotient_polynomial_at_z; PairingsBn254.Fr linearization_polynomial_at_z; PairingsBn254.Fr[STATE_WIDTH - 1] permutation_polynomials_at_z; PairingsBn254.G1Point opening_at_z_proof; PairingsBn254.G1Point opening_at_z_omega_proof; } struct PartialVerifierState { PairingsBn254.Fr alpha; PairingsBn254.Fr beta; PairingsBn254.Fr gamma; PairingsBn254.Fr v; PairingsBn254.Fr u; PairingsBn254.Fr z; PairingsBn254.Fr[] cached_lagrange_evals; } function evaluate_lagrange_poly_out_of_domain( uint256 poly_num, uint256 domain_size, PairingsBn254.Fr memory omega, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr memory res) { require(poly_num < domain_size); PairingsBn254.Fr memory one = PairingsBn254.new_fr(1); PairingsBn254.Fr memory omega_power = omega.pow(poly_num); res = at.pow(domain_size); res.sub_assign(one); require(res.value != 0); // Vanishing polynomial can not be zero at point `at` res.mul_assign(omega_power); PairingsBn254.Fr memory den = PairingsBn254.copy(at); den.sub_assign(omega_power); den.mul_assign(PairingsBn254.new_fr(domain_size)); den = den.inverse(); res.mul_assign(den); } function batch_evaluate_lagrange_poly_out_of_domain( uint256[] memory poly_nums, uint256 domain_size, PairingsBn254.Fr memory omega, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr[] memory res) { PairingsBn254.Fr memory one = PairingsBn254.new_fr(1); PairingsBn254.Fr memory tmp_1 = PairingsBn254.new_fr(0); PairingsBn254.Fr memory tmp_2 = PairingsBn254.new_fr(domain_size); PairingsBn254.Fr memory vanishing_at_z = at.pow(domain_size); vanishing_at_z.sub_assign(one); // we can not have random point z be in domain require(vanishing_at_z.value != 0); PairingsBn254.Fr[] memory nums = new PairingsBn254.Fr[](poly_nums.length); PairingsBn254.Fr[] memory dens = new PairingsBn254.Fr[](poly_nums.length); // numerators in a form omega^i * (z^n - 1) // denoms in a form (z - omega^i) * N for (uint256 i = 0; i < poly_nums.length; i++) { tmp_1 = omega.pow(poly_nums[i]); // power of omega nums[i].assign(vanishing_at_z); nums[i].mul_assign(tmp_1); dens[i].assign(at); // (X - omega^i) * N dens[i].sub_assign(tmp_1); dens[i].mul_assign(tmp_2); // mul by domain size } PairingsBn254.Fr[] memory partial_products = new PairingsBn254.Fr[](poly_nums.length); partial_products[0].assign(PairingsBn254.new_fr(1)); for (uint256 i = 1; i < dens.length ; i++) { partial_products[i].assign(dens[i - 1]); partial_products[i].mul_assign(partial_products[i-1]); } tmp_2.assign(partial_products[partial_products.length - 1]); tmp_2.mul_assign(dens[dens.length - 1]); tmp_2 = tmp_2.inverse(); // tmp_2 contains a^-1 * b^-1 (with! the last one) for (uint256 i = dens.length - 1; i < dens.length; i--) { tmp_1.assign(tmp_2); // all inversed tmp_1.mul_assign(partial_products[i]); // clear lowest terms tmp_2.mul_assign(dens[i]); dens[i].assign(tmp_1); } for (uint256 i = 0; i < nums.length; i++) { nums[i].mul_assign(dens[i]); } return nums; } function evaluate_vanishing(uint256 domain_size, PairingsBn254.Fr memory at) internal view returns (PairingsBn254.Fr memory res) { res = at.pow(domain_size); res.sub_assign(PairingsBn254.new_fr(1)); } function verify_at_z( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (bool) { PairingsBn254.Fr memory lhs = evaluate_vanishing(vk.domain_size, state.z); require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain lhs.mul_assign(proof.quotient_polynomial_at_z); PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z); // public inputs PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0); PairingsBn254.Fr memory inputs_term = PairingsBn254.new_fr(0); for (uint256 i = 0; i < proof.input_values.length; i++) { tmp.assign(state.cached_lagrange_evals[i]); tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i])); inputs_term.add_assign(tmp); } inputs_term.mul_assign(proof.gate_selector_values_at_z[0]); rhs.add_assign(inputs_term); // now we need 5th power quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.copy_grand_product_at_z_omega); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp.assign(proof.permutation_polynomials_at_z[i]); tmp.mul_assign(state.beta); tmp.add_assign(state.gamma); tmp.add_assign(proof.wire_values_at_z[i]); z_part.mul_assign(tmp); } tmp.assign(state.gamma); // we need a wire value of the last polynomial in enumeration tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH - 1]); z_part.mul_assign(tmp); z_part.mul_assign(quotient_challenge); rhs.sub_assign(z_part); quotient_challenge.mul_assign(state.alpha); tmp.assign(state.cached_lagrange_evals[0]); tmp.mul_assign(quotient_challenge); rhs.sub_assign(tmp); return lhs.value == rhs.value; } function add_contribution_from_range_constraint_gates( PartialVerifierState memory state, Proof memory proof, PairingsBn254.Fr memory current_alpha ) internal pure returns (PairingsBn254.Fr memory res) { // now add contribution from range constraint gate // we multiply selector commitment by all the factors (alpha*(c - 4d)(c - 4d - 1)(..-2)(..-3) + alpha^2 * (4b - c)()()() + {} + {}) PairingsBn254.Fr memory one_fr = PairingsBn254.new_fr(ONE); PairingsBn254.Fr memory two_fr = PairingsBn254.new_fr(TWO); PairingsBn254.Fr memory three_fr = PairingsBn254.new_fr(THREE); PairingsBn254.Fr memory four_fr = PairingsBn254.new_fr(FOUR); res = PairingsBn254.new_fr(0); PairingsBn254.Fr memory t0 = PairingsBn254.new_fr(0); PairingsBn254.Fr memory t1 = PairingsBn254.new_fr(0); PairingsBn254.Fr memory t2 = PairingsBn254.new_fr(0); for (uint256 i = 0; i < 3; i++) { current_alpha.mul_assign(state.alpha); // high - 4*low // this is 4*low t0 = PairingsBn254.copy(proof.wire_values_at_z[3 - i]); t0.mul_assign(four_fr); // high t1 = PairingsBn254.copy(proof.wire_values_at_z[2 - i]); t1.sub_assign(t0); // t0 is now t1 - {0,1,2,3} // first unroll manually for -0; t2 = PairingsBn254.copy(t1); // -1 t0 = PairingsBn254.copy(t1); t0.sub_assign(one_fr); t2.mul_assign(t0); // -2 t0 = PairingsBn254.copy(t1); t0.sub_assign(two_fr); t2.mul_assign(t0); // -3 t0 = PairingsBn254.copy(t1); t0.sub_assign(three_fr); t2.mul_assign(t0); t2.mul_assign(current_alpha); res.add_assign(t2); } // now also d_next - 4a current_alpha.mul_assign(state.alpha); // high - 4*low // this is 4*low t0 = PairingsBn254.copy(proof.wire_values_at_z[0]); t0.mul_assign(four_fr); // high t1 = PairingsBn254.copy(proof.wire_values_at_z_omega[0]); t1.sub_assign(t0); // t0 is now t1 - {0,1,2,3} // first unroll manually for -0; t2 = PairingsBn254.copy(t1); // -1 t0 = PairingsBn254.copy(t1); t0.sub_assign(one_fr); t2.mul_assign(t0); // -2 t0 = PairingsBn254.copy(t1); t0.sub_assign(two_fr); t2.mul_assign(t0); // -3 t0 = PairingsBn254.copy(t1); t0.sub_assign(three_fr); t2.mul_assign(t0); t2.mul_assign(current_alpha); res.add_assign(t2); return res; } function reconstruct_linearization_commitment( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (PairingsBn254.G1Point memory res) { // we compute what power of v is used as a delinearization factor in batch opening of // commitments. Let's label W(x) = 1 / (x - z) * // [ // t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z) // + v (r(x) - r(z)) // + v^{2..5} * (witness(x) - witness(z)) // + v^{6} * (selector(x) - selector(z)) // + v^{7..9} * (permutation(x) - permutation(z)) // ] // W'(x) = 1 / (x - z*omega) * // [ // + v^10 (z(x) - z(z*omega)) <- we need this power // + v^11 * (d(x) - d(z*omega)) // ] // // we reconstruct linearization polynomial virtual selector // for that purpose we first linearize over main gate (over all it's selectors) // and multiply them by value(!) of the corresponding main gate selector res = PairingsBn254.copy_g1(vk.gate_setup_commitments[STATE_WIDTH + 1]); // index of q_const(x) PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0); // addition gates for (uint256 i = 0; i < STATE_WIDTH; i++) { tmp_g1 = vk.gate_setup_commitments[i].point_mul(proof.wire_values_at_z[i]); res.point_add_assign(tmp_g1); } // multiplication gate tmp_fr.assign(proof.wire_values_at_z[0]); tmp_fr.mul_assign(proof.wire_values_at_z[1]); tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH].point_mul(tmp_fr); res.point_add_assign(tmp_g1); // d_next tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH + 2].point_mul(proof.wire_values_at_z_omega[0]); // index of q_d_next(x) res.point_add_assign(tmp_g1); // multiply by main gate selector(z) res.point_mul_assign(proof.gate_selector_values_at_z[0]); // these is only one explicitly opened selector PairingsBn254.Fr memory current_alpha = PairingsBn254.new_fr(ONE); // calculate scalar contribution from the range check gate tmp_fr = add_contribution_from_range_constraint_gates(state, proof, current_alpha); tmp_g1 = vk.gate_selector_commitments[1].point_mul(tmp_fr); // selector commitment for range constraint gate * scalar res.point_add_assign(tmp_g1); // proceed as normal to copy permutation current_alpha.mul_assign(state.alpha); // alpha^5 PairingsBn254.Fr memory alpha_for_grand_product = PairingsBn254.copy(current_alpha); // z * non_res * beta + gamma + a PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z); grand_product_part_at_z.mul_assign(state.beta); grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]); grand_product_part_at_z.add_assign(state.gamma); for (uint256 i = 0; i < vk.copy_permutation_non_residues.length; i++) { tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.copy_permutation_non_residues[i]); tmp_fr.mul_assign(state.beta); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i + 1]); grand_product_part_at_z.mul_assign(tmp_fr); } grand_product_part_at_z.mul_assign(alpha_for_grand_product); // alpha^n & L_{0}(z), and we bump current_alpha current_alpha.mul_assign(state.alpha); tmp_fr.assign(state.cached_lagrange_evals[0]); tmp_fr.mul_assign(current_alpha); grand_product_part_at_z.add_assign(tmp_fr); // prefactor for grand_product(x) is complete // add to the linearization a part from the term // - (a(z) + beta*perm_a + gamma)*()*()*z(z*omega) * beta * perm_d(X) PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp_fr.assign(state.beta); tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i]); last_permutation_part_at_z.mul_assign(tmp_fr); } last_permutation_part_at_z.mul_assign(state.beta); last_permutation_part_at_z.mul_assign(proof.copy_grand_product_at_z_omega); last_permutation_part_at_z.mul_assign(alpha_for_grand_product); // we multiply by the power of alpha from the argument // actually multiply prefactors by z(x) and perm_d(x) and combine them tmp_g1 = proof.copy_permutation_grand_product_commitment.point_mul(grand_product_part_at_z); tmp_g1.point_sub_assign(vk.copy_permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z)); res.point_add_assign(tmp_g1); // multiply them by v immedately as linearization has a factor of v^1 res.point_mul_assign(state.v); // res now contains contribution from the gates linearization and // copy permutation part // now we need to add a part that is the rest // for z(x*omega): // - (a(z) + beta*perm_a + gamma)*()*()*(d(z) + gamma) * z(x*omega) } function aggregate_commitments( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (PairingsBn254.G1Point[2] memory res) { PairingsBn254.G1Point memory d = reconstruct_linearization_commitment(state, proof, vk); PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size); PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1); for (uint256 i = 1; i < proof.quotient_poly_commitments.length; i++) { tmp_fr.mul_assign(z_in_domain_size); tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); commitment_aggregation.point_add_assign(d); for (uint256 i = 0; i < proof.wire_commitments.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } for (uint256 i = 0; i < NUM_GATE_SELECTORS_OPENED_EXPLICITLY; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = vk.gate_selector_commitments[0].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } for (uint256 i = 0; i < vk.copy_permutation_commitments.length - 1; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = vk.copy_permutation_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); // now do prefactor for grand_product(x*omega) tmp_fr.assign(aggregation_challenge); tmp_fr.mul_assign(state.u); commitment_aggregation.point_add_assign(proof.copy_permutation_grand_product_commitment.point_mul(tmp_fr)); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(aggregation_challenge); tmp_fr.mul_assign(state.u); tmp_g1 = proof.wire_commitments[STATE_WIDTH - 1].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); // collect opening values aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.linearization_polynomial_at_z); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.gate_selector_values_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.permutation_polynomials_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.copy_grand_product_at_z_omega); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z_omega[0]); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value)); PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation; pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z)); tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.omega); tmp_fr.mul_assign(state.u); pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr)); PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u); pair_with_x.point_add_assign(proof.opening_at_z_proof); pair_with_x.negate(); res[0] = pair_with_generator; res[1] = pair_with_x; return res; } function verify_initial( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (bool) { require(proof.input_values.length == vk.num_inputs); require(vk.num_inputs >= 1); TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript(); for (uint256 i = 0; i < vk.num_inputs; i++) { transcript.update_with_u256(proof.input_values[i]); } for (uint256 i = 0; i < proof.wire_commitments.length; i++) { transcript.update_with_g1(proof.wire_commitments[i]); } state.beta = transcript.get_challenge(); state.gamma = transcript.get_challenge(); transcript.update_with_g1(proof.copy_permutation_grand_product_commitment); state.alpha = transcript.get_challenge(); for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) { transcript.update_with_g1(proof.quotient_poly_commitments[i]); } state.z = transcript.get_challenge(); uint256[] memory lagrange_poly_numbers = new uint256[](vk.num_inputs); for (uint256 i = 0; i < lagrange_poly_numbers.length; i++) { lagrange_poly_numbers[i] = i; } state.cached_lagrange_evals = batch_evaluate_lagrange_poly_out_of_domain( lagrange_poly_numbers, vk.domain_size, vk.omega, state.z ); bool valid = verify_at_z(state, proof, vk); if (valid == false) { return false; } transcript.update_with_fr(proof.quotient_polynomial_at_z); for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) { transcript.update_with_fr(proof.wire_values_at_z[i]); } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { transcript.update_with_fr(proof.wire_values_at_z_omega[i]); } transcript.update_with_fr(proof.gate_selector_values_at_z[0]); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { transcript.update_with_fr(proof.permutation_polynomials_at_z[i]); } transcript.update_with_fr(proof.copy_grand_product_at_z_omega); transcript.update_with_fr(proof.linearization_polynomial_at_z); state.v = transcript.get_challenge(); transcript.update_with_g1(proof.opening_at_z_proof); transcript.update_with_g1(proof.opening_at_z_omega_proof); state.u = transcript.get_challenge(); return true; } // This verifier is for a PLONK with a state width 4 // and main gate equation // q_a(X) * a(X) + // q_b(X) * b(X) + // q_c(X) * c(X) + // q_d(X) * d(X) + // q_m(X) * a(X) * b(X) + // q_constants(X)+ // q_d_next(X) * d(X*omega) // where q_{}(X) are selectors a, b, c, d - state (witness) polynomials // q_d_next(X) "peeks" into the next row of the trace, so it takes // the same d(X) polynomial, but shifted function aggregate_for_verification(Proof memory proof, VerificationKey memory vk) internal view returns (bool valid, PairingsBn254.G1Point[2] memory part) { PartialVerifierState memory state; valid = verify_initial(state, proof, vk); if (valid == false) { return (valid, part); } part = aggregate_commitments(state, proof, vk); (valid, part); } function verify(Proof memory proof, VerificationKey memory vk) internal view returns (bool) { (bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk); if (valid == false) { return false; } valid = PairingsBn254.pairingProd2( recursive_proof_part[0], PairingsBn254.P2(), recursive_proof_part[1], vk.g2_x ); return valid; } function verify_recursive( Proof memory proof, VerificationKey memory vk, uint256 recursive_vks_root, uint8 max_valid_index, uint8[] memory recursive_vks_indexes, uint256[] memory individual_vks_inputs, uint256[16] memory subproofs_limbs ) internal view returns (bool) { (uint256 recursive_input, PairingsBn254.G1Point[2] memory aggregated_g1s) = reconstruct_recursive_public_input( recursive_vks_root, max_valid_index, recursive_vks_indexes, individual_vks_inputs, subproofs_limbs ); assert(recursive_input == proof.input_values[0]); (bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk); if (valid == false) { return false; } // aggregated_g1s = inner // recursive_proof_part = outer PairingsBn254.G1Point[2] memory combined = combine_inner_and_outer(aggregated_g1s, recursive_proof_part); valid = PairingsBn254.pairingProd2(combined[0], PairingsBn254.P2(), combined[1], vk.g2_x); return valid; } function combine_inner_and_outer(PairingsBn254.G1Point[2] memory inner, PairingsBn254.G1Point[2] memory outer) internal view returns (PairingsBn254.G1Point[2] memory result) { // reuse the transcript primitive TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript(); transcript.update_with_g1(inner[0]); transcript.update_with_g1(inner[1]); transcript.update_with_g1(outer[0]); transcript.update_with_g1(outer[1]); PairingsBn254.Fr memory challenge = transcript.get_challenge(); // 1 * inner + challenge * outer result[0] = PairingsBn254.copy_g1(inner[0]); result[1] = PairingsBn254.copy_g1(inner[1]); PairingsBn254.G1Point memory tmp = outer[0].point_mul(challenge); result[0].point_add_assign(tmp); tmp = outer[1].point_mul(challenge); result[1].point_add_assign(tmp); return result; } function reconstruct_recursive_public_input( uint256 recursive_vks_root, uint8 max_valid_index, uint8[] memory recursive_vks_indexes, uint256[] memory individual_vks_inputs, uint256[16] memory subproofs_aggregated ) internal pure returns (uint256 recursive_input, PairingsBn254.G1Point[2] memory reconstructed_g1s) { assert(recursive_vks_indexes.length == individual_vks_inputs.length); bytes memory concatenated = abi.encodePacked(recursive_vks_root); uint8 index; for (uint256 i = 0; i < recursive_vks_indexes.length; i++) { index = recursive_vks_indexes[i]; assert(index <= max_valid_index); concatenated = abi.encodePacked(concatenated, index); } uint256 input; for (uint256 i = 0; i < recursive_vks_indexes.length; i++) { input = individual_vks_inputs[i]; assert(input < r_mod); concatenated = abi.encodePacked(concatenated, input); } concatenated = abi.encodePacked(concatenated, subproofs_aggregated); bytes32 commitment = sha256(concatenated); recursive_input = uint256(commitment) & RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK; reconstructed_g1s[0] = PairingsBn254.new_g1_checked( subproofs_aggregated[0] + (subproofs_aggregated[1] << LIMB_WIDTH) + (subproofs_aggregated[2] << (2 * LIMB_WIDTH)) + (subproofs_aggregated[3] << (3 * LIMB_WIDTH)), subproofs_aggregated[4] + (subproofs_aggregated[5] << LIMB_WIDTH) + (subproofs_aggregated[6] << (2 * LIMB_WIDTH)) + (subproofs_aggregated[7] << (3 * LIMB_WIDTH)) ); reconstructed_g1s[1] = PairingsBn254.new_g1_checked( subproofs_aggregated[8] + (subproofs_aggregated[9] << LIMB_WIDTH) + (subproofs_aggregated[10] << (2 * LIMB_WIDTH)) + (subproofs_aggregated[11] << (3 * LIMB_WIDTH)), subproofs_aggregated[12] + (subproofs_aggregated[13] << LIMB_WIDTH) + (subproofs_aggregated[14] << (2 * LIMB_WIDTH)) + (subproofs_aggregated[15] << (3 * LIMB_WIDTH)) ); return (recursive_input, reconstructed_g1s); } } contract VerifierWithDeserialize is Plonk4VerifierWithAccessToDNext { uint256 constant SERIALIZED_PROOF_LENGTH = 34; function deserialize_proof(uint256[] memory public_inputs, uint256[] memory serialized_proof) internal pure returns (Proof memory proof) { require(serialized_proof.length == SERIALIZED_PROOF_LENGTH); proof.input_values = new uint256[](public_inputs.length); for (uint256 i = 0; i < public_inputs.length; i++) { proof.input_values[i] = public_inputs[i]; } uint256 j = 0; for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.wire_commitments[i] = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); j += 2; } proof.copy_permutation_grand_product_commitment = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j + 1] ); j += 2; for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j + 1] ); j += 2; } for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.wire_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) { proof.gate_selector_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } proof.copy_grand_product_at_z_omega = PairingsBn254.new_fr(serialized_proof[j]); j += 1; proof.quotient_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]); j += 1; proof.linearization_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]); j += 1; proof.opening_at_z_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); j += 2; proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); } function verify_serialized_proof( uint256[] memory public_inputs, uint256[] memory serialized_proof, VerificationKey memory vk ) public view returns (bool) { require(vk.num_inputs == public_inputs.length); Proof memory proof = deserialize_proof(public_inputs, serialized_proof); bool valid = verify(proof, vk); return valid; } function verify_serialized_proof_with_recursion( uint256[] memory public_inputs, uint256[] memory serialized_proof, uint256 recursive_vks_root, uint8 max_valid_index, uint8[] memory recursive_vks_indexes, uint256[] memory individual_vks_inputs, uint256[16] memory subproofs_limbs, VerificationKey memory vk ) public view returns (bool) { require(vk.num_inputs == public_inputs.length); Proof memory proof = deserialize_proof(public_inputs, serialized_proof); bool valid = verify_recursive( proof, vk, recursive_vks_root, max_valid_index, recursive_vks_indexes, individual_vks_inputs, subproofs_limbs ); return valid; } } contract Plonk4VerifierWithAccessToDNextOld { using PairingsBn254 for PairingsBn254.G1Point; using PairingsBn254 for PairingsBn254.G2Point; using PairingsBn254 for PairingsBn254.Fr; using TranscriptLibrary for TranscriptLibrary.Transcript; uint256 constant STATE_WIDTH_OLD = 4; uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD = 1; struct VerificationKeyOld { uint256 domain_size; uint256 num_inputs; PairingsBn254.Fr omega; PairingsBn254.G1Point[STATE_WIDTH_OLD + 2] selector_commitments; // STATE_WIDTH for witness + multiplication + constant PairingsBn254.G1Point[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD] next_step_selector_commitments; PairingsBn254.G1Point[STATE_WIDTH_OLD] permutation_commitments; PairingsBn254.Fr[STATE_WIDTH_OLD - 1] permutation_non_residues; PairingsBn254.G2Point g2_x; } struct ProofOld { uint256[] input_values; PairingsBn254.G1Point[STATE_WIDTH_OLD] wire_commitments; PairingsBn254.G1Point grand_product_commitment; PairingsBn254.G1Point[STATE_WIDTH_OLD] quotient_poly_commitments; PairingsBn254.Fr[STATE_WIDTH_OLD] wire_values_at_z; PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD] wire_values_at_z_omega; PairingsBn254.Fr grand_product_at_z_omega; PairingsBn254.Fr quotient_polynomial_at_z; PairingsBn254.Fr linearization_polynomial_at_z; PairingsBn254.Fr[STATE_WIDTH_OLD - 1] permutation_polynomials_at_z; PairingsBn254.G1Point opening_at_z_proof; PairingsBn254.G1Point opening_at_z_omega_proof; } struct PartialVerifierStateOld { PairingsBn254.Fr alpha; PairingsBn254.Fr beta; PairingsBn254.Fr gamma; PairingsBn254.Fr v; PairingsBn254.Fr u; PairingsBn254.Fr z; PairingsBn254.Fr[] cached_lagrange_evals; } function evaluate_lagrange_poly_out_of_domain_old( uint256 poly_num, uint256 domain_size, PairingsBn254.Fr memory omega, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr memory res) { require(poly_num < domain_size); PairingsBn254.Fr memory one = PairingsBn254.new_fr(1); PairingsBn254.Fr memory omega_power = omega.pow(poly_num); res = at.pow(domain_size); res.sub_assign(one); require(res.value != 0); // Vanishing polynomial can not be zero at point `at` res.mul_assign(omega_power); PairingsBn254.Fr memory den = PairingsBn254.copy(at); den.sub_assign(omega_power); den.mul_assign(PairingsBn254.new_fr(domain_size)); den = den.inverse(); res.mul_assign(den); } function batch_evaluate_lagrange_poly_out_of_domain_old( uint256[] memory poly_nums, uint256 domain_size, PairingsBn254.Fr memory omega, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr[] memory res) { PairingsBn254.Fr memory one = PairingsBn254.new_fr(1); PairingsBn254.Fr memory tmp_1 = PairingsBn254.new_fr(0); PairingsBn254.Fr memory tmp_2 = PairingsBn254.new_fr(domain_size); PairingsBn254.Fr memory vanishing_at_z = at.pow(domain_size); vanishing_at_z.sub_assign(one); // we can not have random point z be in domain require(vanishing_at_z.value != 0); PairingsBn254.Fr[] memory nums = new PairingsBn254.Fr[](poly_nums.length); PairingsBn254.Fr[] memory dens = new PairingsBn254.Fr[](poly_nums.length); // numerators in a form omega^i * (z^n - 1) // denoms in a form (z - omega^i) * N for (uint256 i = 0; i < poly_nums.length; i++) { tmp_1 = omega.pow(poly_nums[i]); // power of omega nums[i].assign(vanishing_at_z); nums[i].mul_assign(tmp_1); dens[i].assign(at); // (X - omega^i) * N dens[i].sub_assign(tmp_1); dens[i].mul_assign(tmp_2); // mul by domain size } PairingsBn254.Fr[] memory partial_products = new PairingsBn254.Fr[](poly_nums.length); partial_products[0].assign(PairingsBn254.new_fr(1)); for (uint256 i = 1; i < dens.length ; i++) { partial_products[i].assign(dens[i - 1]); partial_products[i].mul_assign(partial_products[i-1]); } tmp_2.assign(partial_products[partial_products.length - 1]); tmp_2.mul_assign(dens[dens.length - 1]); tmp_2 = tmp_2.inverse(); // tmp_2 contains a^-1 * b^-1 (with! the last one) for (uint256 i = dens.length - 1; i < dens.length; i--) { tmp_1.assign(tmp_2); // all inversed tmp_1.mul_assign(partial_products[i]); // clear lowest terms tmp_2.mul_assign(dens[i]); dens[i].assign(tmp_1); } for (uint256 i = 0; i < nums.length; i++) { nums[i].mul_assign(dens[i]); } return nums; } function evaluate_vanishing_old(uint256 domain_size, PairingsBn254.Fr memory at) internal view returns (PairingsBn254.Fr memory res) { res = at.pow(domain_size); res.sub_assign(PairingsBn254.new_fr(1)); } function verify_at_z( PartialVerifierStateOld memory state, ProofOld memory proof, VerificationKeyOld memory vk ) internal view returns (bool) { PairingsBn254.Fr memory lhs = evaluate_vanishing_old(vk.domain_size, state.z); require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain lhs.mul_assign(proof.quotient_polynomial_at_z); PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z); // public inputs PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0); for (uint256 i = 0; i < proof.input_values.length; i++) { tmp.assign(state.cached_lagrange_evals[i]); tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i])); rhs.add_assign(tmp); } quotient_challenge.mul_assign(state.alpha); PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.grand_product_at_z_omega); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp.assign(proof.permutation_polynomials_at_z[i]); tmp.mul_assign(state.beta); tmp.add_assign(state.gamma); tmp.add_assign(proof.wire_values_at_z[i]); z_part.mul_assign(tmp); } tmp.assign(state.gamma); // we need a wire value of the last polynomial in enumeration tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH_OLD - 1]); z_part.mul_assign(tmp); z_part.mul_assign(quotient_challenge); rhs.sub_assign(z_part); quotient_challenge.mul_assign(state.alpha); tmp.assign(state.cached_lagrange_evals[0]); tmp.mul_assign(quotient_challenge); rhs.sub_assign(tmp); return lhs.value == rhs.value; } function reconstruct_d( PartialVerifierStateOld memory state, ProofOld memory proof, VerificationKeyOld memory vk ) internal view returns (PairingsBn254.G1Point memory res) { // we compute what power of v is used as a delinearization factor in batch opening of // commitments. Let's label W(x) = 1 / (x - z) * // [ // t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z) // + v (r(x) - r(z)) // + v^{2..5} * (witness(x) - witness(z)) // + v^(6..8) * (permutation(x) - permutation(z)) // ] // W'(x) = 1 / (x - z*omega) * // [ // + v^9 (z(x) - z(z*omega)) <- we need this power // + v^10 * (d(x) - d(z*omega)) // ] // // we pay a little for a few arithmetic operations to not introduce another constant uint256 power_for_z_omega_opening = 1 + 1 + STATE_WIDTH_OLD + STATE_WIDTH_OLD - 1; res = PairingsBn254.copy_g1(vk.selector_commitments[STATE_WIDTH_OLD + 1]); PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0); // addition gates for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) { tmp_g1 = vk.selector_commitments[i].point_mul(proof.wire_values_at_z[i]); res.point_add_assign(tmp_g1); } // multiplication gate tmp_fr.assign(proof.wire_values_at_z[0]); tmp_fr.mul_assign(proof.wire_values_at_z[1]); tmp_g1 = vk.selector_commitments[STATE_WIDTH_OLD].point_mul(tmp_fr); res.point_add_assign(tmp_g1); // d_next tmp_g1 = vk.next_step_selector_commitments[0].point_mul(proof.wire_values_at_z_omega[0]); res.point_add_assign(tmp_g1); // z * non_res * beta + gamma + a PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z); grand_product_part_at_z.mul_assign(state.beta); grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]); grand_product_part_at_z.add_assign(state.gamma); for (uint256 i = 0; i < vk.permutation_non_residues.length; i++) { tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.permutation_non_residues[i]); tmp_fr.mul_assign(state.beta); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i + 1]); grand_product_part_at_z.mul_assign(tmp_fr); } grand_product_part_at_z.mul_assign(state.alpha); tmp_fr.assign(state.cached_lagrange_evals[0]); tmp_fr.mul_assign(state.alpha); tmp_fr.mul_assign(state.alpha); grand_product_part_at_z.add_assign(tmp_fr); PairingsBn254.Fr memory grand_product_part_at_z_omega = state.v.pow(power_for_z_omega_opening); grand_product_part_at_z_omega.mul_assign(state.u); PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp_fr.assign(state.beta); tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i]); last_permutation_part_at_z.mul_assign(tmp_fr); } last_permutation_part_at_z.mul_assign(state.beta); last_permutation_part_at_z.mul_assign(proof.grand_product_at_z_omega); last_permutation_part_at_z.mul_assign(state.alpha); // add to the linearization tmp_g1 = proof.grand_product_commitment.point_mul(grand_product_part_at_z); tmp_g1.point_sub_assign(vk.permutation_commitments[STATE_WIDTH_OLD - 1].point_mul(last_permutation_part_at_z)); res.point_add_assign(tmp_g1); res.point_mul_assign(state.v); res.point_add_assign(proof.grand_product_commitment.point_mul(grand_product_part_at_z_omega)); } function verify_commitments( PartialVerifierStateOld memory state, ProofOld memory proof, VerificationKeyOld memory vk ) internal view returns (bool) { PairingsBn254.G1Point memory d = reconstruct_d(state, proof, vk); PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size); PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1); for (uint256 i = 1; i < proof.quotient_poly_commitments.length; i++) { tmp_fr.mul_assign(z_in_domain_size); tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); commitment_aggregation.point_add_assign(d); for (uint256 i = 0; i < proof.wire_commitments.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } for (uint256 i = 0; i < vk.permutation_commitments.length - 1; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = vk.permutation_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(aggregation_challenge); tmp_fr.mul_assign(state.u); tmp_g1 = proof.wire_commitments[STATE_WIDTH_OLD - 1].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); // collect opening values aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.linearization_polynomial_at_z); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.permutation_polynomials_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.grand_product_at_z_omega); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z_omega[0]); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value)); PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation; pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z)); tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.omega); tmp_fr.mul_assign(state.u); pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr)); PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u); pair_with_x.point_add_assign(proof.opening_at_z_proof); pair_with_x.negate(); return PairingsBn254.pairingProd2(pair_with_generator, PairingsBn254.P2(), pair_with_x, vk.g2_x); } function verify_initial( PartialVerifierStateOld memory state, ProofOld memory proof, VerificationKeyOld memory vk ) internal view returns (bool) { require(proof.input_values.length == vk.num_inputs); require(vk.num_inputs >= 1); TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript(); for (uint256 i = 0; i < vk.num_inputs; i++) { transcript.update_with_u256(proof.input_values[i]); } for (uint256 i = 0; i < proof.wire_commitments.length; i++) { transcript.update_with_g1(proof.wire_commitments[i]); } state.beta = transcript.get_challenge(); state.gamma = transcript.get_challenge(); transcript.update_with_g1(proof.grand_product_commitment); state.alpha = transcript.get_challenge(); for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) { transcript.update_with_g1(proof.quotient_poly_commitments[i]); } state.z = transcript.get_challenge(); uint256[] memory lagrange_poly_numbers = new uint256[](vk.num_inputs); for (uint256 i = 0; i < lagrange_poly_numbers.length; i++) { lagrange_poly_numbers[i] = i; } state.cached_lagrange_evals = batch_evaluate_lagrange_poly_out_of_domain_old( lagrange_poly_numbers, vk.domain_size, vk.omega, state.z ); bool valid = verify_at_z(state, proof, vk); if (valid == false) { return false; } for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) { transcript.update_with_fr(proof.wire_values_at_z[i]); } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { transcript.update_with_fr(proof.wire_values_at_z_omega[i]); } for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { transcript.update_with_fr(proof.permutation_polynomials_at_z[i]); } transcript.update_with_fr(proof.quotient_polynomial_at_z); transcript.update_with_fr(proof.linearization_polynomial_at_z); transcript.update_with_fr(proof.grand_product_at_z_omega); state.v = transcript.get_challenge(); transcript.update_with_g1(proof.opening_at_z_proof); transcript.update_with_g1(proof.opening_at_z_omega_proof); state.u = transcript.get_challenge(); return true; } // This verifier is for a PLONK with a state width 4 // and main gate equation // q_a(X) * a(X) + // q_b(X) * b(X) + // q_c(X) * c(X) + // q_d(X) * d(X) + // q_m(X) * a(X) * b(X) + // q_constants(X)+ // q_d_next(X) * d(X*omega) // where q_{}(X) are selectors a, b, c, d - state (witness) polynomials // q_d_next(X) "peeks" into the next row of the trace, so it takes // the same d(X) polynomial, but shifted function verify_old(ProofOld memory proof, VerificationKeyOld memory vk) internal view returns (bool) { PartialVerifierStateOld memory state; bool valid = verify_initial(state, proof, vk); if (valid == false) { return false; } valid = verify_commitments(state, proof, vk); return valid; } } contract VerifierWithDeserializeOld is Plonk4VerifierWithAccessToDNextOld { uint256 constant SERIALIZED_PROOF_LENGTH_OLD = 33; function deserialize_proof_old(uint256[] memory public_inputs, uint256[] memory serialized_proof) internal pure returns (ProofOld memory proof) { require(serialized_proof.length == SERIALIZED_PROOF_LENGTH_OLD); proof.input_values = new uint256[](public_inputs.length); for (uint256 i = 0; i < public_inputs.length; i++) { proof.input_values[i] = public_inputs[i]; } uint256 j = 0; for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) { proof.wire_commitments[i] = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); j += 2; } proof.grand_product_commitment = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); j += 2; for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) { proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j + 1] ); j += 2; } for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) { proof.wire_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } proof.grand_product_at_z_omega = PairingsBn254.new_fr(serialized_proof[j]); j += 1; proof.quotient_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]); j += 1; proof.linearization_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]); j += 1; for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } proof.opening_at_z_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); j += 2; proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); } } pragma solidity ^0.7.0; import './UniswapV2ERC20.sol'; import './libraries/Math.sol'; import './libraries/UQ112x112.sol'; contract UniswapV2Pair is UniswapV2ERC20 { using UniswapSafeMath for uint; using UQ112x112 for uint224; address public factory; address public token0; address public token1; uint256 private unlocked = 1; modifier lock() { require(unlocked == 1, 'UniswapV2: LOCKED'); unlocked = 0; _; unlocked = 1; } constructor() { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address _token0, address _token1) external { require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; } function mint(address to, uint256 amount) external lock { require(msg.sender == factory, 'mt1'); _mint(to, amount); } function burn(address to, uint256 amount) external lock { require(msg.sender == factory, 'br1'); _burn(to, amount); } } pragma solidity ^0.7.0; import './libraries/UniswapSafeMath.sol'; contract UniswapV2ERC20 { using UniswapSafeMath for uint; string public constant name = 'EdgeSwap V1'; string public constant symbol = 'Edge-V1'; uint8 public constant decimals = 18; uint256 public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); function _mint(address to, uint256 value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint256 value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint256 value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint256 value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint256 value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint256 value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint256 value) external returns (bool) { if (allowance[from][msg.sender] != uint256(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } } pragma solidity ^0.7.0; // a library for performing various math operations library Math { function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } pragma solidity ^0.7.0; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } pragma solidity ^0.7.0; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library UniswapSafeMath { 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'); } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 /// @title Interface of the upgradeable contract /// @author Matter Labs interface Upgradeable { /// @notice Upgrades target of upgradeable contract /// @param newTarget New target /// @param newTargetInitializationParameters New target initialization parameters function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external; }
@notice Returns new_hash = hash(old_hash + bytes)
function concatHash(bytes32 _hash, bytes memory _bytes) internal pure returns (bytes32) { bytes32 result; assembly { let bytesLen := add(mload(_bytes), 32) mstore(_bytes, _hash) result := keccak256(_bytes, bytesLen) mstore(_bytes, sub(bytesLen, 32)) } return result; }
72,194
[ 1, 1356, 394, 67, 2816, 273, 1651, 12, 1673, 67, 2816, 397, 1731, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3835, 2310, 12, 3890, 1578, 389, 2816, 16, 1731, 3778, 389, 3890, 13, 2713, 16618, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 1731, 1578, 563, 31, 203, 3639, 19931, 288, 203, 5411, 2231, 1731, 2891, 519, 527, 12, 81, 945, 24899, 3890, 3631, 3847, 13, 203, 5411, 312, 2233, 24899, 3890, 16, 389, 2816, 13, 203, 5411, 563, 519, 417, 24410, 581, 5034, 24899, 3890, 16, 1731, 2891, 13, 203, 5411, 312, 2233, 24899, 3890, 16, 720, 12, 3890, 2891, 16, 3847, 3719, 203, 3639, 289, 203, 3639, 327, 563, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { LibDiamondCut } from "./diamond/LibDiamondCut.sol"; import { DiamondFacet } from "./diamond/DiamondFacet.sol"; import { OwnershipFacet } from "./diamond/OwnershipFacet.sol"; import { LibDiamondStorage } from "./diamond/LibDiamondStorage.sol"; import { IDiamondCut } from "./diamond/IDiamondCut.sol"; import { IDiamondLoupe } from "./diamond/IDiamondLoupe.sol"; import { IERC165 } from "./diamond/IERC165.sol"; import { LibDiamondStorageDerivaDEX } from "./storage/LibDiamondStorageDerivaDEX.sol"; import { IDDX } from "./tokens/interfaces/IDDX.sol"; /** * @title DerivaDEX * @author DerivaDEX * @notice This is the diamond for DerivaDEX. All current * and future logic runs by way of this contract. * @dev This diamond implements the Diamond Standard (EIP #2535). */ contract DerivaDEX { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @notice This constructor initializes the upgrade machinery (as * per the Diamond Standard), sets the admin of the proxy * to be the deploying address (very temporary), and sets * the native DDX governance/operational token. * @param _ddxToken The native DDX token address. */ constructor(IDDX _ddxToken) public { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Temporarily set admin to the deploying address to facilitate // adding the Diamond functions dsDerivaDEX.admin = msg.sender; // Set DDX token address for token logic in facet contracts require(address(_ddxToken) != address(0), "DerivaDEX: ddx token is zero address."); dsDerivaDEX.ddxToken = _ddxToken; emit OwnershipTransferred(address(0), msg.sender); // Create DiamondFacet contract - // implements DiamondCut interface and DiamondLoupe interface DiamondFacet diamondFacet = new DiamondFacet(); // Create OwnershipFacet contract which implements ownership // functions and supportsInterface function OwnershipFacet ownershipFacet = new OwnershipFacet(); IDiamondCut.FacetCut[] memory diamondCut = new IDiamondCut.FacetCut[](2); // adding diamondCut function and diamond loupe functions diamondCut[0].facetAddress = address(diamondFacet); diamondCut[0].action = IDiamondCut.FacetCutAction.Add; diamondCut[0].functionSelectors = new bytes4[](6); diamondCut[0].functionSelectors[0] = DiamondFacet.diamondCut.selector; diamondCut[0].functionSelectors[1] = DiamondFacet.facetFunctionSelectors.selector; diamondCut[0].functionSelectors[2] = DiamondFacet.facets.selector; diamondCut[0].functionSelectors[3] = DiamondFacet.facetAddress.selector; diamondCut[0].functionSelectors[4] = DiamondFacet.facetAddresses.selector; diamondCut[0].functionSelectors[5] = DiamondFacet.supportsInterface.selector; // adding ownership functions diamondCut[1].facetAddress = address(ownershipFacet); diamondCut[1].action = IDiamondCut.FacetCutAction.Add; diamondCut[1].functionSelectors = new bytes4[](2); diamondCut[1].functionSelectors[0] = OwnershipFacet.transferOwnershipToSelf.selector; diamondCut[1].functionSelectors[1] = OwnershipFacet.getAdmin.selector; // execute internal diamondCut function to add functions LibDiamondCut.diamondCut(diamondCut, address(0), new bytes(0)); // adding ERC165 data ds.supportedInterfaces[IERC165.supportsInterface.selector] = true; ds.supportedInterfaces[IDiamondCut.diamondCut.selector] = true; bytes4 interfaceID = IDiamondLoupe.facets.selector ^ IDiamondLoupe.facetFunctionSelectors.selector ^ IDiamondLoupe.facetAddresses.selector ^ IDiamondLoupe.facetAddress.selector; ds.supportedInterfaces[interfaceID] = true; } // TODO(jalextowle): Remove this linter directive when // https://github.com/protofire/solhint/issues/248 is merged and released. /* solhint-disable ordering */ receive() external payable { revert("DerivaDEX does not directly accept ether."); } // Finds facet for function that is called and executes the // function if it is found and returns any value. fallback() external payable { LibDiamondStorage.DiamondStorage storage ds; bytes32 position = LibDiamondStorage.DIAMOND_STORAGE_POSITION; assembly { ds_slot := position } address facet = ds.selectorToFacetAndPosition[msg.sig].facetAddress; require(facet != address(0), "Function does not exist."); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(0, 0, size) switch result case 0 { revert(0, size) } default { return(0, size) } } } /* solhint-enable ordering */ } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * * Implementation of internal diamondCut function. /******************************************************************************/ import "./LibDiamondStorage.sol"; import "./IDiamondCut.sol"; library LibDiamondCut { event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata); // Internal function version of diamondCut // This code is almost the same as the external diamondCut, // except it is using 'FacetCut[] memory _diamondCut' instead of // 'FacetCut[] calldata _diamondCut'. // The code is duplicated to prevent copying calldata to memory which // causes an error for a two dimensional array. function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { require(_diamondCut.length > 0, "LibDiamondCut: No facets to cut"); for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { addReplaceRemoveFacetSelectors( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].action, _diamondCut[facetIndex].functionSelectors ); } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } function addReplaceRemoveFacetSelectors( address _newFacetAddress, IDiamondCut.FacetCutAction _action, bytes4[] memory _selectors ) internal { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); require(_selectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); // add or replace functions if (_newFacetAddress != address(0)) { uint256 facetAddressPosition = ds.facetFunctionSelectors[_newFacetAddress].facetAddressPosition; // add new facet address if it does not exist if ( facetAddressPosition == 0 && ds.facetFunctionSelectors[_newFacetAddress].functionSelectors.length == 0 ) { ensureHasContractCode(_newFacetAddress, "LibDiamondCut: New facet has no code"); facetAddressPosition = ds.facetAddresses.length; ds.facetAddresses.push(_newFacetAddress); ds.facetFunctionSelectors[_newFacetAddress].facetAddressPosition = uint16(facetAddressPosition); } // add or replace selectors for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; // add if (_action == IDiamondCut.FacetCutAction.Add) { require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists"); addSelector(_newFacetAddress, selector); } else if (_action == IDiamondCut.FacetCutAction.Replace) { // replace require( oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function" ); removeSelector(oldFacetAddress, selector); addSelector(_newFacetAddress, selector); } else { revert("LibDiamondCut: Incorrect FacetCutAction"); } } } else { require( _action == IDiamondCut.FacetCutAction.Remove, "LibDiamondCut: action not set to FacetCutAction.Remove" ); // remove selectors for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; removeSelector(ds.selectorToFacetAndPosition[selector].facetAddress, selector); } } } function addSelector(address _newFacet, bytes4 _selector) internal { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); uint256 selectorPosition = ds.facetFunctionSelectors[_newFacet].functionSelectors.length; ds.facetFunctionSelectors[_newFacet].functionSelectors.push(_selector); ds.selectorToFacetAndPosition[_selector].facetAddress = _newFacet; ds.selectorToFacetAndPosition[_selector].functionSelectorPosition = uint16(selectorPosition); } function removeSelector(address _oldFacetAddress, bytes4 _selector) internal { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); require(_oldFacetAddress != address(0), "LibDiamondCut: Can't remove or replace function that doesn't exist"); // replace selector with last selector, then delete last selector uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition; uint256 lastSelectorPosition = ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors.length - 1; bytes4 lastSelector = ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors[lastSelectorPosition]; // if not the same then replace _selector with lastSelector if (lastSelector != _selector) { ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors[selectorPosition] = lastSelector; ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint16(selectorPosition); } // delete the last selector ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors.pop(); delete ds.selectorToFacetAndPosition[_selector]; // if no more selectors for facet address then delete the facet address if (lastSelectorPosition == 0) { // replace facet address with last facet address and delete last facet address uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1; address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition]; uint256 facetAddressPosition = ds.facetFunctionSelectors[_oldFacetAddress].facetAddressPosition; if (_oldFacetAddress != lastFacetAddress) { ds.facetAddresses[facetAddressPosition] = lastFacetAddress; ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = uint16(facetAddressPosition); } ds.facetAddresses.pop(); delete ds.facetFunctionSelectors[_oldFacetAddress]; } } function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty"); } else { require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)"); if (_init != address(this)) { LibDiamondCut.ensureHasContractCode(_init, "LibDiamondCut: _init address has no code"); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert("LibDiamondCut: _init function reverted"); } } } } function ensureHasContractCode(address _contract, string memory _errorMessage) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * * Implementation of diamondCut external function and DiamondLoupe interface. /******************************************************************************/ import "./LibDiamondStorage.sol"; import "./LibDiamondCut.sol"; import "../storage/LibDiamondStorageDerivaDEX.sol"; import "./IDiamondCut.sol"; import "./IDiamondLoupe.sol"; import "./IERC165.sol"; contract DiamondFacet is IDiamondCut, IDiamondLoupe, IERC165 { // Standard diamondCut external function /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external override { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "DiamondFacet: Must own the contract"); require(_diamondCut.length > 0, "DiamondFacet: No facets to cut"); for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { LibDiamondCut.addReplaceRemoveFacetSelectors( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].action, _diamondCut[facetIndex].functionSelectors ); } emit DiamondCut(_diamondCut, _init, _calldata); LibDiamondCut.initializeDiamondCut(_init, _calldata); } // Diamond Loupe Functions //////////////////////////////////////////////////////////////////// /// These functions are expected to be called frequently by tools. // // struct Facet { // address facetAddress; // bytes4[] functionSelectors; // } // /// @notice Gets all facets and their selectors. /// @return facets_ Facet function facets() external view override returns (Facet[] memory facets_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); uint256 numFacets = ds.facetAddresses.length; facets_ = new Facet[](numFacets); for (uint256 i; i < numFacets; i++) { address facetAddress_ = ds.facetAddresses[i]; facets_[i].facetAddress = facetAddress_; facets_[i].functionSelectors = ds.facetFunctionSelectors[facetAddress_].functionSelectors; } } /// @notice Gets all the function selectors provided by a facet. /// @param _facet The facet address. /// @return facetFunctionSelectors_ function facetFunctionSelectors(address _facet) external view override returns (bytes4[] memory facetFunctionSelectors_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); facetFunctionSelectors_ = ds.facetFunctionSelectors[_facet].functionSelectors; } /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external view override returns (address[] memory facetAddresses_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); facetAddresses_ = ds.facetAddresses; } /// @notice Gets the facet that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external view override returns (address facetAddress_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); facetAddress_ = ds.selectorToFacetAndPosition[_functionSelector].facetAddress; } // This implements ERC-165. function supportsInterface(bytes4 _interfaceId) external view override returns (bool) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); return ds.supportedInterfaces[_interfaceId]; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import { LibDiamondStorageDerivaDEX } from "../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorage } from "../diamond/LibDiamondStorage.sol"; import { IERC165 } from "./IERC165.sol"; contract OwnershipFacet { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @notice This function transfers ownership to self. This is done * so that we can ensure upgrades (using diamondCut) and * various other critical parameter changing scenarios * can only be done via governance (a facet). */ function transferOwnershipToSelf() external { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Not authorized"); dsDerivaDEX.admin = address(this); emit OwnershipTransferred(msg.sender, address(this)); } /** * @notice This gets the admin for the diamond. * @return Admin address. */ function getAdmin() external view returns (address) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); return dsDerivaDEX.admin; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) /******************************************************************************/ library LibDiamondStorage { struct FacetAddressAndPosition { address facetAddress; uint16 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array } struct FacetFunctionSelectors { bytes4[] functionSelectors; uint16 facetAddressPosition; // position of facetAddress in facetAddresses array } struct DiamondStorage { // maps function selector to the facet address and // the position of the facet address in the facetAddresses array // and the position of the selector in the facetSelectors.selectors array mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition; // maps facet addresses to function selectors mapping(address => FacetFunctionSelectors) facetFunctionSelectors; // facet addresses address[] facetAddresses; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; } bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) /******************************************************************************/ interface IDiamondCut { enum FacetCutAction { Add, Replace, Remove } struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) /******************************************************************************/ import "./IDiamondCut.sol"; // A loupe is a small magnifying glass used to look at diamonds. // These functions look at diamonds interface IDiamondLoupe { /// These functions are expected to be called frequently /// by tools. struct Facet { address facetAddress; bytes4[] functionSelectors; } /// @notice Gets all facet addresses and their four byte function selectors. /// @return facets_ Facet function facets() external view returns (Facet[] memory facets_); /// @notice Gets all the function selectors supported by a specific facet. /// @param _facet The facet address. /// @return facetFunctionSelectors_ function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_); /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external view returns (address[] memory facetAddresses_); /// @notice Gets the facet that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IERC165 { /// @notice Query if a contract implements an interface /// @param interfaceId The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { IDDX } from "../tokens/interfaces/IDDX.sol"; library LibDiamondStorageDerivaDEX { struct DiamondStorageDerivaDEX { string name; address admin; IDDX ddxToken; } bytes32 constant DIAMOND_STORAGE_POSITION_DERIVADEX = keccak256("diamond.standard.diamond.storage.DerivaDEX.DerivaDEX"); function diamondStorageDerivaDEX() internal pure returns (DiamondStorageDerivaDEX storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_DERIVADEX; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IDDX { function transfer(address _recipient, uint256 _amount) external returns (bool); function mint(address _recipient, uint256 _amount) external; function delegate(address _delegatee) external; function transferFrom( address _sender, address _recipient, uint256 _amount ) external returns (bool); function approve(address _spender, uint256 _amount) external returns (bool); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { IDDX } from "./interfaces/IDDX.sol"; /** * @title DDXWalletCloneable * @author DerivaDEX * @notice This is a cloneable on-chain DDX wallet that holds a trader's * stakes and issued rewards. */ contract DDXWalletCloneable { // Whether contract has already been initialized once before bool initialized; /** * @notice This function initializes the on-chain DDX wallet * for a given trader. * @param _trader Trader address. * @param _ddxToken DDX token address. * @param _derivaDEX DerivaDEX Proxy address. */ function initialize( address _trader, IDDX _ddxToken, address _derivaDEX ) external { // Prevent initializing more than once require(!initialized, "DDXWalletCloneable: already init."); initialized = true; // Automatically delegate the holdings of this contract/wallet // back to the trader. _ddxToken.delegate(_trader); // Approve the DerivaDEX Proxy contract for unlimited transfers _ddxToken.approve(_derivaDEX, uint96(-1)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { TraderDefs } from "../../libs/defs/TraderDefs.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageTrader } from "../../storage/LibDiamondStorageTrader.sol"; import { DDXWalletCloneable } from "../../tokens/DDXWalletCloneable.sol"; import { IDDX } from "../../tokens/interfaces/IDDX.sol"; import { IDDXWalletCloneable } from "../../tokens/interfaces/IDDXWalletCloneable.sol"; import { LibTraderInternal } from "./LibTraderInternal.sol"; /** * @title Trader * @author DerivaDEX * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to traders - staking DDX, withdrawing * DDX, receiving DDX rewards, etc. */ contract Trader { using SafeMath96 for uint96; using SafeMath for uint256; using SafeERC20 for IERC20; event RewardCliffSet(bool rewardCliffSet); event DDXRewardIssued(address trader, uint96 amount); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Trader: must be called by Gov."); _; } /** * @notice Limits functions to only be called post reward cliff. */ modifier postRewardCliff { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); require(dsTrader.rewardCliff, "Trader: prior to reward cliff."); _; } /** * @notice This function initializes the state with some critical * information, including the on-chain wallet cloneable * contract address. This can only be called via governance. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. */ function initialize(IDDXWalletCloneable _ddxWalletCloneable) external onlyAdmin { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); // Set the on-chain DDX wallet cloneable contract address dsTrader.ddxWalletCloneable = _ddxWalletCloneable; } /** * @notice This function sets the reward cliff. * @param _rewardCliff Reward cliff. */ function setRewardCliff(bool _rewardCliff) external onlyAdmin { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); // Set the reward cliff (boolean value) dsTrader.rewardCliff = _rewardCliff; emit RewardCliffSet(_rewardCliff); } /** * @notice This function issues DDX rewards to a trader. It can * only be called via governance. * @param _amount DDX tokens to be rewarded. * @param _trader Trader recipient address. */ function issueDDXReward(uint96 _amount, address _trader) external onlyAdmin { // Call the internal function to issue DDX rewards. This // internal function is shareable with other facets that import // the LibTraderInternal library. LibTraderInternal.issueDDXReward(_amount, _trader); } /** * @notice This function issues DDX rewards to an external address. * It can only be called via governance. * @param _amount DDX tokens to be rewarded. * @param _recipient External recipient address. */ function issueDDXToRecipient(uint96 _amount, address _recipient) external onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Transfer DDX from trader to trader's on-chain wallet dsDerivaDEX.ddxToken.mint(_recipient, _amount); emit DDXRewardIssued(_recipient, _amount); } /** * @notice This function lets traders take DDX from their wallet * into their on-chain DDX wallet. It's important to note * that any DDX staked from the trader to this wallet * delegates the voting rights of that stake back to the * user. To be more explicit, if Alice's personal wallet is * delegating to Bob, and she now stakes a portion of her * DDX into this on-chain DDX wallet of hers, those tokens * will now count towards her voting power, not Bob's, since * her on-chain wallet is automatically delegating back to * her. * @param _amount The DDX tokens to be staked. */ function stakeDDXFromTrader(uint96 _amount) external { transferDDXToWallet(msg.sender, _amount); } /** * @notice This function lets traders send DDX from their wallet * into another trader's on-chain DDX wallet. It's * important to note that any DDX staked to this wallet * delegates the voting rights of that stake back to the * user. * @param _trader Trader address to receive DDX (inside their * wallet, which will be created if it does not already * exist). * @param _amount The DDX tokens to be staked. */ function sendDDXFromTraderToTraderWallet(address _trader, uint96 _amount) external { transferDDXToWallet(_trader, _amount); } /** * @notice This function lets traders withdraw DDX from their * on-chain DDX wallet to their personal wallet. It's * important to note that the voting rights for any DDX * withdrawn are returned back to the delegatee of the * user's personal wallet. To be more explicit, if Alice is * personal wallet is delegating to Bob, and she now * withdraws a portion of her DDX from this on-chain DDX * wallet of hers, those tokens will now count towards Bob's * voting power, not her's, since her on-chain wallet is * automatically delegating back to her, but her personal * wallet is delegating to Bob. Withdrawals can only happen * when the governance cliff is lifted. * @param _amount The DDX tokens to be withdrawn. */ function withdrawDDXToTrader(uint96 _amount) external postRewardCliff { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); TraderDefs.Trader storage trader = dsTrader.traders[msg.sender]; LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Subtract trader's DDX balance in the contract trader.ddxBalance = trader.ddxBalance.sub96(_amount); // Transfer DDX from trader's on-chain wallet to the trader dsDerivaDEX.ddxToken.transferFrom(trader.ddxWalletContract, msg.sender, _amount); } /** * @notice This function gets the attributes for a given trader. * @param _trader Trader address. */ function getTrader(address _trader) external view returns (TraderDefs.Trader memory) { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); return dsTrader.traders[_trader]; } /** * @notice This function transfers DDX from the sender * to another trader's DDX wallet. * @param _trader Trader address' DDX wallet address to transfer * into. * @param _amount Amount of DDX to transfer. */ function transferDDXToWallet(address _trader, uint96 _amount) internal { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); TraderDefs.Trader storage trader = dsTrader.traders[_trader]; // If trader does not have a DDX on-chain wallet yet, create one if (trader.ddxWalletContract == address(0)) { LibTraderInternal.createDDXWallet(_trader); } LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Add trader's DDX balance in the contract trader.ddxBalance = trader.ddxBalance.add96(_amount); // Transfer DDX from trader to trader's on-chain wallet dsDerivaDEX.ddxToken.transferFrom(msg.sender, trader.ddxWalletContract, _amount); } } // 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath96 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add96(uint96 a, uint96 b) internal pure returns (uint96) { uint96 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 sub96(uint96 a, uint96 b) internal pure returns (uint96) { return sub96(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 sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); uint96 c = a - b; return c; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title TraderDefs * @author DerivaDEX * * This library contains the common structs and enums pertaining to * traders. */ library TraderDefs { // Consists of trader attributes, including the DDX balance and // the onchain DDX wallet contract address struct Trader { uint96 ddxBalance; address ddxWalletContract; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { TraderDefs } from "../libs/defs/TraderDefs.sol"; import { IDDXWalletCloneable } from "../tokens/interfaces/IDDXWalletCloneable.sol"; library LibDiamondStorageTrader { struct DiamondStorageTrader { mapping(address => TraderDefs.Trader) traders; bool rewardCliff; IDDXWalletCloneable ddxWalletCloneable; } bytes32 constant DIAMOND_STORAGE_POSITION_TRADER = keccak256("diamond.standard.diamond.storage.DerivaDEX.Trader"); function diamondStorageTrader() internal pure returns (DiamondStorageTrader storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_TRADER; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import { IDDX } from "./IDDX.sol"; interface IDDXWalletCloneable { function initialize( address _trader, IDDX _ddxToken, address _derivaDEX ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import { LibClone } from "../../libs/LibClone.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { TraderDefs } from "../../libs/defs/TraderDefs.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageTrader } from "../../storage/LibDiamondStorageTrader.sol"; import { IDDX } from "../../tokens/interfaces/IDDX.sol"; import { IDDXWalletCloneable } from "../../tokens/interfaces/IDDXWalletCloneable.sol"; /** * @title TraderInternalLib * @author DerivaDEX * @notice This is a library of internal functions mainly defined in * the Trader facet, but used in other facets. */ library LibTraderInternal { using SafeMath96 for uint96; using SafeMath for uint256; using SafeERC20 for IERC20; event DDXRewardIssued(address trader, uint96 amount); /** * @notice This function creates a new DDX wallet for a trader. * @param _trader Trader address. */ function createDDXWallet(address _trader) internal { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); // Leveraging the minimal proxy contract/clone factory pattern // as described here (https://eips.ethereum.org/EIPS/eip-1167) IDDXWalletCloneable ddxWallet = IDDXWalletCloneable(LibClone.createClone(address(dsTrader.ddxWalletCloneable))); LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Cloneable contracts have no constructor, so instead we use // an initialize function. This initialize delegates this // on-chain DDX wallet back to the trader and sets the allowance // for the DerivaDEX Proxy contract to be unlimited. ddxWallet.initialize(_trader, dsDerivaDEX.ddxToken, address(this)); // Store the on-chain wallet address in the trader's storage dsTrader.traders[_trader].ddxWalletContract = address(ddxWallet); } /** * @notice This function issues DDX rewards to a trader. It can be * called by any facet part of the diamond. * @param _amount DDX tokens to be rewarded. * @param _trader Trader address. */ function issueDDXReward(uint96 _amount, address _trader) internal { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); TraderDefs.Trader storage trader = dsTrader.traders[_trader]; // If trader does not have a DDX on-chain wallet yet, create one if (trader.ddxWalletContract == address(0)) { createDDXWallet(_trader); } LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Add trader's DDX balance in the contract trader.ddxBalance = trader.ddxBalance.add96(_amount); // Transfer DDX from trader to trader's on-chain wallet dsDerivaDEX.ddxToken.mint(trader.ddxWalletContract, _amount); emit DDXRewardIssued(_trader, _amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies 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.12; /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //solhint-disable max-line-length //solhint-disable no-inline-assembly library LibClone { 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) } } function isClone(address target, address query) internal view returns (bool result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000) mstore(add(clone, 0xa), targetBytes) mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and(eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))) } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { Math } from "openzeppelin-solidity/contracts/math/Math.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath32 } from "../../libs/SafeMath32.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { MathHelpers } from "../../libs/MathHelpers.sol"; import { InsuranceFundDefs } from "../../libs/defs/InsuranceFundDefs.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageInsuranceFund } from "../../storage/LibDiamondStorageInsuranceFund.sol"; import { LibDiamondStorageTrader } from "../../storage/LibDiamondStorageTrader.sol"; import { LibDiamondStoragePause } from "../../storage/LibDiamondStoragePause.sol"; import { IDDX } from "../../tokens/interfaces/IDDX.sol"; import { LibTraderInternal } from "../trader/LibTraderInternal.sol"; import { IAToken } from "../interfaces/IAToken.sol"; import { IComptroller } from "../interfaces/IComptroller.sol"; import { ICToken } from "../interfaces/ICToken.sol"; import { IDIFundToken } from "../../tokens/interfaces/IDIFundToken.sol"; import { IDIFundTokenFactory } from "../../tokens/interfaces/IDIFundTokenFactory.sol"; interface IERCCustom { function decimals() external view returns (uint8); } /** * @title InsuranceFund * @author DerivaDEX * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to insurance mining - staking directly * into the insurance fund and receiving a DDX issuance to be * used in governance/operations. * @dev This facet at the moment only handles insurance mining. It can * and will grow to handle the remaining functions of the insurance * fund, such as receiving quote-denominated fees and liquidation * spreads, among others. The Diamond storage will only be * affected when facet functions are called via the proxy * contract, no checks are necessary. */ contract InsuranceFund { using SafeMath32 for uint32; using SafeMath96 for uint96; using SafeMath for uint96; using SafeMath for uint256; using MathHelpers for uint32; using MathHelpers for uint96; using MathHelpers for uint224; using MathHelpers for uint256; using SafeERC20 for IERC20; // Compound-related constant variables // kovan: 0x5eAe89DC1C671724A672ff0630122ee834098657 IComptroller public constant COMPTROLLER = IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); // kovan: 0x61460874a7196d6a22D1eE4922473664b3E95270 IERC20 public constant COMP_TOKEN = IERC20(0xc00e94Cb662C3520282E6f5717214004A7f26888); event InsuranceFundInitialized( uint32 interval, uint32 withdrawalFactor, uint96 mineRatePerBlock, uint96 advanceIntervalReward, uint256 miningFinalBlockNumber ); event InsuranceFundCollateralAdded( bytes32 collateralName, address underlyingToken, address collateralToken, InsuranceFundDefs.Flavor flavor ); event StakedToInsuranceFund(address staker, uint96 amount, bytes32 collateralName); event WithdrawnFromInsuranceFund(address withdrawer, uint96 amount, bytes32 collateralName); event AdvancedOtherRewards(address intervalAdvancer, uint96 advanceReward); event InsuranceMineRewardsClaimed(address claimant, uint96 minedAmount); event MineRatePerBlockSet(uint96 mineRatePerBlock); event AdvanceIntervalRewardSet(uint96 advanceIntervalReward); event WithdrawalFactorSet(uint32 withdrawalFactor); event InsuranceMiningExtended(uint256 miningFinalBlockNumber); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "IFund: must be called by Gov."); _; } /** * @notice Limits functions to only be called while insurance * mining is ongoing. */ modifier insuranceMiningOngoing { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(block.number < dsInsuranceFund.miningFinalBlockNumber, "IFund: mining ended."); _; } /** * @notice Limits functions to only be called while other * rewards checkpointing is ongoing. */ modifier otherRewardsOngoing { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require( dsInsuranceFund.otherRewardsCheckpointBlock < dsInsuranceFund.miningFinalBlockNumber, "IFund: other rewards checkpointing ended." ); _; } /** * @notice Limits functions to only be called via governance. */ modifier isNotPaused { LibDiamondStoragePause.DiamondStoragePause storage dsPause = LibDiamondStoragePause.diamondStoragePause(); require(!dsPause.isPaused, "IFund: paused."); _; } /** * @notice This function initializes the state with some critical * information. This can only be called via governance. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. * @param _interval The interval length (blocks) for other rewards * claiming checkpoints (i.e. COMP and extra aTokens). * @param _withdrawalFactor Specifies the withdrawal fee if users * redeem their insurance tokens. * @param _mineRatePerBlock The DDX tokens to be mined each interval * for insurance mining. * @param _advanceIntervalReward DDX reward for participant who * advances the insurance mining interval. * @param _insuranceMiningLength Insurance mining length (blocks). */ function initialize( uint32 _interval, uint32 _withdrawalFactor, uint96 _mineRatePerBlock, uint96 _advanceIntervalReward, uint256 _insuranceMiningLength, IDIFundTokenFactory _diFundTokenFactory ) external onlyAdmin { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Set the interval for other rewards claiming checkpoints // (i.e. COMP and aTokens that accrue to the contract) // (e.g. 40320 ~ 1 week = 7 * 24 * 60 * 60 / 15 blocks) dsInsuranceFund.interval = _interval; // Keep track of the block number for other rewards checkpoint, // which is initialized to the block number the insurance fund // facet is added to the diamond dsInsuranceFund.otherRewardsCheckpointBlock = block.number; // Set the withdrawal factor, capped at 1000, implying 0% fee require(_withdrawalFactor <= 1000, "IFund: withdrawal fee too high."); // Set withdrawal ratio, which will be used with a 1e3 scaling // factor, meaning a value of 995 implies a withdrawal fee of // 0.5% since 995/1e3 => 0.995 dsInsuranceFund.withdrawalFactor = _withdrawalFactor; // Set the insurance mine rate per block. // (e.g. 1.189e18 ~ 5% liquidity mine (50mm tokens)) dsInsuranceFund.mineRatePerBlock = _mineRatePerBlock; // Incentive to advance the other rewards interval // (e.g. 100e18 = 100 DDX) dsInsuranceFund.advanceIntervalReward = _advanceIntervalReward; // Set the final block number for insurance mining dsInsuranceFund.miningFinalBlockNumber = block.number.add(_insuranceMiningLength); // DIFundToken factory to deploy DerivaDEX Insurance Fund token // contracts pertaining to each supported collateral dsInsuranceFund.diFundTokenFactory = _diFundTokenFactory; // Initialize the DDX market state index and block. These values // are critical for computing the DDX continuously issued per // block dsInsuranceFund.ddxMarketState.index = 1e36; dsInsuranceFund.ddxMarketState.block = block.number.safe32("IFund: exceeds 32 bits"); emit InsuranceFundInitialized( _interval, _withdrawalFactor, _mineRatePerBlock, _advanceIntervalReward, dsInsuranceFund.miningFinalBlockNumber ); } /** * @notice This function sets the DDX mine rate per block. * @param _mineRatePerBlock The DDX tokens mine rate per block. */ function setMineRatePerBlock(uint96 _mineRatePerBlock) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // NOTE(jalextowle): We must update the DDX Market State prior to // changing the mine rate per block in order to lock in earned rewards // for insurance mining participants. updateDDXMarketState(dsInsuranceFund); require(_mineRatePerBlock != dsInsuranceFund.mineRatePerBlock, "IFund: same as current value."); // Set the insurance mine rate per block. // (e.g. 1.189e18 ~ 5% liquidity mine (50mm tokens)) dsInsuranceFund.mineRatePerBlock = _mineRatePerBlock; emit MineRatePerBlockSet(_mineRatePerBlock); } /** * @notice This function sets the advance interval reward. * @param _advanceIntervalReward DDX reward for advancing interval. */ function setAdvanceIntervalReward(uint96 _advanceIntervalReward) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(_advanceIntervalReward != dsInsuranceFund.advanceIntervalReward, "IFund: same as current value."); // Set the advance interval reward dsInsuranceFund.advanceIntervalReward = _advanceIntervalReward; emit AdvanceIntervalRewardSet(_advanceIntervalReward); } /** * @notice This function sets the withdrawal factor. * @param _withdrawalFactor Withdrawal factor. */ function setWithdrawalFactor(uint32 _withdrawalFactor) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(_withdrawalFactor != dsInsuranceFund.withdrawalFactor, "IFund: same as current value."); // Set the withdrawal factor, capped at 1000, implying 0% fee require(dsInsuranceFund.withdrawalFactor <= 1000, "IFund: withdrawal fee too high."); dsInsuranceFund.withdrawalFactor = _withdrawalFactor; emit WithdrawalFactorSet(_withdrawalFactor); } /** * @notice This function extends insurance mining. * @param _insuranceMiningExtension Insurance mining extension * (blocks). */ function extendInsuranceMining(uint256 _insuranceMiningExtension) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(_insuranceMiningExtension != 0, "IFund: invalid extension."); // Extend the mining final block number dsInsuranceFund.miningFinalBlockNumber = dsInsuranceFund.miningFinalBlockNumber.add(_insuranceMiningExtension); emit InsuranceMiningExtended(dsInsuranceFund.miningFinalBlockNumber); } /** * @notice This function adds a new supported collateral type that * can be staked to the insurance fund. It can only * be called via governance. * @dev For vanilla contracts (e.g. USDT, USDC, etc.), the * underlying token equals address(0). * @param _collateralName Name of collateral. * @param _collateralSymbol Symbol of collateral. * @param _underlyingToken Deployed address of underlying token. * @param _collateralToken Deployed address of collateral token. * @param _flavor Collateral flavor (Vanilla, Compound, Aave, etc.). */ function addInsuranceFundCollateral( string memory _collateralName, string memory _collateralSymbol, address _underlyingToken, address _collateralToken, InsuranceFundDefs.Flavor _flavor ) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain bytes32 representation of collateral name bytes32 result; assembly { result := mload(add(_collateralName, 32)) } // Ensure collateral has not already been added require( dsInsuranceFund.stakeCollaterals[result].collateralToken == address(0), "IFund: collateral already added." ); require(_collateralToken != address(0), "IFund: collateral address must be non-zero."); require(!isCollateralTokenPresent(_collateralToken), "IFund: collateral token already present."); require(_underlyingToken != _collateralToken, "IFund: token addresses are same."); if (_flavor == InsuranceFundDefs.Flavor.Vanilla) { // If collateral is of vanilla flavor, there should only be // a value for collateral token, and underlying token should // be empty require(_underlyingToken == address(0), "IFund: underlying address non-zero for Vanilla."); } // Add collateral type to storage, including its underlying // token and collateral token addresses, and its flavor dsInsuranceFund.stakeCollaterals[result].underlyingToken = _underlyingToken; dsInsuranceFund.stakeCollaterals[result].collateralToken = _collateralToken; dsInsuranceFund.stakeCollaterals[result].flavor = _flavor; // Create a DerivaDEX Insurance Fund token contract associated // with this supported collateral dsInsuranceFund.stakeCollaterals[result].diFundToken = IDIFundToken( dsInsuranceFund.diFundTokenFactory.createNewDIFundToken( _collateralName, _collateralSymbol, IERCCustom(_collateralToken).decimals() ) ); dsInsuranceFund.collateralNames.push(result); emit InsuranceFundCollateralAdded(result, _underlyingToken, _collateralToken, _flavor); } /** * @notice This function allows participants to stake a supported * collateral type to the insurance fund. * @param _collateralName Name of collateral. * @param _amount Amount to stake. */ function stakeToInsuranceFund(bytes32 _collateralName, uint96 _amount) external insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Ensure this is a supported collateral type and that the user // has approved the proxy contract for transfer require(stakeCollateral.collateralToken != address(0), "IFund: invalid collateral."); // Ensure non-zero stake amount require(_amount > 0, "IFund: non-zero amount."); // Claim DDX for staking user. We do this prior to the stake // taking effect, thereby preventing someone from being rewarded // instantly for the stake. claimDDXFromInsuranceMining(msg.sender); // Increment the underlying capitalization stakeCollateral.cap = stakeCollateral.cap.add96(_amount); // Transfer collateral amount from user to proxy contract IERC20(stakeCollateral.collateralToken).safeTransferFrom(msg.sender, address(this), _amount); // Mint DIFund tokens to user stakeCollateral.diFundToken.mint(msg.sender, _amount); emit StakedToInsuranceFund(msg.sender, _amount, _collateralName); } /** * @notice This function allows participants to withdraw a supported * collateral type from the insurance fund. * @param _collateralName Name of collateral. * @param _amount Amount to stake. */ function withdrawFromInsuranceFund(bytes32 _collateralName, uint96 _amount) external isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Ensure this is a supported collateral type and that the user // has approved the proxy contract for transfer require(stakeCollateral.collateralToken != address(0), "IFund: invalid collateral."); // Ensure non-zero withdraw amount require(_amount > 0, "IFund: non-zero amount."); // Claim DDX for withdrawing user. We do this prior to the // redeem taking effect. claimDDXFromInsuranceMining(msg.sender); // Determine underlying to transfer based on how much underlying // can be redeemed given the current underlying capitalization // and how many DIFund tokens are globally available. This // theoretically fails in the scenario where globally there are // 0 insurance fund tokens, however that would mean the user // also has 0 tokens in their possession, and thus would have // nothing to be redeemed anyways. uint96 underlyingToTransferNoFee = _amount.proportion96(stakeCollateral.cap, stakeCollateral.diFundToken.totalSupply()); uint96 underlyingToTransfer = underlyingToTransferNoFee.proportion96(dsInsuranceFund.withdrawalFactor, 1e3); // Decrement the capitalization stakeCollateral.cap = stakeCollateral.cap.sub96(underlyingToTransferNoFee); // Increment the withdrawal fee cap stakeCollateral.withdrawalFeeCap = stakeCollateral.withdrawalFeeCap.add96( underlyingToTransferNoFee.sub96(underlyingToTransfer) ); // Transfer collateral amount from proxy contract to user IERC20(stakeCollateral.collateralToken).safeTransfer(msg.sender, underlyingToTransfer); // Burn DIFund tokens being redeemed from user stakeCollateral.diFundToken.burnFrom(msg.sender, _amount); emit WithdrawnFromInsuranceFund(msg.sender, _amount, _collateralName); } /** * @notice Advance other rewards interval */ function advanceOtherRewardsInterval() external otherRewardsOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Check if the current block has exceeded the interval bounds, // allowing for a new other rewards interval to be checkpointed require( block.number >= dsInsuranceFund.otherRewardsCheckpointBlock.add(dsInsuranceFund.interval), "IFund: advance too soon." ); // Maintain the USD-denominated sum of all Compound-flavor // assets. This needs to be stored separately than the rest // due to the way COMP tokens are rewarded to the contract in // order to properly disseminate to the user. uint96 normalizedCapCheckpointSumCompound; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain collateral struct under consideration InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Compound) { // If collateral is of type Compound, set the exchange // rate at this point in time. We do this so later on, // when claiming rewards, we know the exchange rate // checkpointed balances should be converted to // determine the USD-denominated value of holdings // needed to compute fair share of DDX rewards. stakeCollateral.exchangeRate = ICToken(stakeCollateral.collateralToken).exchangeRateStored().safe96( "IFund: amount exceeds 96 bits" ); // Set checkpoint cap for this Compound flavor // collateral to handle COMP distribution lookbacks stakeCollateral.checkpointCap = stakeCollateral.cap; // Increment the normalized Compound checkpoint cap // with the USD-denominated value normalizedCapCheckpointSumCompound = normalizedCapCheckpointSumCompound.add96( getUnderlyingTokenAmountForCompound(stakeCollateral.cap, stakeCollateral.exchangeRate) ); } else if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Aave) { // If collateral is of type Aave, we need to do some // custom Aave aToken reward distribution. We first // determine the contract's aToken balance for this // collateral type and subtract the underlying // aToken capitalization that are due to users. This // leaves us with the excess that has been rewarded // to the contract due to Aave's mechanisms, but // belong to the users. uint96 myATokenBalance = uint96(IAToken(stakeCollateral.collateralToken).balanceOf(address(this)).sub(stakeCollateral.cap)); // Store the aToken yield information dsInsuranceFund.aTokenYields[dsInsuranceFund.collateralNames[i]] = InsuranceFundDefs .ExternalYieldCheckpoint({ accrued: myATokenBalance, totalNormalizedCap: 0 }); } } // Ensure that the normalized cap sum is non-zero if (normalizedCapCheckpointSumCompound > 0) { // If there's Compound-type asset capitalization in the // system, claim COMP accrued to this contract. This COMP is // a result of holding all the cToken deposits from users. // We claim COMP via Compound's Comptroller contract. COMPTROLLER.claimComp(address(this)); // Obtain contract's balance of COMP uint96 myCompBalance = COMP_TOKEN.balanceOf(address(this)).safe96("IFund: amount exceeds 96 bits."); // Store the updated value as the checkpointed COMP yield owed // for this interval dsInsuranceFund.compYields = InsuranceFundDefs.ExternalYieldCheckpoint({ accrued: myCompBalance, totalNormalizedCap: normalizedCapCheckpointSumCompound }); } // Set other rewards checkpoint block to current block dsInsuranceFund.otherRewardsCheckpointBlock = block.number; // Issue DDX reward to trader's on-chain DDX wallet as an // incentive to users calling this function LibTraderInternal.issueDDXReward(dsInsuranceFund.advanceIntervalReward, msg.sender); emit AdvancedOtherRewards(msg.sender, dsInsuranceFund.advanceIntervalReward); } /** * @notice This function gets some high level insurance mining * details. * @return The interval length (blocks) for other rewards * claiming checkpoints (i.e. COMP and extra aTokens). * @return Current insurance mine withdrawal factor. * @return DDX reward for advancing interval. * @return Total global insurance mined amount in DDX. * @return Current insurance mine rate per block. * @return Insurance mining final block number. * @return DDX market state used for continuous DDX payouts. * @return Supported collateral names supported. */ function getInsuranceMineInfo() external view returns ( uint32, uint32, uint96, uint96, uint96, uint256, InsuranceFundDefs.DDXMarketState memory, bytes32[] memory ) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); return ( dsInsuranceFund.interval, dsInsuranceFund.withdrawalFactor, dsInsuranceFund.advanceIntervalReward, dsInsuranceFund.minedAmount, dsInsuranceFund.mineRatePerBlock, dsInsuranceFund.miningFinalBlockNumber, dsInsuranceFund.ddxMarketState, dsInsuranceFund.collateralNames ); } /** * @notice This function gets the current claimant state for a user. * @param _claimant Claimant address. * @return Claimant state. */ function getDDXClaimantState(address _claimant) external view returns (InsuranceFundDefs.DDXClaimantState memory) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); return dsInsuranceFund.ddxClaimantState[_claimant]; } /** * @notice This function gets a supported collateral type's data, * including collateral's token addresses, collateral * flavor/type, current cap and withdrawal amounts, the * latest checkpointed cap, and exchange rate (for cTokens). * An interface for the DerivaDEX Insurance Fund token * corresponding to this collateral is also maintained. * @param _collateralName Name of collateral. * @return Stake collateral. */ function getStakeCollateralByCollateralName(bytes32 _collateralName) external view returns (InsuranceFundDefs.StakeCollateral memory) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); return dsInsuranceFund.stakeCollaterals[_collateralName]; } /** * @notice This function gets unclaimed DDX rewards for a claimant. * @param _claimant Claimant address. * @return Unclaimed DDX rewards. */ function getUnclaimedDDXRewards(address _claimant) external view returns (uint96) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Number of blocks that have elapsed from the last protocol // interaction resulting in DDX accrual. If insurance mining // has ended, we use this as the reference point, so deltaBlocks // will be 0 from the second time onwards. uint256 deltaBlocks = Math.min(block.number, dsInsuranceFund.miningFinalBlockNumber).sub(dsInsuranceFund.ddxMarketState.block); // Save off last index value uint256 index = dsInsuranceFund.ddxMarketState.index; // If number of blocks elapsed and mine rate per block are // non-zero if (deltaBlocks > 0 && dsInsuranceFund.mineRatePerBlock > 0) { // Maintain a running total of USDT-normalized claim tokens // (i.e. 1e6 multiplier) uint256 claimTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claim tokens count with // the current total supply claimTokens = claimTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits") ) ); } // Compute DDX accrued during the time elapsed and the // number of tokens accrued per claim token outstanding uint256 ddxAccrued = deltaBlocks.mul(dsInsuranceFund.mineRatePerBlock); uint256 ratio = claimTokens > 0 ? ddxAccrued.mul(1e36).div(claimTokens) : 0; // Increment the index index = index.add(ratio); } // Obtain the most recent claimant index uint256 ddxClaimantIndex = dsInsuranceFund.ddxClaimantState[_claimant].index; // If the claimant index is 0, i.e. it's the user's first time // interacting with the protocol, initialize it to this starting // value if ((ddxClaimantIndex == 0) && (index > 0)) { ddxClaimantIndex = 1e36; } // Maintain a running total of USDT-normalized claimant tokens // (i.e. 1e6 multiplier) uint256 claimantTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claimant tokens count with // the current balance claimantTokens = claimantTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.balanceOf(_claimant).safe96("IFund: exceeds 96 bits") ) ); } // Compute the unclaimed DDX based on the number of claimant // tokens and the difference between the user's index and the // claimant index computed above return claimantTokens.mul(index.sub(ddxClaimantIndex)).div(1e36).safe96("IFund: exceeds 96 bits"); } /** * @notice Calculate DDX accrued by a claimant and possibly transfer * it to them. * @param _claimant The address of the claimant. */ function claimDDXFromInsuranceMining(address _claimant) public { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Update the DDX Market State in order to determine the amount of // rewards that should be paid to the claimant. updateDDXMarketState(dsInsuranceFund); // Obtain the most recent claimant index uint256 ddxClaimantIndex = dsInsuranceFund.ddxClaimantState[_claimant].index; dsInsuranceFund.ddxClaimantState[_claimant].index = dsInsuranceFund.ddxMarketState.index; // If the claimant index is 0, i.e. it's the user's first time // interacting with the protocol, initialize it to this starting // value if ((ddxClaimantIndex == 0) && (dsInsuranceFund.ddxMarketState.index > 0)) { ddxClaimantIndex = 1e36; } // Compute the difference between the latest DDX market state // index and the claimant's index uint256 deltaIndex = uint256(dsInsuranceFund.ddxMarketState.index).sub(ddxClaimantIndex); // Maintain a running total of USDT-normalized claimant tokens // (i.e. 1e6 multiplier) uint256 claimantTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claimant tokens count with // the current balance claimantTokens = claimantTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.balanceOf(_claimant).safe96("IFund: exceeds 96 bits") ) ); } // Compute the claimed DDX based on the number of claimant // tokens and the difference between the user's index and the // claimant index computed above uint96 claimantDelta = claimantTokens.mul(deltaIndex).div(1e36).safe96("IFund: exceeds 96 bits"); if (claimantDelta != 0) { // Adjust insurance mined amount dsInsuranceFund.minedAmount = dsInsuranceFund.minedAmount.add96(claimantDelta); // Increment the insurance mined claimed DDX for claimant dsInsuranceFund.ddxClaimantState[_claimant].claimedDDX = dsInsuranceFund.ddxClaimantState[_claimant] .claimedDDX .add96(claimantDelta); // Mint the DDX governance/operational token claimed reward // from the proxy contract to the participant LibTraderInternal.issueDDXReward(claimantDelta, _claimant); } // Check if COMP or aTokens have not already been claimed if (dsInsuranceFund.stakerToOtherRewardsClaims[_claimant] < dsInsuranceFund.otherRewardsCheckpointBlock) { // Record the current block number preventing a user from // reclaiming the COMP reward unfairly dsInsuranceFund.stakerToOtherRewardsClaims[_claimant] = block.number; // Claim COMP and extra aTokens claimOtherRewardsFromInsuranceMining(_claimant); } emit InsuranceMineRewardsClaimed(_claimant, claimantDelta); } /** * @notice Get USDT-normalized collateral token amount. * @param _collateralName The collateral name. * @param _value The number of tokens. */ function getNormalizedCollateralValue(bytes32 _collateralName, uint96 _value) public view returns (uint96) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; return (stakeCollateral.flavor != InsuranceFundDefs.Flavor.Compound) ? getUnderlyingTokenAmountForVanilla(_value, stakeCollateral.collateralToken) : getUnderlyingTokenAmountForCompound( _value, ICToken(stakeCollateral.collateralToken).exchangeRateStored() ); } /** * @notice This function gets a participant's current * USD-normalized/denominated stake and global * USD-normalized/denominated stake across all supported * collateral types. * @param _staker Participant's address. * @return Current USD redemption value of DIFund tokens staked. * @return Current USD global cap. */ function getCurrentTotalStakes(address _staker) public view returns (uint96, uint96) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Maintain running totals uint96 normalizedStakerStakeSum; uint96 normalizedGlobalCapSum; // Loop through each supported collateral for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { (, , uint96 normalizedStakerStake, uint96 normalizedGlobalCap) = getCurrentStakeByCollateralNameAndStaker(dsInsuranceFund.collateralNames[i], _staker); normalizedStakerStakeSum = normalizedStakerStakeSum.add96(normalizedStakerStake); normalizedGlobalCapSum = normalizedGlobalCapSum.add96(normalizedGlobalCap); } return (normalizedStakerStakeSum, normalizedGlobalCapSum); } /** * @notice This function gets a participant's current DIFund token * holdings and global DIFund token holdings for a * collateral type and staker, in addition to the * USD-normalized collateral in the system and the * redemption value for the staker. * @param _collateralName Name of collateral. * @param _staker Participant's address. * @return DIFund tokens for staker. * @return DIFund tokens globally. * @return Redemption value for staker (USD-denominated). * @return Underlying collateral (USD-denominated) in staking system. */ function getCurrentStakeByCollateralNameAndStaker(bytes32 _collateralName, address _staker) public view returns ( uint96, uint96, uint96, uint96 ) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Get DIFund tokens for staker uint96 stakerStake = stakeCollateral.diFundToken.balanceOf(_staker).safe96("IFund: exceeds 96 bits."); // Get DIFund tokens globally uint96 globalCap = stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits."); // Compute global USD-denominated stake capitalization. This is // is straightforward for non-Compound assets, but requires // exchange rate conversion for Compound assets. uint96 normalizedGlobalCap = (stakeCollateral.flavor != InsuranceFundDefs.Flavor.Compound) ? getUnderlyingTokenAmountForVanilla(stakeCollateral.cap, stakeCollateral.collateralToken) : getUnderlyingTokenAmountForCompound( stakeCollateral.cap, ICToken(stakeCollateral.collateralToken).exchangeRateStored() ); // Compute the redemption value (USD-normalized) for staker // given DIFund token holdings uint96 normalizedStakerStake = globalCap > 0 ? normalizedGlobalCap.proportion96(stakerStake, globalCap) : 0; return (stakerStake, globalCap, normalizedStakerStake, normalizedGlobalCap); } /** * @notice This function gets a participant's DIFund token * holdings and global DIFund token holdings for Compound * and Aave tokens for a collateral type and staker as of * the checkpointed block, in addition to the * USD-normalized collateral in the system and the * redemption value for the staker. * @param _collateralName Name of collateral. * @param _staker Participant's address. * @return DIFund tokens for staker. * @return DIFund tokens globally. * @return Redemption value for staker (USD-denominated). * @return Underlying collateral (USD-denominated) in staking system. */ function getOtherRewardsStakeByCollateralNameAndStaker(bytes32 _collateralName, address _staker) public view returns ( uint96, uint96, uint96, uint96 ) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Get DIFund tokens for staker as of the checkpointed block uint96 stakerStake = stakeCollateral.diFundToken.getPriorValues(_staker, dsInsuranceFund.otherRewardsCheckpointBlock.sub(1)); // Get DIFund tokens globally as of the checkpointed block uint96 globalCap = stakeCollateral.diFundToken.getTotalPriorValues(dsInsuranceFund.otherRewardsCheckpointBlock.sub(1)); // If Aave, don't worry about the normalized values since 1-1 if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Aave) { return (stakerStake, globalCap, 0, 0); } // Compute global USD-denominated stake capitalization. This is // is straightforward for non-Compound assets, but requires // exchange rate conversion for Compound assets. uint96 normalizedGlobalCap = getUnderlyingTokenAmountForCompound(stakeCollateral.checkpointCap, stakeCollateral.exchangeRate); // Compute the redemption value (USD-normalized) for staker // given DIFund token holdings uint96 normalizedStakerStake = globalCap > 0 ? normalizedGlobalCap.proportion96(stakerStake, globalCap) : 0; return (stakerStake, globalCap, normalizedStakerStake, normalizedGlobalCap); } /** * @notice Claim other rewards (COMP and aTokens) for a claimant. * @param _claimant The address for the claimant. */ function claimOtherRewardsFromInsuranceMining(address _claimant) internal { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Maintain a running total of COMP to be claimed from // insurance mining contract as a by product of cToken deposits uint96 compClaimedAmountSum; // Loop through collateral names that are supported for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain collateral struct under consideration InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Vanilla) { // If collateral is of Vanilla flavor, we just // continue... continue; } // Compute the DIFund token holdings and the normalized, // USDT-normalized collateral value for the user (uint96 collateralStaker, uint96 collateralTotal, uint96 normalizedCollateralStaker, ) = getOtherRewardsStakeByCollateralNameAndStaker(dsInsuranceFund.collateralNames[i], _claimant); if ((collateralTotal == 0) || (collateralStaker == 0)) { // If there are no DIFund tokens, there is no reason to // claim rewards, so we continue... continue; } if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Aave) { // Aave has a special circumstance, where every // aToken results in additional aTokens accruing // to the holder's wallet. In this case, this is // the DerivaDEX contract. Therefore, we must // appropriately distribute the extra aTokens to // users claiming DDX for their aToken deposits. transferTokensAave(_claimant, dsInsuranceFund.collateralNames[i], collateralStaker, collateralTotal); } else if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Compound) { // If collateral is of type Compound, determine the // COMP claimant is entitled to based on the COMP // yield for this interval, the claimant's // DIFundToken share, and the USD-denominated // share for this market. uint96 compClaimedAmount = dsInsuranceFund.compYields.accrued.proportion96( normalizedCollateralStaker, dsInsuranceFund.compYields.totalNormalizedCap ); // Increment the COMP claimed sum to be paid out // later compClaimedAmountSum = compClaimedAmountSum.add96(compClaimedAmount); } } // Distribute any COMP to be shared with the user if (compClaimedAmountSum > 0) { transferTokensCompound(_claimant, compClaimedAmountSum); } } /** * @notice This function transfers extra Aave aTokens to claimant. */ function transferTokensAave( address _claimant, bytes32 _collateralName, uint96 _aaveStaker, uint96 _aaveTotal ) internal { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain collateral struct under consideration InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; uint96 aTokenClaimedAmount = dsInsuranceFund.aTokenYields[_collateralName].accrued.proportion96(_aaveStaker, _aaveTotal); // Continues in scenarios token transfer fails (such as // transferring 0 tokens) try IAToken(stakeCollateral.collateralToken).transfer(_claimant, aTokenClaimedAmount) {} catch {} } /** * @notice This function transfers COMP tokens from the contract to * a recipient. * @param _amount Amount of COMP to receive. */ function transferTokensCompound(address _claimant, uint96 _amount) internal { // Continues in scenarios token transfer fails (such as // transferring 0 tokens) try COMP_TOKEN.transfer(_claimant, _amount) {} catch {} } /** * @notice Updates the DDX market state to ensure that claimants can receive * their earned DDX rewards. */ function updateDDXMarketState(LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund) internal { // Number of blocks that have elapsed from the last protocol // interaction resulting in DDX accrual. If insurance mining // has ended, we use this as the reference point, so deltaBlocks // will be 0 from the second time onwards. uint256 endBlock = Math.min(block.number, dsInsuranceFund.miningFinalBlockNumber); uint256 deltaBlocks = endBlock.sub(dsInsuranceFund.ddxMarketState.block); // If number of blocks elapsed and mine rate per block are // non-zero if (deltaBlocks > 0 && dsInsuranceFund.mineRatePerBlock > 0) { // Maintain a running total of USDT-normalized claim tokens // (i.e. 1e6 multiplier) uint256 claimTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claim tokens count with // the current total supply claimTokens = claimTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits") ) ); } // Compute DDX accrued during the time elapsed and the // number of tokens accrued per claim token outstanding uint256 ddxAccrued = deltaBlocks.mul(dsInsuranceFund.mineRatePerBlock); uint256 ratio = claimTokens > 0 ? ddxAccrued.mul(1e36).div(claimTokens) : 0; // Increment the index uint256 index = uint256(dsInsuranceFund.ddxMarketState.index).add(ratio); // Update the claim ddx market state with the new index // and block dsInsuranceFund.ddxMarketState.index = index.safe224("IFund: exceeds 224 bits"); dsInsuranceFund.ddxMarketState.block = endBlock.safe32("IFund: exceeds 32 bits"); } else if (deltaBlocks > 0) { dsInsuranceFund.ddxMarketState.block = endBlock.safe32("IFund: exceeds 32 bits"); } } /** * @notice This function checks if a collateral token is present. * @param _collateralToken Collateral token address. * @return Whether collateral token is present or not. */ function isCollateralTokenPresent(address _collateralToken) internal view returns (bool) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Return true if collateral token has been added if ( dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]].collateralToken == _collateralToken ) { return true; } } // Collateral token has not been added, return false return false; } /** * @notice This function computes the underlying token amount for a * vanilla token. * @param _vanillaAmount Number of vanilla tokens. * @param _collateral Address of vanilla collateral. * @return Underlying token amount. */ function getUnderlyingTokenAmountForVanilla(uint96 _vanillaAmount, address _collateral) internal view returns (uint96) { uint256 vanillaDecimals = uint256(IERCCustom(_collateral).decimals()); if (vanillaDecimals >= 6) { return uint256(_vanillaAmount).div(10**(vanillaDecimals.sub(6))).safe96("IFund: amount exceeds 96 bits"); } return uint256(_vanillaAmount).mul(10**(uint256(6).sub(vanillaDecimals))).safe96("IFund: amount exceeds 96 bits"); } /** * @notice This function computes the underlying token amount for a * cToken amount by computing the current exchange rate. * @param _cTokenAmount Number of cTokens. * @param _exchangeRate Exchange rate derived from Compound. * @return Underlying token amount. */ function getUnderlyingTokenAmountForCompound(uint96 _cTokenAmount, uint256 _exchangeRate) internal pure returns (uint96) { return _exchangeRate.mul(_cTokenAmount).div(1e18).safe96("IFund: amount exceeds 96 bits."); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath32 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add32(uint32 a, uint32 b) internal pure returns (uint32) { uint32 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 sub32(uint32 a, uint32 b) internal pure returns (uint32) { return sub32(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 sub32( uint32 a, uint32 b, string memory errorMessage ) internal pure returns (uint32) { require(b <= a, errorMessage); uint32 c = a - b; return c; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { Math } from "openzeppelin-solidity/contracts/math/Math.sol"; import { SafeMath96 } from "./SafeMath96.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 MathHelpers { using SafeMath96 for uint96; using SafeMath for uint256; function proportion96( uint96 a, uint256 b, uint256 c ) internal pure returns (uint96) { return safe96(uint256(a).mul(b).div(c), "Amount exceeds 96 bits"); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } /** * @dev Returns the largest of two numbers. */ function clamp96( uint96 a, uint256 b, uint256 c ) internal pure returns (uint96) { return safe96(Math.min(Math.max(a, b), c), "Amount exceeds 96 bits"); } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { IDIFundToken } from "../../tokens/interfaces/IDIFundToken.sol"; /** * @title InsuranceFundDefs * @author DerivaDEX * * This library contains the common structs and enums pertaining to * the insurance fund. */ library InsuranceFundDefs { // DDX market state maintaining claim index and last updated block struct DDXMarketState { uint224 index; uint32 block; } // DDX claimant state maintaining claim index and claimed DDX struct DDXClaimantState { uint256 index; uint96 claimedDDX; } // Supported collateral struct consisting of the collateral's token // addresses, collateral flavor/type, current cap and withdrawal // amounts, the latest checkpointed cap, and exchange rate (for // cTokens). An interface for the DerivaDEX Insurance Fund token // corresponding to this collateral is also maintained. struct StakeCollateral { address underlyingToken; address collateralToken; IDIFundToken diFundToken; uint96 cap; uint96 withdrawalFeeCap; uint96 checkpointCap; uint96 exchangeRate; Flavor flavor; } // Contains the yield accrued and the total normalized cap. // Total normalized cap is maintained for Compound flavors so COMP // distribution can be paid out properly struct ExternalYieldCheckpoint { uint96 accrued; uint96 totalNormalizedCap; } // Type of collateral enum Flavor { Vanilla, Compound, Aave } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { InsuranceFundDefs } from "../libs/defs/InsuranceFundDefs.sol"; import { IDIFundTokenFactory } from "../tokens/interfaces/IDIFundTokenFactory.sol"; library LibDiamondStorageInsuranceFund { struct DiamondStorageInsuranceFund { // List of supported collateral names bytes32[] collateralNames; // Collateral name to stake collateral struct mapping(bytes32 => InsuranceFundDefs.StakeCollateral) stakeCollaterals; mapping(address => InsuranceFundDefs.DDXClaimantState) ddxClaimantState; // aToken name to yield checkpoints mapping(bytes32 => InsuranceFundDefs.ExternalYieldCheckpoint) aTokenYields; mapping(address => uint256) stakerToOtherRewardsClaims; // Interval to COMP yield checkpoint InsuranceFundDefs.ExternalYieldCheckpoint compYields; // Set the interval for other rewards claiming checkpoints // (i.e. COMP and aTokens that accrue to the contract) // (e.g. 40320 ~ 1 week = 7 * 24 * 60 * 60 / 15 blocks) uint32 interval; // Current insurance mining withdrawal factor uint32 withdrawalFactor; // DDX to be issued per block as insurance mining reward uint96 mineRatePerBlock; // Incentive to advance the insurance mining interval // (e.g. 100e18 = 100 DDX) uint96 advanceIntervalReward; // Total DDX insurance mined uint96 minedAmount; // Insurance fund capitalization due to liquidations and fees uint96 liqAndFeeCapitalization; // Checkpoint block for other rewards uint256 otherRewardsCheckpointBlock; // Insurance mining final block number uint256 miningFinalBlockNumber; InsuranceFundDefs.DDXMarketState ddxMarketState; IDIFundTokenFactory diFundTokenFactory; } bytes32 constant DIAMOND_STORAGE_POSITION_INSURANCE_FUND = keccak256("diamond.standard.diamond.storage.DerivaDEX.InsuranceFund"); function diamondStorageInsuranceFund() internal pure returns (DiamondStorageInsuranceFund storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_INSURANCE_FUND; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; library LibDiamondStoragePause { struct DiamondStoragePause { bool isPaused; } bytes32 constant DIAMOND_STORAGE_POSITION_PAUSE = keccak256("diamond.standard.diamond.storage.DerivaDEX.Pause"); function diamondStoragePause() internal pure returns (DiamondStoragePause storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_PAUSE; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IAToken { function decimals() external returns (uint256); function transfer(address _recipient, uint256 _amount) external; function balanceOf(address _user) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; abstract contract IComptroller { struct CompMarketState { uint224 index; uint32 block; } /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; // solhint-disable-line const-name-snakecase // @notice The COMP market supply state for each market mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP mapping(address => mapping(address => uint256)) public compSupplierIndex; /// @notice The portion of compRate that each market currently receives mapping(address => uint256) public compSpeeds; /// @notice The COMP accrued but not yet transferred to each user mapping(address => uint256) public compAccrued; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external virtual returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external virtual; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external virtual returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external virtual; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external virtual returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external virtual; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external virtual returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external virtual; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external virtual returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external virtual; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external virtual returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external virtual; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external virtual returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external virtual; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external virtual returns (uint256, uint256); function claimComp(address holder) public virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface ICToken { function accrueInterest() external returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function balanceOfUnderlying(address owner) external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function totalBorrowsCurrent() external returns (uint256); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function decimals() external view returns (uint256); function exchangeRateStored() external view returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function getCash() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title IDIFundToken * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the native token contract for DerivaDEX. It * implements the ERC-20 standard, with additional * functionality to efficiently handle the governance aspect of * the DerivaDEX ecosystem. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DDX token makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances, allowances, and * voting checkpoints, this allows us to more efficiently pack * data together, thereby resulting in cheaper transactions. */ interface IDIFundToken { function transfer(address _recipient, uint256 _amount) external returns (bool); function mint(address _recipient, uint256 _amount) external; function burnFrom(address _account, uint256 _amount) external; function delegate(address _delegatee) external; function transferFrom( address _sender, address _recipient, uint256 _amount ) external returns (bool); function approve(address _spender, uint256 _amount) external returns (bool); function getPriorValues(address account, uint256 blockNumber) external view returns (uint96); function getTotalPriorValues(uint256 blockNumber) external view returns (uint96); function balanceOf(address _account) external view returns (uint256); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { DIFundToken } from "../DIFundToken.sol"; /** * @title DIFundToken * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the token contract for tokenized DerivaDEX insurance * fund positions. It implements the ERC-20 standard, with * additional functionality around snapshotting user and global * balances. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DIFundToken makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances and allowances, this * allows us to more efficiently pack data together, thereby * resulting in cheaper transactions. */ interface IDIFundTokenFactory { function createNewDIFundToken( string calldata _name, string calldata _symbol, uint8 _decimals ) external returns (address); function diFundTokens(uint256 index) external returns (DIFundToken); function issuer() external view returns (address); function getDIFundTokens() external view returns (DIFundToken[] memory); function getDIFundTokensLength() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { LibBytes } from "../libs/LibBytes.sol"; import { LibEIP712 } from "../libs/LibEIP712.sol"; import { LibPermit } from "../libs/LibPermit.sol"; import { SafeMath96 } from "../libs/SafeMath96.sol"; import { IInsuranceFund } from "../facets/interfaces/IInsuranceFund.sol"; /** * @title DIFundToken * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the token contract for tokenized DerivaDEX insurance * fund positions. It implements the ERC-20 standard, with * additional functionality around snapshotting user and global * balances. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DIFundToken makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances and allowances, this * allows us to more efficiently pack data together, thereby * resulting in cheaper transactions. */ contract DIFundToken { using SafeMath96 for uint96; using SafeMath for uint256; using LibBytes for bytes; uint256 internal _totalSupply; string private _name; string private _symbol; string private _version; uint8 private _decimals; /// @notice Address authorized to issue/mint DDX tokens address public issuer; mapping(address => mapping(address => uint96)) internal allowances; mapping(address => uint96) internal balances; /// @notice A checkpoint for marking vote count from given block struct Checkpoint { uint32 id; uint96 values; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint256 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint256) public numCheckpoints; mapping(uint256 => Checkpoint) totalCheckpoints; uint256 numTotalCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice Emitted when a user account's balance changes event ValuesChanged(address indexed user, uint96 previousValue, uint96 newValue); /// @notice Emitted when a user account's balance changes event TotalValuesChanged(uint96 previousValue, uint96 newValue); /// @notice Emitted when transfer takes place event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice Emitted when approval takes place event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new DIFundToken token */ constructor( string memory name, string memory symbol, uint8 decimals, address _issuer ) public { _name = name; _symbol = symbol; _decimals = decimals; _version = "1"; // Set issuer to deploying address issuer = _issuer; } /** * @notice Returns the name of the token. * @return Name of the token. */ function name() public view returns (string memory) { return _name; } /** * @notice Returns the symbol of the token. * @return Symbol of the token. */ 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}. * @return Number of decimals. */ function decimals() public view returns (uint8) { return _decimals; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param _spender The address of the account which may transfer tokens * @param _amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address _spender, uint256 _amount) external returns (bool) { require(_spender != address(0), "DIFT: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Set allowance allowances[msg.sender][_spender] = amount; emit Approval(msg.sender, _spender, _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) external returns (bool) { require(_spender != address(0), "DIFT: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_addedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_addedValue, "DIFT: amount exceeds 96 bits."); } // Increase allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].add96(amount); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); 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) external returns (bool) { require(_spender != address(0), "DIFT: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_subtractedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_subtractedValue, "DIFT: amount exceeds 96 bits."); } // Decrease allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].sub96( amount, "DIFT: decreased allowance below zero." ); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); 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 (uint256) { return balances[_account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address _recipient, uint256 _amount) external returns (bool) { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Claim DDX rewards on behalf of the sender IInsuranceFund(issuer).claimDDXFromInsuranceMining(msg.sender); // Claim DDX rewards on behalf of the recipient IInsuranceFund(issuer).claimDDXFromInsuranceMining(_recipient); // Transfer tokens from sender to recipient _transferTokens(msg.sender, _recipient, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param _sender The address of the source account * @param _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address _sender, address _recipient, uint256 _amount ) external returns (bool) { uint96 spenderAllowance = allowances[_sender][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } if (msg.sender != _sender && spenderAllowance != uint96(-1)) { // Tx sender is not the same as transfer sender and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount); allowances[_sender][msg.sender] = newAllowance; emit Approval(_sender, msg.sender, newAllowance); } // Claim DDX rewards on behalf of the sender IInsuranceFund(issuer).claimDDXFromInsuranceMining(_sender); // Claim DDX rewards on behalf of the recipient IInsuranceFund(issuer).claimDDXFromInsuranceMining(_recipient); // Transfer tokens from sender to recipient _transferTokens(_sender, _recipient, amount); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function mint(address _recipient, uint256 _amount) external { require(msg.sender == issuer, "DIFT: unauthorized mint."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Mint tokens to recipient _transferTokensMint(_recipient, amount); } /** * @dev Creates `amount` tokens and assigns them to `account`, decreasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function burn(uint256 _amount) external { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Burn tokens from sender _transferTokensBurn(msg.sender, 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 burnFrom(address _account, uint256 _amount) external { uint96 spenderAllowance = allowances[_account][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } if (msg.sender != _account && spenderAllowance != uint96(-1) && msg.sender != issuer) { // Tx sender is not the same as burn account and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount, "DIFT: burn amount exceeds allowance."); allowances[_account][msg.sender] = newAllowance; emit Approval(_account, msg.sender, newAllowance); } // Burn tokens from account _transferTokensBurn(_account, amount); } /** * @notice Permits allowance from signatory to `spender` * @param _spender The spender being approved * @param _value The value being approved * @param _nonce The contract state required to match the signature * @param _expiry The time at which to expire the signature * @param _signature Signature */ function permit( address _spender, uint256 _value, uint256 _nonce, uint256 _expiry, bytes memory _signature ) external { // Perform EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(_name, _version, getChainId(), address(this)); bytes32 permitHash = LibPermit.getPermitHash( LibPermit.Permit({ spender: _spender, value: _value, nonce: _nonce, expiry: _expiry }), eip712OrderParamsDomainHash ); // Perform sig recovery uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } address recovered = ecrecover(permitHash, v, r, s); require(recovered != address(0), "DIFT: invalid signature."); require(_nonce == nonces[recovered]++, "DIFT: invalid nonce."); require(block.timestamp <= _expiry, "DIFT: signature expired."); // Convert amount to uint96 uint96 amount; if (_value == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_value, "DIFT: amount exceeds 96 bits."); } // Set allowance allowances[recovered][_spender] = amount; emit Approval(recovered, _spender, _value); } /** * @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 (uint256) { return allowances[_account][_spender]; } /** * @notice Get the total max supply of DDX tokens * @return The total max supply of DDX */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @notice Determine the prior number of values 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 values the account had as of the given block */ function getPriorValues(address _account, uint256 _blockNumber) external view returns (uint96) { require(_blockNumber < block.number, "DIFT: block not yet determined."); uint256 numCheckpointsAccount = numCheckpoints[_account]; if (numCheckpointsAccount == 0) { return 0; } // First check most recent balance if (checkpoints[_account][numCheckpointsAccount - 1].id <= _blockNumber) { return checkpoints[_account][numCheckpointsAccount - 1].values; } // Next check implicit zero balance if (checkpoints[_account][0].id > _blockNumber) { return 0; } // Perform binary search to find the most recent token holdings uint256 lower = 0; uint256 upper = numCheckpointsAccount - 1; while (upper > lower) { // ceil, avoiding overflow uint256 center = upper - (upper - lower) / 2; Checkpoint memory cp = checkpoints[_account][center]; if (cp.id == _blockNumber) { return cp.values; } else if (cp.id < _blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[_account][lower].values; } /** * @notice Determine the prior number of values 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 _blockNumber The block number to get the vote balance at * @return The number of values the account had as of the given block */ function getTotalPriorValues(uint256 _blockNumber) external view returns (uint96) { require(_blockNumber < block.number, "DIFT: block not yet determined."); if (numTotalCheckpoints == 0) { return 0; } // First check most recent balance if (totalCheckpoints[numTotalCheckpoints - 1].id <= _blockNumber) { return totalCheckpoints[numTotalCheckpoints - 1].values; } // Next check implicit zero balance if (totalCheckpoints[0].id > _blockNumber) { return 0; } // Perform binary search to find the most recent token holdings // leading to a measure of voting power uint256 lower = 0; uint256 upper = numTotalCheckpoints - 1; while (upper > lower) { // ceil, avoiding overflow uint256 center = upper - (upper - lower) / 2; Checkpoint memory cp = totalCheckpoints[center]; if (cp.id == _blockNumber) { return cp.values; } else if (cp.id < _blockNumber) { lower = center; } else { upper = center - 1; } } return totalCheckpoints[lower].values; } function _transferTokens( address _spender, address _recipient, uint96 _amount ) internal { require(_spender != address(0), "DIFT: cannot transfer from the zero address."); require(_recipient != address(0), "DIFT: cannot transfer to the zero address."); // Reduce spender's balance and increase recipient balance balances[_spender] = balances[_spender].sub96(_amount); balances[_recipient] = balances[_recipient].add96(_amount); emit Transfer(_spender, _recipient, _amount); // Move values from spender to recipient _moveTokens(_spender, _recipient, _amount); } function _transferTokensMint(address _recipient, uint96 _amount) internal { require(_recipient != address(0), "DIFT: cannot transfer to the zero address."); // Add to recipient's balance balances[_recipient] = balances[_recipient].add96(_amount); _totalSupply = _totalSupply.add(_amount); emit Transfer(address(0), _recipient, _amount); // Add value to recipient's checkpoint _moveTokens(address(0), _recipient, _amount); _writeTotalCheckpoint(_amount, true); } function _transferTokensBurn(address _spender, uint96 _amount) internal { require(_spender != address(0), "DIFT: cannot transfer from the zero address."); // Reduce the spender/burner's balance balances[_spender] = balances[_spender].sub96(_amount, "DIFT: not enough balance to burn."); // Reduce the circulating supply _totalSupply = _totalSupply.sub(_amount); emit Transfer(_spender, address(0), _amount); // Reduce value from spender's checkpoint _moveTokens(_spender, address(0), _amount); _writeTotalCheckpoint(_amount, false); } function _moveTokens( address _initUser, address _finUser, uint96 _amount ) internal { if (_initUser != _finUser && _amount > 0) { // Initial user address is different than final // user address and nonzero number of values moved if (_initUser != address(0)) { uint256 initUserNum = numCheckpoints[_initUser]; // Retrieve and compute the old and new initial user // address' values uint96 initUserOld = initUserNum > 0 ? checkpoints[_initUser][initUserNum - 1].values : 0; uint96 initUserNew = initUserOld.sub96(_amount); _writeCheckpoint(_initUser, initUserOld, initUserNew); } if (_finUser != address(0)) { uint256 finUserNum = numCheckpoints[_finUser]; // Retrieve and compute the old and new final user // address' values uint96 finUserOld = finUserNum > 0 ? checkpoints[_finUser][finUserNum - 1].values : 0; uint96 finUserNew = finUserOld.add96(_amount); _writeCheckpoint(_finUser, finUserOld, finUserNew); } } } function _writeCheckpoint( address _user, uint96 _oldValues, uint96 _newValues ) internal { uint32 blockNumber = safe32(block.number, "DIFT: exceeds 32 bits."); uint256 userNum = numCheckpoints[_user]; if (userNum > 0 && checkpoints[_user][userNum - 1].id == blockNumber) { // If latest checkpoint is current block, edit in place checkpoints[_user][userNum - 1].values = _newValues; } else { // Create a new id, value pair checkpoints[_user][userNum] = Checkpoint({ id: blockNumber, values: _newValues }); numCheckpoints[_user] = userNum.add(1); } emit ValuesChanged(_user, _oldValues, _newValues); } function _writeTotalCheckpoint(uint96 _amount, bool increase) internal { if (_amount > 0) { uint32 blockNumber = safe32(block.number, "DIFT: exceeds 32 bits."); uint96 oldValues = numTotalCheckpoints > 0 ? totalCheckpoints[numTotalCheckpoints - 1].values : 0; uint96 newValues = increase ? oldValues.add96(_amount) : oldValues.sub96(_amount); if (numTotalCheckpoints > 0 && totalCheckpoints[numTotalCheckpoints - 1].id == block.number) { // If latest checkpoint is current block, edit in place totalCheckpoints[numTotalCheckpoints - 1].values = newValues; } else { // Create a new id, value pair totalCheckpoints[numTotalCheckpoints].id = blockNumber; totalCheckpoints[numTotalCheckpoints].values = newValues; numTotalCheckpoints = numTotalCheckpoints.add(1); } emit TotalValuesChanged(oldValues, newValues); } } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT /* 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.6.12; library LibBytes { using LibBytes for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } return memoryAddress; } /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for { } lt(source, sEnd) { } { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for { } slt(dest, dEnd) { } { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require(from <= to, "FROM_LESS_THAN_TO_REQUIRED"); require(to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED"); // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy(result.contentAddress(), b.contentAddress() + from, result.length); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require(from <= to, "FROM_LESS_THAN_TO_REQUIRED"); require(to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED"); // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return result The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { require(b.length > 0, "GREATER_THAN_ZERO_LENGTH_REQUIRED"); // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Pops the last 20 bytes off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return result The 20 byte address that was popped off. function popLast20Bytes(bytes memory b) internal pure returns (address result) { require(b.length >= 20, "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"); // Store last 20 bytes. result = readAddress(b, b.length - 20); assembly { // Subtract 20 from byte array length. let newLen := sub(mload(b), 20) mstore(b, newLen) } return result; } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return equal True if arrays are the same. False otherwise. function equals(bytes memory lhs, bytes memory rhs) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return result address from byte array. function readAddress(bytes memory b, uint256 index) internal pure returns (address result) { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function writeAddress( bytes memory b, uint256 index, address input ) internal pure { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Store address into array memory assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) } } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return result bytes32 value from byte array. function readBytes32(bytes memory b, uint256 index) internal pure returns (bytes32 result) { require(b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function writeBytes32( bytes memory b, uint256 index, bytes32 input ) internal pure { require(b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { mstore(add(b, index), input) } } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return result uint256 value from byte array. function readUint256(bytes memory b, uint256 index) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return result bytes4 value from byte array. function readBytes4(bytes memory b, uint256 index) internal pure returns (bytes4 result) { require(b.length >= index + 4, "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED"); // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Reads nested bytes from a specific position. /// @dev NOTE: the returned value overlaps with the input value. /// Both should be treated as immutable. /// @param b Byte array containing nested bytes. /// @param index Index of nested bytes. /// @return result Nested bytes. function readBytesWithLength(bytes memory b, uint256 index) internal pure returns (bytes memory result) { // Read length of nested bytes uint256 nestedBytesLength = readUint256(b, index); index += 32; // Assert length of <b> is valid, given // length of nested bytes require(b.length >= index + nestedBytesLength, "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"); // Return a pointer to the byte array as it exists inside `b` assembly { result := add(b, index) } return result; } /// @dev Inserts bytes at a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes to insert. function writeBytesWithLength( bytes memory b, uint256 index, bytes memory input ) internal pure { // Assert length of <b> is valid, given // length of input require( b.length >= index + 32 + input.length, // 32 bytes to store length "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED" ); // Copy <input> into <b> memCopy( b.contentAddress() + index, input.rawAddress(), // includes length of <input> input.length + 32 // +32 bytes to store <input> length ); } /// @dev Performs a deep copy of a byte array onto another byte array of greater than or equal length. /// @param dest Byte array that will be overwritten with source bytes. /// @param source Byte array to copy onto dest bytes. function deepCopyBytes(bytes memory dest, bytes memory source) internal pure { uint256 sourceLen = source.length; // Dest length must be >= source length, or some bytes would not be copied. require(dest.length >= sourceLen, "GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED"); memCopy(dest.contentAddress(), source.contentAddress(), sourceLen); } } // SPDX-License-Identifier: MIT /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.12; library LibEIP712 { // Hash of the EIP712 Domain Separator Schema // keccak256(abi.encodePacked( // "EIP712Domain(", // "string name,", // "string version,", // "uint256 chainId,", // "address verifyingContract", // ")" // )) bytes32 internal constant _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; /// @dev Calculates a EIP712 domain separator. /// @param name The EIP712 domain name. /// @param version The EIP712 domain version. /// @param verifyingContract The EIP712 verifying contract. /// @return result EIP712 domain separator. function hashEIP712Domain( string memory name, string memory version, uint256 chainId, address verifyingContract ) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH; // Assembly for more efficient computing: // keccak256(abi.encodePacked( // _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, // keccak256(bytes(name)), // keccak256(bytes(version)), // chainId, // uint256(verifyingContract) // )) assembly { // Calculate hashes of dynamic data let nameHash := keccak256(add(name, 32), mload(name)) let versionHash := keccak256(add(version, 32), mload(version)) // Load free memory pointer let memPtr := mload(64) // Store params in memory mstore(memPtr, schemaHash) mstore(add(memPtr, 32), nameHash) mstore(add(memPtr, 64), versionHash) mstore(add(memPtr, 96), chainId) mstore(add(memPtr, 128), verifyingContract) // Compute hash result := keccak256(memPtr, 160) } return result; } /// @dev Calculates EIP712 encoding for a hash struct with a given domain hash. /// @param eip712DomainHash Hash of the domain domain separator data, computed /// with getDomainHash(). /// @param hashStruct The EIP712 hash struct. /// @return result EIP712 hash applied to the given EIP712 Domain. function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) internal pure returns (bytes32 result) { // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, // EIP712_DOMAIN_HASH, // hashStruct // )); assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } // SPDX-License-Identifier: MIT /* 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.6.12; import { LibEIP712 } from "./LibEIP712.sol"; library LibPermit { struct Permit { address spender; // Spender uint256 value; // Value uint256 nonce; // Nonce uint256 expiry; // Expiry } // Hash for the EIP712 LibPermit Schema // bytes32 constant internal EIP712_PERMIT_SCHEMA_HASH = keccak256(abi.encodePacked( // "Permit(", // "address spender,", // "uint256 value,", // "uint256 nonce,", // "uint256 expiry", // ")" // )); bytes32 internal constant EIP712_PERMIT_SCHEMA_HASH = 0x58e19c95adc541dea238d3211d11e11e7def7d0c7fda4e10e0c45eb224ef2fb7; /// @dev Calculates Keccak-256 hash of the permit. /// @param permit The permit structure. /// @return permitHash Keccak-256 EIP712 hash of the permit. function getPermitHash(Permit memory permit, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 permitHash) { permitHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashPermit(permit)); return permitHash; } /// @dev Calculates EIP712 hash of the permit. /// @param permit The permit structure. /// @return result EIP712 hash of the permit. function hashPermit(Permit memory permit) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_PERMIT_SCHEMA_HASH; assembly { // Assert permit offset (this is an internal error that should never be triggered) if lt(permit, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(permit, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 160) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IInsuranceFund { function claimDDXFromInsuranceMining(address _claimant) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { LibBytes } from "../libs/LibBytes.sol"; import { LibEIP712 } from "../libs/LibEIP712.sol"; import { LibPermit } from "../libs/LibPermit.sol"; import { SafeMath96 } from "../libs/SafeMath96.sol"; import { DIFundToken } from "./DIFundToken.sol"; /** * @title DIFundTokenFactory * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the native token contract for DerivaDEX. It * implements the ERC-20 standard, with additional * functionality to efficiently handle the governance aspect of * the DerivaDEX ecosystem. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DDX token makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances, allowances, and * voting checkpoints, this allows us to more efficiently pack * data together, thereby resulting in cheaper transactions. */ contract DIFundTokenFactory { DIFundToken[] public diFundTokens; address public issuer; /** * @notice Construct a new DDX token */ constructor(address _issuer) public { // Set issuer to deploying address issuer = _issuer; } function createNewDIFundToken( string calldata _name, string calldata _symbol, uint8 _decimals ) external returns (address) { require(msg.sender == issuer, "DIFTF: unauthorized."); DIFundToken diFundToken = new DIFundToken(_name, _symbol, _decimals, issuer); diFundTokens.push(diFundToken); return address(diFundToken); } function getDIFundTokens() external view returns (DIFundToken[] memory) { return diFundTokens; } function getDIFundTokensLength() external view returns (uint256) { return diFundTokens.length; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { LibBytes } from "../libs/LibBytes.sol"; import { LibEIP712 } from "../libs/LibEIP712.sol"; import { LibDelegation } from "../libs/LibDelegation.sol"; import { LibPermit } from "../libs/LibPermit.sol"; import { SafeMath96 } from "../libs/SafeMath96.sol"; /** * @title DDX * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the native token contract for DerivaDEX. It * implements the ERC-20 standard, with additional * functionality to efficiently handle the governance aspect of * the DerivaDEX ecosystem. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DDX token makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances, allowances, and * voting checkpoints, this allows us to more efficiently pack * data together, thereby resulting in cheaper transactions. */ contract DDX { using SafeMath96 for uint96; using SafeMath for uint256; using LibBytes for bytes; /// @notice ERC20 token name for this token string public constant name = "DerivaDAO"; // solhint-disable-line const-name-snakecase /// @notice ERC20 token symbol for this token string public constant symbol = "DDX"; // solhint-disable-line const-name-snakecase /// @notice ERC20 token decimals for this token uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase /// @notice Version number for this token. Used for EIP712 hashing. string public constant version = "1"; // solhint-disable-line const-name-snakecase /// @notice Max number of tokens to be issued (100 million DDX) uint96 public constant MAX_SUPPLY = 100000000e18; /// @notice Total number of tokens in circulation (50 million DDX) uint96 public constant PRE_MINE_SUPPLY = 50000000e18; /// @notice Issued supply of tokens uint96 public issuedSupply; /// @notice Current total/circulating supply of tokens uint96 public totalSupply; /// @notice Whether ownership has been transferred to the DAO bool public ownershipTransferred; /// @notice Address authorized to issue/mint DDX tokens address public issuer; mapping(address => mapping(address => uint96)) internal allowances; mapping(address => uint96) internal balances; /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @notice A checkpoint for marking vote count from given block struct Checkpoint { uint32 id; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint256 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint256) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice Emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice Emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint96 previousBalance, uint96 newBalance); /// @notice Emitted when transfer takes place event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice Emitted when approval takes place event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new DDX token */ constructor() public { // Set issuer to deploying address issuer = msg.sender; // Issue pre-mine token supply to deploying address and // set the issued and circulating supplies to pre-mine amount _transferTokensMint(msg.sender, PRE_MINE_SUPPLY); } /** * @notice Transfer ownership of DDX token from the deploying * address to the DerivaDEX Proxy/DAO * @param _derivaDEXProxy DerivaDEX Proxy address */ function transferOwnershipToDerivaDEXProxy(address _derivaDEXProxy) external { // Ensure deploying address is calling this, destination is not // the zero address, and that ownership has never been // transferred thus far require(msg.sender == issuer, "DDX: unauthorized transfer of ownership."); require(_derivaDEXProxy != address(0), "DDX: transferring to zero address."); require(!ownershipTransferred, "DDX: ownership already transferred."); // Set ownership transferred boolean flag and the new authorized // issuer ownershipTransferred = true; issuer = _derivaDEXProxy; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param _spender The address of the account which may transfer tokens * @param _amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address _spender, uint256 _amount) external returns (bool) { require(_spender != address(0), "DDX: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Set allowance allowances[msg.sender][_spender] = amount; emit Approval(msg.sender, _spender, _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) external returns (bool) { require(_spender != address(0), "DDX: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_addedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_addedValue, "DDX: amount exceeds 96 bits."); } // Increase allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].add96(amount); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); 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) external returns (bool) { require(_spender != address(0), "DDX: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_subtractedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_subtractedValue, "DDX: amount exceeds 96 bits."); } // Decrease allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].sub96( amount, "DDX: decreased allowance below zero." ); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); 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 (uint256) { return balances[_account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address _recipient, uint256 _amount) external returns (bool) { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Transfer tokens from sender to recipient _transferTokens(msg.sender, _recipient, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param _from The address of the source account * @param _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address _from, address _recipient, uint256 _amount ) external returns (bool) { uint96 spenderAllowance = allowances[_from][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } if (msg.sender != _from && spenderAllowance != uint96(-1)) { // Tx sender is not the same as transfer sender and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount); allowances[_from][msg.sender] = newAllowance; emit Approval(_from, msg.sender, newAllowance); } // Transfer tokens from sender to recipient _transferTokens(_from, _recipient, amount); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function mint(address _recipient, uint256 _amount) external { require(msg.sender == issuer, "DDX: unauthorized mint."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Ensure the mint doesn't cause the issued supply to exceed // the total supply that could ever be issued require(issuedSupply.add96(amount) <= MAX_SUPPLY, "DDX: cap exceeded."); // Mint tokens to recipient _transferTokensMint(_recipient, amount); } /** * @dev Creates `amount` tokens and assigns them to `account`, decreasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function burn(uint256 _amount) external { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Burn tokens from sender _transferTokensBurn(msg.sender, 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 burnFrom(address _account, uint256 _amount) external { uint96 spenderAllowance = allowances[_account][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } if (msg.sender != _account && spenderAllowance != uint96(-1)) { // Tx sender is not the same as burn account and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount, "DDX: burn amount exceeds allowance."); allowances[_account][msg.sender] = newAllowance; emit Approval(_account, msg.sender, newAllowance); } // Burn tokens from account _transferTokensBurn(_account, amount); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param _delegatee The address to delegate votes to */ function delegate(address _delegatee) external { _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 _signature Signature */ function delegateBySig( address _delegatee, uint256 _nonce, uint256 _expiry, bytes memory _signature ) external { // Perform EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 delegationHash = LibDelegation.getDelegationHash( LibDelegation.Delegation({ delegatee: _delegatee, nonce: _nonce, expiry: _expiry }), eip712OrderParamsDomainHash ); // Perform sig recovery uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); address recovered = ecrecover(delegationHash, v, r, s); require(recovered != address(0), "DDX: invalid signature."); require(_nonce == nonces[recovered]++, "DDX: invalid nonce."); require(block.timestamp <= _expiry, "DDX: signature expired."); // Delegate votes from recovered address to delegatee _delegate(recovered, _delegatee); } /** * @notice Permits allowance from signatory to `spender` * @param _spender The spender being approved * @param _value The value being approved * @param _nonce The contract state required to match the signature * @param _expiry The time at which to expire the signature * @param _signature Signature */ function permit( address _spender, uint256 _value, uint256 _nonce, uint256 _expiry, bytes memory _signature ) external { // Perform EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 permitHash = LibPermit.getPermitHash( LibPermit.Permit({ spender: _spender, value: _value, nonce: _nonce, expiry: _expiry }), eip712OrderParamsDomainHash ); // Perform sig recovery uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } address recovered = ecrecover(permitHash, v, r, s); require(recovered != address(0), "DDX: invalid signature."); require(_nonce == nonces[recovered]++, "DDX: invalid nonce."); require(block.timestamp <= _expiry, "DDX: signature expired."); // Convert amount to uint96 uint96 amount; if (_value == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_value, "DDX: amount exceeds 96 bits."); } // Set allowance allowances[recovered][_spender] = amount; emit Approval(recovered, _spender, _value); } /** * @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 (uint256) { return allowances[_account][_spender]; } /** * @notice Gets the current votes balance. * @param _account The address to get votes balance. * @return The number of current votes. */ function getCurrentVotes(address _account) external view returns (uint96) { uint256 numCheckpointsAccount = numCheckpoints[_account]; return numCheckpointsAccount > 0 ? checkpoints[_account][numCheckpointsAccount - 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, uint256 _blockNumber) external view returns (uint96) { require(_blockNumber < block.number, "DDX: block not yet determined."); uint256 numCheckpointsAccount = numCheckpoints[_account]; if (numCheckpointsAccount == 0) { return 0; } // First check most recent balance if (checkpoints[_account][numCheckpointsAccount - 1].id <= _blockNumber) { return checkpoints[_account][numCheckpointsAccount - 1].votes; } // Next check implicit zero balance if (checkpoints[_account][0].id > _blockNumber) { return 0; } // Perform binary search to find the most recent token holdings // leading to a measure of voting power uint256 lower = 0; uint256 upper = numCheckpointsAccount - 1; while (upper > lower) { // ceil, avoiding overflow uint256 center = upper - (upper - lower) / 2; Checkpoint memory cp = checkpoints[_account][center]; if (cp.id == _blockNumber) { return cp.votes; } else if (cp.id < _blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[_account][lower].votes; } function _delegate(address _delegator, address _delegatee) internal { // Get the current address delegator has delegated address currentDelegate = _getDelegatee(_delegator); // Get delegator's DDX balance uint96 delegatorBalance = balances[_delegator]; // Set delegator's new delegatee address delegates[_delegator] = _delegatee; emit DelegateChanged(_delegator, currentDelegate, _delegatee); // Move votes from currently-delegated address to // new address _moveDelegates(currentDelegate, _delegatee, delegatorBalance); } function _transferTokens( address _spender, address _recipient, uint96 _amount ) internal { require(_spender != address(0), "DDX: cannot transfer from the zero address."); require(_recipient != address(0), "DDX: cannot transfer to the zero address."); // Reduce spender's balance and increase recipient balance balances[_spender] = balances[_spender].sub96(_amount); balances[_recipient] = balances[_recipient].add96(_amount); emit Transfer(_spender, _recipient, _amount); // Move votes from currently-delegated address to // recipient's delegated address _moveDelegates(_getDelegatee(_spender), _getDelegatee(_recipient), _amount); } function _transferTokensMint(address _recipient, uint96 _amount) internal { require(_recipient != address(0), "DDX: cannot transfer to the zero address."); // Add to recipient's balance balances[_recipient] = balances[_recipient].add96(_amount); // Increase the issued supply and circulating supply issuedSupply = issuedSupply.add96(_amount); totalSupply = totalSupply.add96(_amount); emit Transfer(address(0), _recipient, _amount); // Add delegates to recipient's delegated address _moveDelegates(address(0), _getDelegatee(_recipient), _amount); } function _transferTokensBurn(address _spender, uint96 _amount) internal { require(_spender != address(0), "DDX: cannot transfer from the zero address."); // Reduce the spender/burner's balance balances[_spender] = balances[_spender].sub96(_amount, "DDX: not enough balance to burn."); // Reduce the total supply totalSupply = totalSupply.sub96(_amount); emit Transfer(_spender, address(0), _amount); // MRedduce delegates from spender's delegated address _moveDelegates(_getDelegatee(_spender), address(0), _amount); } function _moveDelegates( address _initDel, address _finDel, uint96 _amount ) internal { if (_initDel != _finDel && _amount > 0) { // Initial delegated address is different than final // delegated address and nonzero number of votes moved if (_initDel != address(0)) { uint256 initDelNum = numCheckpoints[_initDel]; // Retrieve and compute the old and new initial delegate // address' votes uint96 initDelOld = initDelNum > 0 ? checkpoints[_initDel][initDelNum - 1].votes : 0; uint96 initDelNew = initDelOld.sub96(_amount); _writeCheckpoint(_initDel, initDelOld, initDelNew); } if (_finDel != address(0)) { uint256 finDelNum = numCheckpoints[_finDel]; // Retrieve and compute the old and new final delegate // address' votes uint96 finDelOld = finDelNum > 0 ? checkpoints[_finDel][finDelNum - 1].votes : 0; uint96 finDelNew = finDelOld.add96(_amount); _writeCheckpoint(_finDel, finDelOld, finDelNew); } } } function _writeCheckpoint( address _delegatee, uint96 _oldVotes, uint96 _newVotes ) internal { uint32 blockNumber = safe32(block.number, "DDX: exceeds 32 bits."); uint256 delNum = numCheckpoints[_delegatee]; if (delNum > 0 && checkpoints[_delegatee][delNum - 1].id == blockNumber) { // If latest checkpoint is current block, edit in place checkpoints[_delegatee][delNum - 1].votes = _newVotes; } else { // Create a new id, vote pair checkpoints[_delegatee][delNum] = Checkpoint({ id: blockNumber, votes: _newVotes }); numCheckpoints[_delegatee] = delNum.add(1); } emit DelegateVotesChanged(_delegatee, _oldVotes, _newVotes); } function _getDelegatee(address _delegator) internal view returns (address) { if (delegates[_delegator] == address(0)) { return _delegator; } return delegates[_delegator]; } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT /* 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.6.12; import { LibEIP712 } from "./LibEIP712.sol"; library LibDelegation { struct Delegation { address delegatee; // Delegatee uint256 nonce; // Nonce uint256 expiry; // Expiry } // Hash for the EIP712 OrderParams Schema // bytes32 constant internal EIP712_DELEGATION_SCHEMA_HASH = keccak256(abi.encodePacked( // "Delegation(", // "address delegatee,", // "uint256 nonce,", // "uint256 expiry", // ")" // )); bytes32 internal constant EIP712_DELEGATION_SCHEMA_HASH = 0xe48329057bfd03d55e49b547132e39cffd9c1820ad7b9d4c5307691425d15adf; /// @dev Calculates Keccak-256 hash of the delegation. /// @param delegation The delegation structure. /// @return delegationHash Keccak-256 EIP712 hash of the delegation. function getDelegationHash(Delegation memory delegation, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 delegationHash) { delegationHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashDelegation(delegation)); return delegationHash; } /// @dev Calculates EIP712 hash of the delegation. /// @param delegation The delegation structure. /// @return result EIP712 hash of the delegation. function hashDelegation(Delegation memory delegation) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_DELEGATION_SCHEMA_HASH; assembly { // Assert delegation offset (this is an internal error that should never be triggered) if lt(delegation, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(delegation, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 128) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT /* 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.6.12; import { LibEIP712 } from "./LibEIP712.sol"; library LibVoteCast { struct VoteCast { uint128 proposalId; // Proposal ID bool support; // Support } // Hash for the EIP712 OrderParams Schema // bytes32 constant internal EIP712_VOTE_CAST_SCHEMA_HASH = keccak256(abi.encodePacked( // "VoteCast(", // "uint128 proposalId,", // "bool support", // ")" // )); bytes32 internal constant EIP712_VOTE_CAST_SCHEMA_HASH = 0x4abb8ae9facc09d5584ac64f616551bfc03c3ac63e5c431132305bd9bc8f8246; /// @dev Calculates Keccak-256 hash of the vote cast. /// @param voteCast The vote cast structure. /// @return voteCastHash Keccak-256 EIP712 hash of the vote cast. function getVoteCastHash(VoteCast memory voteCast, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 voteCastHash) { voteCastHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashVoteCast(voteCast)); return voteCastHash; } /// @dev Calculates EIP712 hash of the vote cast. /// @param voteCast The vote cast structure. /// @return result EIP712 hash of the vote cast. function hashVoteCast(VoteCast memory voteCast) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_VOTE_CAST_SCHEMA_HASH; assembly { // Assert vote cast offset (this is an internal error that should never be triggered) if lt(voteCast, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(voteCast, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 96) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { GovernanceDefs } from "../../libs/defs/GovernanceDefs.sol"; import { LibEIP712 } from "../../libs/LibEIP712.sol"; import { LibVoteCast } from "../../libs/LibVoteCast.sol"; import { LibBytes } from "../../libs/LibBytes.sol"; import { SafeMath32 } from "../../libs/SafeMath32.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { SafeMath128 } from "../../libs/SafeMath128.sol"; import { MathHelpers } from "../../libs/MathHelpers.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageGovernance } from "../../storage/LibDiamondStorageGovernance.sol"; /** * @title Governance * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to governance. The Diamond storage * will only be affected when facet functions are called via * the proxy contract, no checks are necessary. * @dev The Diamond storage will only be affected when facet functions * are called via the proxy contract, no checks are necessary. */ contract Governance { using SafeMath32 for uint32; using SafeMath96 for uint96; using SafeMath128 for uint128; using SafeMath for uint256; using MathHelpers for uint96; using MathHelpers for uint256; using LibBytes for bytes; /// @notice name for this Governance contract string public constant name = "DDX Governance"; // solhint-disable-line const-name-snakecase /// @notice version for this Governance contract string public constant version = "1"; // solhint-disable-line const-name-snakecase /// @notice Emitted when a new proposal is created event ProposalCreated( uint128 indexed id, address indexed proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description ); /// @notice Emitted when a vote has been cast on a proposal event VoteCast(address indexed voter, uint128 indexed proposalId, bool support, uint96 votes); /// @notice Emitted when a proposal has been canceled event ProposalCanceled(uint128 indexed id); /// @notice Emitted when a proposal has been queued event ProposalQueued(uint128 indexed id, uint256 eta); /// @notice Emitted when a proposal has been executed event ProposalExecuted(uint128 indexed id); /// @notice Emitted when a proposal action has been canceled event CancelTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); /// @notice Emitted when a proposal action has been executed event ExecuteTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); /// @notice Emitted when a proposal action has been queued event QueueTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Governance: must be called by Governance admin."); _; } /** * @notice This function initializes the state with some critical * information. This can only be called once and must be * done via governance. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. * @param _quorumVotes Minimum number of for votes required, even * if there's a majority in favor. * @param _proposalThreshold Minimum DDX token holdings required * to create a proposal * @param _proposalMaxOperations Max number of operations/actions a * proposal can have * @param _votingDelay Number of blocks after a proposal is made * that voting begins. * @param _votingPeriod Number of blocks voting will be held. * @param _skipRemainingVotingThreshold Number of for or against * votes that are necessary to skip the remainder of the * voting period. * @param _gracePeriod Period in which a successful proposal must be * executed, otherwise will be expired. * @param _timelockDelay Time (s) in which a successful proposal * must be in the queue before it can be executed. */ function initialize( uint32 _proposalMaxOperations, uint32 _votingDelay, uint32 _votingPeriod, uint32 _gracePeriod, uint32 _timelockDelay, uint32 _quorumVotes, uint32 _proposalThreshold, uint32 _skipRemainingVotingThreshold ) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure state variable comparisons are valid requireValidSkipRemainingVotingThreshold(_skipRemainingVotingThreshold); requireSkipRemainingVotingThresholdGtQuorumVotes(_skipRemainingVotingThreshold, _quorumVotes); // Set initial variable values dsGovernance.proposalMaxOperations = _proposalMaxOperations; dsGovernance.votingDelay = _votingDelay; dsGovernance.votingPeriod = _votingPeriod; dsGovernance.gracePeriod = _gracePeriod; dsGovernance.timelockDelay = _timelockDelay; dsGovernance.quorumVotes = _quorumVotes; dsGovernance.proposalThreshold = _proposalThreshold; dsGovernance.skipRemainingVotingThreshold = _skipRemainingVotingThreshold; dsGovernance.fastPathFunctionSignatures["setIsPaused(bool)"] = true; } /** * @notice This function allows participants who have sufficient * DDX holdings to create new proposals up for vote. The * proposals contain the ordered lists of on-chain * executable calldata. * @param _targets Addresses of contracts involved. * @param _values Values to be passed along with the calls. * @param _signatures Function signatures. * @param _calldatas Calldata passed to the function. * @param _description Text description of proposal. */ function propose( address[] memory _targets, uint256[] memory _values, string[] memory _signatures, bytes[] memory _calldatas, string memory _description ) external returns (uint128) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure proposer has sufficient token holdings to propose require( dsDerivaDEX.ddxToken.getPriorVotes(msg.sender, block.number.sub(1)) >= getProposerThresholdCount(), "Governance: proposer votes below proposal threshold." ); require( _targets.length == _values.length && _targets.length == _signatures.length && _targets.length == _calldatas.length, "Governance: proposal function information parity mismatch." ); require(_targets.length != 0, "Governance: must provide actions."); require(_targets.length <= dsGovernance.proposalMaxOperations, "Governance: too many actions."); if (dsGovernance.latestProposalIds[msg.sender] != 0) { // Ensure proposer doesn't already have one active/pending GovernanceDefs.ProposalState proposersLatestProposalState = state(dsGovernance.latestProposalIds[msg.sender]); require( proposersLatestProposalState != GovernanceDefs.ProposalState.Active, "Governance: one live proposal per proposer, found an already active proposal." ); require( proposersLatestProposalState != GovernanceDefs.ProposalState.Pending, "Governance: one live proposal per proposer, found an already pending proposal." ); } // Proposal voting starts votingDelay after proposal is made uint256 startBlock = block.number.add(dsGovernance.votingDelay); // Increment count of proposals dsGovernance.proposalCount++; // Create new proposal struct and add to mapping GovernanceDefs.Proposal memory newProposal = GovernanceDefs.Proposal({ id: dsGovernance.proposalCount, proposer: msg.sender, delay: getTimelockDelayForSignatures(_signatures), eta: 0, targets: _targets, values: _values, signatures: _signatures, calldatas: _calldatas, startBlock: startBlock, endBlock: startBlock.add(dsGovernance.votingPeriod), forVotes: 0, againstVotes: 0, canceled: false, executed: false }); dsGovernance.proposals[newProposal.id] = newProposal; // Update proposer's latest proposal dsGovernance.latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated( newProposal.id, msg.sender, _targets, _values, _signatures, _calldatas, startBlock, startBlock.add(dsGovernance.votingPeriod), _description ); return newProposal.id; } /** * @notice This function allows any participant to queue a * successful proposal for execution. Proposals are deemed * successful if at any point the number of for votes has * exceeded the skip remaining voting threshold or if there * is a simple majority (and more for votes than the * minimum quorum) at the end of voting. * @param _proposalId Proposal id. */ function queue(uint128 _proposalId) external { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure proposal has succeeded (i.e. it has either enough for // votes to skip the remainder of the voting period or the // voting period has ended and there is a simple majority in // favor and also above the quorum require( state(_proposalId) == GovernanceDefs.ProposalState.Succeeded, "Governance: proposal can only be queued if it is succeeded." ); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Establish eta of execution, which is a number of seconds // after queuing at which point proposal can actually execute uint256 eta = block.timestamp.add(proposal.delay); for (uint256 i = 0; i < proposal.targets.length; i++) { // Ensure proposal action is not already in the queue bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta ) ); require(!dsGovernance.queuedTransactions[txHash], "Governance: proposal action already queued at eta."); dsGovernance.queuedTransactions[txHash] = true; emit QueueTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta ); } // Set proposal eta timestamp after which it can be executed proposal.eta = eta; emit ProposalQueued(_proposalId, eta); } /** * @notice This function allows any participant to execute a * queued proposal. A proposal in the queue must be in the * queue for the delay period it was proposed with prior to * executing, allowing the community to position itself * accordingly. * @param _proposalId Proposal id. */ function execute(uint128 _proposalId) external payable { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure proposal is queued require( state(_proposalId) == GovernanceDefs.ProposalState.Queued, "Governance: proposal can only be executed if it is queued." ); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Ensure proposal has been in the queue long enough require(block.timestamp >= proposal.eta, "Governance: proposal hasn't finished queue time length."); // Ensure proposal hasn't been in the queue for too long require(block.timestamp <= proposal.eta.add(dsGovernance.gracePeriod), "Governance: transaction is stale."); proposal.executed = true; // Loop through each of the actions in the proposal for (uint256 i = 0; i < proposal.targets.length; i++) { bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ) ); require(dsGovernance.queuedTransactions[txHash], "Governance: transaction hasn't been queued."); dsGovernance.queuedTransactions[txHash] = false; // Execute action bytes memory callData; require(bytes(proposal.signatures[i]).length != 0, "Governance: Invalid function signature."); callData = abi.encodePacked(bytes4(keccak256(bytes(proposal.signatures[i]))), proposal.calldatas[i]); // solium-disable-next-line security/no-call-value (bool success, ) = proposal.targets[i].call{ value: proposal.values[i] }(callData); require(success, "Governance: transaction execution reverted."); emit ExecuteTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ); } emit ProposalExecuted(_proposalId); } /** * @notice This function allows any participant to cancel any non- * executed proposal. It can be canceled if the proposer's * token holdings has dipped below the proposal threshold * at the time of cancellation. * @param _proposalId Proposal id. */ function cancel(uint128 _proposalId) external { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); GovernanceDefs.ProposalState state = state(_proposalId); // Ensure proposal hasn't executed require(state != GovernanceDefs.ProposalState.Executed, "Governance: cannot cancel executed proposal."); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Ensure proposer's token holdings has dipped below the // proposer threshold, leaving their proposal subject to // cancellation require( dsDerivaDEX.ddxToken.getPriorVotes(proposal.proposer, block.number.sub(1)) < getProposerThresholdCount(), "Governance: proposer above threshold." ); proposal.canceled = true; // Loop through each of the proposal's actions for (uint256 i = 0; i < proposal.targets.length; i++) { bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ) ); dsGovernance.queuedTransactions[txHash] = false; emit CancelTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ); } emit ProposalCanceled(_proposalId); } /** * @notice This function allows participants to cast either in * favor or against a particular proposal. * @param _proposalId Proposal id. * @param _support In favor (true) or against (false). */ function castVote(uint128 _proposalId, bool _support) external { return _castVote(msg.sender, _proposalId, _support); } /** * @notice This function allows participants to cast votes with * offline signatures in favor or against a particular * proposal. * @param _proposalId Proposal id. * @param _support In favor (true) or against (false). * @param _signature Signature */ function castVoteBySig( uint128 _proposalId, bool _support, bytes memory _signature ) external { // EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 voteCastHash = LibVoteCast.getVoteCastHash( LibVoteCast.VoteCast({ proposalId: _proposalId, support: _support }), eip712OrderParamsDomainHash ); // Recover the signature and EIP712 hash uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); address recovered = ecrecover(voteCastHash, v, r, s); require(recovered != address(0), "Governance: invalid signature."); return _castVote(recovered, _proposalId, _support); } /** * @notice This function sets the quorum votes required for a * proposal to pass. It must be called via * governance. * @param _quorumVotes Quorum votes threshold. */ function setQuorumVotes(uint32 _quorumVotes) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); requireSkipRemainingVotingThresholdGtQuorumVotes(dsGovernance.skipRemainingVotingThreshold, _quorumVotes); dsGovernance.quorumVotes = _quorumVotes; } /** * @notice This function sets the token holdings threshold required * to propose something. It must be called via * governance. * @param _proposalThreshold Proposal threshold. */ function setProposalThreshold(uint32 _proposalThreshold) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.proposalThreshold = _proposalThreshold; } /** * @notice This function sets the max operations a proposal can * carry out. It must be called via governance. * @param _proposalMaxOperations Proposal's max operations. */ function setProposalMaxOperations(uint32 _proposalMaxOperations) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.proposalMaxOperations = _proposalMaxOperations; } /** * @notice This function sets the voting delay in blocks from when * a proposal is made and voting begins. It must be called * via governance. * @param _votingDelay Voting delay (blocks). */ function setVotingDelay(uint32 _votingDelay) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.votingDelay = _votingDelay; } /** * @notice This function sets the voting period in blocks that a * vote will last. It must be called via * governance. * @param _votingPeriod Voting period (blocks). */ function setVotingPeriod(uint32 _votingPeriod) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.votingPeriod = _votingPeriod; } /** * @notice This function sets the threshold at which a proposal can * immediately be deemed successful or rejected if the for * or against votes exceeds this threshold, even if the * voting period is still ongoing. It must be called * governance. * @param _skipRemainingVotingThreshold Threshold for or against * votes must reach to skip remainder of voting period. */ function setSkipRemainingVotingThreshold(uint32 _skipRemainingVotingThreshold) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); requireValidSkipRemainingVotingThreshold(_skipRemainingVotingThreshold); requireSkipRemainingVotingThresholdGtQuorumVotes(_skipRemainingVotingThreshold, dsGovernance.quorumVotes); dsGovernance.skipRemainingVotingThreshold = _skipRemainingVotingThreshold; } /** * @notice This function sets the grace period in seconds that a * queued proposal can last before expiring. It must be * called via governance. * @param _gracePeriod Grace period (seconds). */ function setGracePeriod(uint32 _gracePeriod) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.gracePeriod = _gracePeriod; } /** * @notice This function sets the timelock delay (s) a proposal * must be queued before execution. * @param _timelockDelay Timelock delay (seconds). */ function setTimelockDelay(uint32 _timelockDelay) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.timelockDelay = _timelockDelay; } /** * @notice This function allows any participant to retrieve * the actions involved in a given proposal. * @param _proposalId Proposal id. * @return targets Addresses of contracts involved. * @return values Values to be passed along with the calls. * @return signatures Function signatures. * @return calldatas Calldata passed to the function. */ function getActions(uint128 _proposalId) external view returns ( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas ) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); GovernanceDefs.Proposal storage p = dsGovernance.proposals[_proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } /** * @notice This function allows any participant to retrieve * the receipt for a given proposal and voter. * @param _proposalId Proposal id. * @param _voter Voter address. * @return Voter receipt. */ function getReceipt(uint128 _proposalId, address _voter) external view returns (GovernanceDefs.Receipt memory) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.proposals[_proposalId].receipts[_voter]; } /** * @notice This function gets a proposal from an ID. * @param _proposalId Proposal id. * @return Proposal attributes. */ function getProposal(uint128 _proposalId) external view returns ( bool, bool, address, uint32, uint96, uint96, uint128, uint256, uint256, uint256 ) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); GovernanceDefs.Proposal memory proposal = dsGovernance.proposals[_proposalId]; return ( proposal.canceled, proposal.executed, proposal.proposer, proposal.delay, proposal.forVotes, proposal.againstVotes, proposal.id, proposal.eta, proposal.startBlock, proposal.endBlock ); } /** * @notice This function gets whether a proposal action transaction * hash is queued or not. * @param _txHash Proposal action tx hash. * @return Is proposal action transaction hash queued or not. */ function getIsQueuedTransaction(bytes32 _txHash) external view returns (bool) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.queuedTransactions[_txHash]; } /** * @notice This function gets the Governance facet's current * parameters. * @return Proposal max operations. * @return Voting delay. * @return Voting period. * @return Grace period. * @return Timelock delay. * @return Quorum votes threshold. * @return Proposal threshold. * @return Skip remaining voting threshold. */ function getGovernanceParameters() external view returns ( uint32, uint32, uint32, uint32, uint32, uint32, uint32, uint32 ) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return ( dsGovernance.proposalMaxOperations, dsGovernance.votingDelay, dsGovernance.votingPeriod, dsGovernance.gracePeriod, dsGovernance.timelockDelay, dsGovernance.quorumVotes, dsGovernance.proposalThreshold, dsGovernance.skipRemainingVotingThreshold ); } /** * @notice This function gets the proposal count. * @return Proposal count. */ function getProposalCount() external view returns (uint128) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.proposalCount; } /** * @notice This function gets the latest proposal ID for a user. * @param _proposer Proposer's address. * @return Proposal ID. */ function getLatestProposalId(address _proposer) external view returns (uint128) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.latestProposalIds[_proposer]; } /** * @notice This function gets the quorum vote count given the * quorum vote percentage relative to the total DDX supply. * @return Quorum vote count. */ function getQuorumVoteCount() public view returns (uint96) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); uint96 totalSupply = dsDerivaDEX.ddxToken.totalSupply().safe96("Governance: amount exceeds 96 bits"); return totalSupply.proportion96(dsGovernance.quorumVotes, 100); } /** * @notice This function gets the quorum vote count given the * quorum vote percentage relative to the total DDX supply. * @return Quorum vote count. */ function getProposerThresholdCount() public view returns (uint96) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); uint96 totalSupply = dsDerivaDEX.ddxToken.totalSupply().safe96("Governance: amount exceeds 96 bits"); return totalSupply.proportion96(dsGovernance.proposalThreshold, 100); } /** * @notice This function gets the quorum vote count given the * quorum vote percentage relative to the total DDX supply. * @return Quorum vote count. */ function getSkipRemainingVotingThresholdCount() public view returns (uint96) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); uint96 totalSupply = dsDerivaDEX.ddxToken.totalSupply().safe96("Governance: amount exceeds 96 bits"); return totalSupply.proportion96(dsGovernance.skipRemainingVotingThreshold, 100); } /** * @notice This function retrieves the status for any given * proposal. * @param _proposalId Proposal id. * @return Status of proposal. */ function state(uint128 _proposalId) public view returns (GovernanceDefs.ProposalState) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); require(dsGovernance.proposalCount >= _proposalId && _proposalId > 0, "Governance: invalid proposal id."); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Note the 3rd conditional where we can escape out of the vote // phase if the for or against votes exceeds the skip remaining // voting threshold if (proposal.canceled) { return GovernanceDefs.ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return GovernanceDefs.ProposalState.Pending; } else if ( (block.number <= proposal.endBlock) && (proposal.forVotes < getSkipRemainingVotingThresholdCount()) && (proposal.againstVotes < getSkipRemainingVotingThresholdCount()) ) { return GovernanceDefs.ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < getQuorumVoteCount()) { return GovernanceDefs.ProposalState.Defeated; } else if (proposal.eta == 0) { return GovernanceDefs.ProposalState.Succeeded; } else if (proposal.executed) { return GovernanceDefs.ProposalState.Executed; } else if (block.timestamp >= proposal.eta.add(dsGovernance.gracePeriod)) { return GovernanceDefs.ProposalState.Expired; } else { return GovernanceDefs.ProposalState.Queued; } } function _castVote( address _voter, uint128 _proposalId, bool _support ) internal { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); require(state(_proposalId) == GovernanceDefs.ProposalState.Active, "Governance: voting is closed."); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; GovernanceDefs.Receipt storage receipt = proposal.receipts[_voter]; // Ensure voter has not already voted require(!receipt.hasVoted, "Governance: voter already voted."); // Obtain the token holdings (voting power) for participant at // the time voting started. They may have gained or lost tokens // since then, doesn't matter. uint96 votes = dsDerivaDEX.ddxToken.getPriorVotes(_voter, proposal.startBlock); // Ensure voter has nonzero voting power require(votes > 0, "Governance: voter has no voting power."); if (_support) { // Increment the for votes in favor proposal.forVotes = proposal.forVotes.add96(votes); } else { // Increment the against votes proposal.againstVotes = proposal.againstVotes.add96(votes); } // Set receipt attributes based on cast vote parameters receipt.hasVoted = true; receipt.support = _support; receipt.votes = votes; emit VoteCast(_voter, _proposalId, _support, votes); } function getTimelockDelayForSignatures(string[] memory _signatures) internal view returns (uint32) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); for (uint256 i = 0; i < _signatures.length; i++) { if (!dsGovernance.fastPathFunctionSignatures[_signatures[i]]) { return dsGovernance.timelockDelay; } } return 1; } function requireSkipRemainingVotingThresholdGtQuorumVotes(uint32 _skipRemainingVotingThreshold, uint32 _quorumVotes) internal pure { require(_skipRemainingVotingThreshold > _quorumVotes, "Governance: skip rem votes must be higher than quorum."); } function requireValidSkipRemainingVotingThreshold(uint32 _skipRemainingVotingThreshold) internal pure { require(_skipRemainingVotingThreshold >= 50, "Governance: skip rem votes must be higher than 50pct."); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title GovernanceDefs * @author DerivaDEX * * This library contains the common structs and enums pertaining to * the governance. */ library GovernanceDefs { struct Proposal { bool canceled; bool executed; address proposer; uint32 delay; uint96 forVotes; uint96 againstVotes; uint128 id; uint256 eta; address[] targets; string[] signatures; bytes[] calldatas; uint256[] values; uint256 startBlock; uint256 endBlock; mapping(address => Receipt) receipts; } struct Receipt { bool hasVoted; bool support; uint96 votes; } enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint128 a, uint128 b) internal pure returns (uint128) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b <= a, errorMessage); uint128 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint128 a, uint128 b) internal pure returns (uint128) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint128 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint128 a, uint128 b) internal pure returns (uint128) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b > 0, errorMessage); uint128 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint128 a, uint128 b) internal pure returns (uint128) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { GovernanceDefs } from "../libs/defs/GovernanceDefs.sol"; library LibDiamondStorageGovernance { struct DiamondStorageGovernance { // Proposal struct by ID mapping(uint256 => GovernanceDefs.Proposal) proposals; // Latest proposal IDs by proposer address mapping(address => uint128) latestProposalIds; // Whether transaction hash is currently queued mapping(bytes32 => bool) queuedTransactions; // Fast path for governance mapping(string => bool) fastPathFunctionSignatures; // Max number of operations/actions a proposal can have uint32 proposalMaxOperations; // Number of blocks after a proposal is made that voting begins // (e.g. 1 block) uint32 votingDelay; // Number of blocks voting will be held // (e.g. 17280 blocks ~ 3 days of blocks) uint32 votingPeriod; // Time window (s) a successful proposal must be executed, // otherwise will be expired, measured in seconds // (e.g. 1209600 seconds) uint32 gracePeriod; // Minimum time (s) in which a successful proposal must be // in the queue before it can be executed // (e.g. 0 seconds) uint32 minimumDelay; // Maximum time (s) in which a successful proposal must be // in the queue before it can be executed // (e.g. 2592000 seconds ~ 30 days) uint32 maximumDelay; // Minimum number of for votes required, even if there's a // majority in favor // (e.g. 2000000e18 ~ 4% of pre-mine DDX supply) uint32 quorumVotes; // Minimum DDX token holdings required to create a proposal // (e.g. 500000e18 ~ 1% of pre-mine DDX supply) uint32 proposalThreshold; // Number of for or against votes that are necessary to skip // the remainder of the voting period // (e.g. 25000000e18 tokens/votes) uint32 skipRemainingVotingThreshold; // Time (s) proposals must be queued before executing uint32 timelockDelay; // Total number of proposals uint128 proposalCount; } bytes32 constant DIAMOND_STORAGE_POSITION_GOVERNANCE = keccak256("diamond.standard.diamond.storage.DerivaDEX.Governance"); function diamondStorageGovernance() internal pure returns (DiamondStorageGovernance storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_GOVERNANCE; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStoragePause } from "../../storage/LibDiamondStoragePause.sol"; /** * @title Pause * @author DerivaDEX * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to pausing functionality. The purpose * of this is to ensure the system can pause in the unlikely * scenario of a bug or issue materially jeopardizing users' * funds or experience. This facet will be removed entirely * as the system stabilizes shortly. It's important to note that * unlike the vast majority of projects, even during this * short-lived period of time in which the system can be paused, * no single admin address can wield this power, but rather * pausing must be carried out via governance. */ contract Pause { event PauseInitialized(); event IsPausedSet(bool isPaused); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Pause: must be called by Gov."); _; } /** * @notice This function initializes the facet. */ function initialize() external onlyAdmin { emit PauseInitialized(); } /** * @notice This function sets the paused status. * @param _isPaused Whether contracts are paused or not. */ function setIsPaused(bool _isPaused) external onlyAdmin { LibDiamondStoragePause.DiamondStoragePause storage dsPause = LibDiamondStoragePause.diamondStoragePause(); dsPause.isPaused = _isPaused; emit IsPausedSet(_isPaused); } /** * @notice This function gets whether the contract ecosystem is * currently paused. * @return Whether contracts are paused or not. */ function getIsPaused() public view returns (bool) { LibDiamondStoragePause.DiamondStoragePause storage dsPause = LibDiamondStoragePause.diamondStoragePause(); return dsPause.isPaused; } } // SPDX-License-Identifier: MIT /** *Submitted for verification at Etherscan.io on 2019-07-18 */ pragma solidity 0.6.12; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { Ownable } from "openzeppelin-solidity/contracts/access/Ownable.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; library Roles { struct Role { mapping(address => bool) bearer; } function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } 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]; } } contract PauserRole is Ownable { using Roles for Roles.Role; Roles.Role private _pausers; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); constructor() internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyOwner { _addPauser(account); } function removePauser(address account) public onlyOwner { _removePauser(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); } } contract Pausable is PauserRole { bool private _paused; event Paused(address account); event Unpaused(address account); constructor() internal { _paused = false; } function paused() public view returns (bool) { return _paused; } modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } contract ERC20 is IERC20, Ownable { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; event Issue(address indexed account, uint256 amount); event Redeem(address indexed account, uint256 value); function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 value) public virtual override returns (bool) { _approve(msg.sender, spender, value); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 value ) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } function _issue(address account, uint256 amount) internal { require(account != address(0), "CoinFactory: issue to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); emit Issue(account, amount); } function _redeem(address account, uint256 value) internal { require(account != address(0), "CoinFactory: redeem from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); emit Redeem(account, value); } } contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public virtual override whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom( address from, address to, uint256 value ) public virtual override whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public virtual override whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public virtual override whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } contract CoinFactoryAdminRole is Ownable { using Roles for Roles.Role; event CoinFactoryAdminRoleAdded(address indexed account); event CoinFactoryAdminRoleRemoved(address indexed account); Roles.Role private _coinFactoryAdmins; constructor() internal { _addCoinFactoryAdmin(msg.sender); } modifier onlyCoinFactoryAdmin() { require(isCoinFactoryAdmin(msg.sender), "CoinFactoryAdminRole: caller does not have the CoinFactoryAdmin role"); _; } function isCoinFactoryAdmin(address account) public view returns (bool) { return _coinFactoryAdmins.has(account); } function addCoinFactoryAdmin(address account) public onlyOwner { _addCoinFactoryAdmin(account); } function removeCoinFactoryAdmin(address account) public onlyOwner { _removeCoinFactoryAdmin(account); } function renounceCoinFactoryAdmin() public { _removeCoinFactoryAdmin(msg.sender); } function _addCoinFactoryAdmin(address account) internal { _coinFactoryAdmins.add(account); emit CoinFactoryAdminRoleAdded(account); } function _removeCoinFactoryAdmin(address account) internal { _coinFactoryAdmins.remove(account); emit CoinFactoryAdminRoleRemoved(account); } } contract CoinFactory is ERC20, CoinFactoryAdminRole { function issue(address account, uint256 amount) public onlyCoinFactoryAdmin returns (bool) { _issue(account, amount); return true; } function redeem(address account, uint256 amount) public onlyCoinFactoryAdmin returns (bool) { _redeem(account, amount); return true; } } contract BlacklistAdminRole is Ownable { using Roles for Roles.Role; event BlacklistAdminAdded(address indexed account); event BlacklistAdminRemoved(address indexed account); Roles.Role private _blacklistAdmins; constructor() internal { _addBlacklistAdmin(msg.sender); } modifier onlyBlacklistAdmin() { require(isBlacklistAdmin(msg.sender), "BlacklistAdminRole: caller does not have the BlacklistAdmin role"); _; } function isBlacklistAdmin(address account) public view returns (bool) { return _blacklistAdmins.has(account); } function addBlacklistAdmin(address account) public onlyOwner { _addBlacklistAdmin(account); } function removeBlacklistAdmin(address account) public onlyOwner { _removeBlacklistAdmin(account); } function renounceBlacklistAdmin() public { _removeBlacklistAdmin(msg.sender); } function _addBlacklistAdmin(address account) internal { _blacklistAdmins.add(account); emit BlacklistAdminAdded(account); } function _removeBlacklistAdmin(address account) internal { _blacklistAdmins.remove(account); emit BlacklistAdminRemoved(account); } } contract Blacklist is ERC20, BlacklistAdminRole { mapping(address => bool) private _blacklist; event BlacklistAdded(address indexed account); event BlacklistRemoved(address indexed account); function addBlacklist(address[] memory accounts) public onlyBlacklistAdmin returns (bool) { for (uint256 i = 0; i < accounts.length; i++) { _addBlacklist(accounts[i]); } } function removeBlacklist(address[] memory accounts) public onlyBlacklistAdmin returns (bool) { for (uint256 i = 0; i < accounts.length; i++) { _removeBlacklist(accounts[i]); } } function isBlacklist(address account) public view returns (bool) { return _blacklist[account]; } function _addBlacklist(address account) internal { _blacklist[account] = true; emit BlacklistAdded(account); } function _removeBlacklist(address account) internal { _blacklist[account] = false; emit BlacklistRemoved(account); } } contract HDUMToken is ERC20, ERC20Pausable, CoinFactory, Blacklist { string public name; string public symbol; uint8 public decimals; uint256 private _totalSupply; constructor( string memory _name, string memory _symbol, uint8 _decimals ) public { _totalSupply = 0; name = _name; symbol = _symbol; decimals = _decimals; } function transfer(address to, uint256 value) public override(ERC20, ERC20Pausable) whenNotPaused returns (bool) { require(!isBlacklist(msg.sender), "HDUMToken: caller in blacklist can't transfer"); require(!isBlacklist(to), "HDUMToken: not allow to transfer to recipient address in blacklist"); return super.transfer(to, value); } function transferFrom( address from, address to, uint256 value ) public override(ERC20, ERC20Pausable) whenNotPaused returns (bool) { require(!isBlacklist(msg.sender), "HDUMToken: caller in blacklist can't transferFrom"); require(!isBlacklist(from), "HDUMToken: from in blacklist can't transfer"); require(!isBlacklist(to), "HDUMToken: not allow to transfer to recipient address in blacklist"); return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public virtual override(ERC20, ERC20Pausable) returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public virtual override(ERC20, ERC20Pausable) returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override(ERC20, ERC20Pausable) returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: 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; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { Context } from "openzeppelin-solidity/contracts/GSN/Context.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; contract SafeERC20Wrapper is Context { using SafeERC20 for IERC20; IERC20 private _token; constructor(IERC20 token) public { _token = token; } function transfer(address recipient, uint256 amount) public { _token.safeTransfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public { _token.safeTransferFrom(sender, recipient, amount); } function approve(address spender, uint256 amount) public { _token.safeApprove(spender, amount); } function increaseAllowance(address spender, uint256 amount) public { _token.safeIncreaseAllowance(spender, amount); } function decreaseAllowance(address spender, uint256 amount) public { _token.safeDecreaseAllowance(spender, amount); } function allowance(address owner, address spender) public view returns (uint256) { return _token.allowance(owner, spender); } function balanceOf(address account) public view returns (uint256) { return _token.balanceOf(account); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/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 {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; // mock class using ERC20 contract DummyToken is ERC20 { uint256 public constant INITIAL_SUPPLY = 100000000 * (10**18); constructor(string memory name, string memory symbol) public payable ERC20(name, symbol) { _mint(msg.sender, INITIAL_SUPPLY); } function mint(address account, uint256 amount) public { _mint(account, amount); } function burn(address account, uint256 amount) public { _burn(account, amount); } function transferInternal( address from, address to, uint256 value ) public { _transfer(from, to, value); } function approveInternal( address owner, address spender, uint256 value ) public { _approve(owner, spender, value); } }
* @notice This function gets a participant's current DIFund token holdings and global DIFund token holdings for a collateral type and staker, in addition to the USD-normalized collateral in the system and the redemption value for the staker. @param _collateralName Name of collateral. @param _staker Participant's address. @return DIFund tokens for staker. @return DIFund tokens globally. @return Redemption value for staker (USD-denominated). @return Underlying collateral (USD-denominated) in staking system./ Get DIFund tokens for staker Get DIFund tokens globally Compute global USD-denominated stake capitalization. This is is straightforward for non-Compound assets, but requires exchange rate conversion for Compound assets. Compute the redemption value (USD-normalized) for staker given DIFund token holdings
function getCurrentStakeByCollateralNameAndStaker(bytes32 _collateralName, address _staker) public view returns ( uint96, uint96, uint96, uint96 ) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; uint96 stakerStake = stakeCollateral.diFundToken.balanceOf(_staker).safe96("IFund: exceeds 96 bits."); uint96 globalCap = stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits."); uint96 normalizedGlobalCap = (stakeCollateral.flavor != InsuranceFundDefs.Flavor.Compound) ? getUnderlyingTokenAmountForVanilla(stakeCollateral.cap, stakeCollateral.collateralToken) : getUnderlyingTokenAmountForCompound( stakeCollateral.cap, ICToken(stakeCollateral.collateralToken).exchangeRateStored() ); uint96 normalizedStakerStake = globalCap > 0 ? normalizedGlobalCap.proportion96(stakerStake, globalCap) : 0; return (stakerStake, globalCap, normalizedStakerStake, normalizedGlobalCap); }
1,813,594
[ 1, 2503, 445, 5571, 279, 14188, 1807, 783, 3690, 42, 1074, 1147, 540, 6887, 899, 471, 2552, 3690, 42, 1074, 1147, 6887, 899, 364, 279, 540, 4508, 2045, 287, 618, 471, 384, 6388, 16, 316, 2719, 358, 326, 540, 587, 9903, 17, 17762, 4508, 2045, 287, 316, 326, 2619, 471, 326, 540, 283, 19117, 375, 460, 364, 326, 384, 6388, 18, 225, 389, 12910, 2045, 287, 461, 1770, 434, 4508, 2045, 287, 18, 225, 389, 334, 6388, 31333, 1807, 1758, 18, 327, 3690, 42, 1074, 2430, 364, 384, 6388, 18, 327, 3690, 42, 1074, 2430, 25654, 18, 327, 868, 19117, 375, 460, 364, 384, 6388, 261, 3378, 40, 17, 13002, 362, 7458, 2934, 327, 21140, 6291, 4508, 2045, 287, 261, 3378, 40, 17, 13002, 362, 7458, 13, 316, 384, 6159, 2619, 18, 19, 968, 3690, 42, 1074, 2430, 364, 384, 6388, 968, 3690, 42, 1074, 2430, 25654, 8155, 2552, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 5175, 510, 911, 858, 13535, 2045, 287, 31925, 510, 6388, 12, 3890, 1578, 389, 12910, 2045, 287, 461, 16, 1758, 389, 334, 6388, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 5411, 2254, 10525, 16, 203, 5411, 2254, 10525, 16, 203, 5411, 2254, 10525, 16, 203, 5411, 2254, 10525, 203, 3639, 262, 203, 565, 288, 203, 3639, 10560, 14521, 301, 1434, 3245, 5048, 295, 1359, 42, 1074, 18, 14521, 301, 1434, 3245, 5048, 295, 1359, 42, 1074, 2502, 3780, 5048, 295, 1359, 42, 1074, 273, 203, 5411, 10560, 14521, 301, 1434, 3245, 5048, 295, 1359, 42, 1074, 18, 3211, 301, 1434, 3245, 5048, 295, 1359, 42, 1074, 5621, 203, 3639, 657, 10050, 1359, 42, 1074, 14554, 18, 510, 911, 13535, 2045, 287, 2502, 384, 911, 13535, 2045, 287, 273, 3780, 5048, 295, 1359, 42, 1074, 18, 334, 911, 13535, 2045, 1031, 63, 67, 12910, 2045, 287, 461, 15533, 203, 203, 3639, 2254, 10525, 384, 6388, 510, 911, 273, 384, 911, 13535, 2045, 287, 18, 3211, 42, 1074, 1345, 18, 12296, 951, 24899, 334, 6388, 2934, 4626, 10525, 2932, 5501, 1074, 30, 14399, 19332, 4125, 1199, 1769, 203, 203, 3639, 2254, 10525, 2552, 4664, 273, 384, 911, 13535, 2045, 287, 18, 3211, 42, 1074, 1345, 18, 4963, 3088, 1283, 7675, 4626, 10525, 2932, 5501, 1074, 30, 14399, 19332, 4125, 1199, 1769, 203, 203, 3639, 2254, 10525, 5640, 5160, 4664, 273, 203, 5411, 261, 334, 911, 13535, 2045, 287, 18, 2242, 9444, 480, 657, 10050, 1359, 42, 1074, 14554, 18, 2 ]
//Address: 0x7367a68039d4704f30bfbf6d948020c3b07dfc59 //Contract name: Beercoin //Balance: 0 Ether //Verification Date: 1/12/2018 //Transacion Count: 226 // CODE STARTS HERE pragma solidity ^0.4.19; /** * A contract containing the fundamental state variables of the Beercoin */ contract InternalBeercoin { // As 18 decimal places will be used, the constants are multiplied by 10^18 uint256 internal constant INITIAL_SUPPLY = 15496000000 * 10**18; uint256 internal constant DIAMOND_VALUE = 10000 * 10**18; uint256 internal constant GOLD_VALUE = 100 * 10**18; uint256 internal constant SILVER_VALUE = 10 * 10**18; uint256 internal constant BRONZE_VALUE = 1 * 10**18; // In addition to the initial total supply of 15496000000 Beercoins, // more Beercoins will only be added by scanning bottle caps. // 20800000000 bottle caps will be eventually produced. // // Within 10000 bottle caps, // 1 (i.e. every 10000th cap in total) has a value of 10000 ("Diamond") Beercoins, // 9 (i.e. every 1000th cap in total) have a value of 100 ("Gold") Beercoins, // 990 (i.e. every 10th cap in total) have a value of 10 ("Silver") Beercoins, // 9000 (i.e. every remaining cap) have a value of 1 ("Bronze") Beercoin. // // Therefore one bottle cap has an average Beercoin value of // (1 * 10000 + 9 * 100 + 990 * 10 + 9000 * 1) / 10000 = 2.98. // // This means the total Beercoin value of all bottle caps that will // be eventually produced equals 20800000000 * 2.98 = 61984000000. uint64 internal producibleCaps = 20800000000; // The amounts of diamond, gold, silver, and bronze caps are stored // as a single 256-bit value divided into four sections of 64 bits. // // Bits 255 to 192 are used for the amount of diamond caps, // bits 191 to 128 are used for the amount of gold caps, // bits 127 to 64 are used for the amount of silver caps, // bits 63 to 0 are used for the amount of bronze caps. // // For example, the following numbers represent a single cap of a certain type: // 0x0000000000000001000000000000000000000000000000000000000000000000 (diamond) // 0x0000000000000000000000000000000100000000000000000000000000000000 (gold) // 0x0000000000000000000000000000000000000000000000010000000000000000 (silver) // 0x0000000000000000000000000000000000000000000000000000000000000001 (bronze) uint256 internal packedProducedCaps = 0; uint256 internal packedScannedCaps = 0; // The amount of irreversibly burnt Beercoins uint256 internal burntValue = 0; } /** * A contract containing functions to understand the packed low-level data */ contract ExplorableBeercoin is InternalBeercoin { /** * The amount of caps that can still be produced */ function unproducedCaps() public view returns (uint64) { return producibleCaps; } /** * The amount of caps that is produced but not yet scanned */ function unscannedCaps() public view returns (uint64) { uint256 caps = packedProducedCaps - packedScannedCaps; uint64 amount = uint64(caps >> 192); amount += uint64(caps >> 128); amount += uint64(caps >> 64); amount += uint64(caps); return amount; } /** * The amount of all caps produced so far */ function producedCaps() public view returns (uint64) { uint256 caps = packedProducedCaps; uint64 amount = uint64(caps >> 192); amount += uint64(caps >> 128); amount += uint64(caps >> 64); amount += uint64(caps); return amount; } /** * The amount of all caps scanned so far */ function scannedCaps() public view returns (uint64) { uint256 caps = packedScannedCaps; uint64 amount = uint64(caps >> 192); amount += uint64(caps >> 128); amount += uint64(caps >> 64); amount += uint64(caps); return amount; } /** * The amount of diamond caps produced so far */ function producedDiamondCaps() public view returns (uint64) { return uint64(packedProducedCaps >> 192); } /** * The amount of diamond caps scanned so far */ function scannedDiamondCaps() public view returns (uint64) { return uint64(packedScannedCaps >> 192); } /** * The amount of gold caps produced so far */ function producedGoldCaps() public view returns (uint64) { return uint64(packedProducedCaps >> 128); } /** * The amount of gold caps scanned so far */ function scannedGoldCaps() public view returns (uint64) { return uint64(packedScannedCaps >> 128); } /** * The amount of silver caps produced so far */ function producedSilverCaps() public view returns (uint64) { return uint64(packedProducedCaps >> 64); } /** * The amount of silver caps scanned so far */ function scannedSilverCaps() public view returns (uint64) { return uint64(packedScannedCaps >> 64); } /** * The amount of bronze caps produced so far */ function producedBronzeCaps() public view returns (uint64) { return uint64(packedProducedCaps); } /** * The amount of bronze caps scanned so far */ function scannedBronzeCaps() public view returns (uint64) { return uint64(packedScannedCaps); } } /** * A contract implementing all standard ERC20 functionality for the Beercoin */ contract ERC20Beercoin is ExplorableBeercoin { event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); mapping (address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowances; /** * Beercoin's name */ function name() public pure returns (string) { return "Beercoin"; } /** * Beercoin's symbol */ function symbol() public pure returns (string) { return "🍺"; } /** * Beercoin's decimal places */ function decimals() public pure returns (uint8) { return 18; } /** * The current total supply of Beercoins */ function totalSupply() public view returns (uint256) { uint256 caps = packedScannedCaps; uint256 supply = INITIAL_SUPPLY; supply += (caps >> 192) * DIAMOND_VALUE; supply += ((caps >> 128) & 0xFFFFFFFFFFFFFFFF) * GOLD_VALUE; supply += ((caps >> 64) & 0xFFFFFFFFFFFFFFFF) * SILVER_VALUE; supply += (caps & 0xFFFFFFFFFFFFFFFF) * BRONZE_VALUE; return supply - burntValue; } /** * Check the balance of a Beercoin user * * @param _owner the user to check */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * Transfer Beercoins to another user * * @param _to the address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != 0x0); uint256 balanceFrom = balances[msg.sender]; require(_value <= balanceFrom); uint256 oldBalanceTo = balances[_to]; uint256 newBalanceTo = oldBalanceTo + _value; require(oldBalanceTo <= newBalanceTo); balances[msg.sender] = balanceFrom - _value; balances[_to] = newBalanceTo; Transfer(msg.sender, _to, _value); return true; } /** * Transfer Beercoins from other address if a respective allowance exists * * @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) public returns (bool) { require(_to != 0x0); uint256 balanceFrom = balances[_from]; uint256 allowanceFrom = allowances[_from][msg.sender]; require(_value <= balanceFrom); require(_value <= allowanceFrom); uint256 oldBalanceTo = balances[_to]; uint256 newBalanceTo = oldBalanceTo + _value; require(oldBalanceTo <= newBalanceTo); balances[_from] = balanceFrom - _value; balances[_to] = newBalanceTo; allowances[_from][msg.sender] = allowanceFrom - _value; Transfer(_from, _to, _value); return true; } /** * Allow another user to spend a certain amount of Beercoins on your behalf * * @param _spender the address of the user authorized to spend * @param _value the maximum amount that can be spent on your behalf */ function approve(address _spender, uint256 _value) public returns (bool) { allowances[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * The amount of Beercoins that can be spent by a user on behalf of another * * @param _owner the address of the user user whose Beercoins are spent * @param _spender the address of the user who executes the transaction */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowances[_owner][_spender]; } } /** * A contract that defines a master with special debiting abilities * required for operating a user-friendly Beercoin redemption system */ contract MasteredBeercoin is ERC20Beercoin { address internal beercoinMaster; mapping (address => bool) internal directDebitAllowances; /** * Construct the MasteredBeercoin contract * and make the sender the master */ function MasteredBeercoin() public { beercoinMaster = msg.sender; } /** * Restrict to the master only */ modifier onlyMaster { require(msg.sender == beercoinMaster); _; } /** * The master of the Beercoin */ function master() public view returns (address) { return beercoinMaster; } /** * Declare a master at another address * * @param newMaster the new owner's address */ function declareNewMaster(address newMaster) public onlyMaster { beercoinMaster = newMaster; } /** * Allow the master to withdraw Beercoins from your * account so you don't have to send Beercoins yourself */ function allowDirectDebit() public { directDebitAllowances[msg.sender] = true; } /** * Forbid the master to withdraw Beercoins from you account */ function forbidDirectDebit() public { directDebitAllowances[msg.sender] = false; } /** * Check whether a user allows direct debits by the master * * @param user the user to check */ function directDebitAllowance(address user) public view returns (bool) { return directDebitAllowances[user]; } /** * Withdraw Beercoins from multiple users * * Beercoins are only withdrawn this way if and only if * a user deliberately wants it to happen by initiating * a transaction on a plattform operated by the owner * * @param users the addresses of the users to take Beercoins from * @param values the respective amounts to take */ function debit(address[] users, uint256[] values) public onlyMaster returns (bool) { require(users.length == values.length); uint256 oldBalance = balances[msg.sender]; uint256 newBalance = oldBalance; address currentUser; uint256 currentValue; uint256 currentBalance; for (uint256 i = 0; i < users.length; ++i) { currentUser = users[i]; currentValue = values[i]; currentBalance = balances[currentUser]; require(directDebitAllowances[currentUser]); require(currentValue <= currentBalance); balances[currentUser] = currentBalance - currentValue; newBalance += currentValue; Transfer(currentUser, msg.sender, currentValue); } require(oldBalance <= newBalance); balances[msg.sender] = newBalance; return true; } /** * Withdraw Beercoins from multiple users * * Beercoins are only withdrawn this way if and only if * a user deliberately wants it to happen by initiating * a transaction on a plattform operated by the owner * * @param users the addresses of the users to take Beercoins from * @param value the amount to take from each user */ function debitEqually(address[] users, uint256 value) public onlyMaster returns (bool) { uint256 oldBalance = balances[msg.sender]; uint256 newBalance = oldBalance + (users.length * value); require(oldBalance <= newBalance); balances[msg.sender] = newBalance; address currentUser; uint256 currentBalance; for (uint256 i = 0; i < users.length; ++i) { currentUser = users[i]; currentBalance = balances[currentUser]; require(directDebitAllowances[currentUser]); require(value <= currentBalance); balances[currentUser] = currentBalance - value; Transfer(currentUser, msg.sender, value); } return true; } /** * Send Beercoins to multiple users * * @param users the addresses of the users to send Beercoins to * @param values the respective amounts to send */ function credit(address[] users, uint256[] values) public onlyMaster returns (bool) { require(users.length == values.length); uint256 balance = balances[msg.sender]; uint256 totalValue = 0; address currentUser; uint256 currentValue; uint256 currentOldBalance; uint256 currentNewBalance; for (uint256 i = 0; i < users.length; ++i) { currentUser = users[i]; currentValue = values[i]; currentOldBalance = balances[currentUser]; currentNewBalance = currentOldBalance + currentValue; require(currentOldBalance <= currentNewBalance); balances[currentUser] = currentNewBalance; totalValue += currentValue; Transfer(msg.sender, currentUser, currentValue); } require(totalValue <= balance); balances[msg.sender] = balance - totalValue; return true; } /** * Send Beercoins to multiple users * * @param users the addresses of the users to send Beercoins to * @param value the amounts to send to each user */ function creditEqually(address[] users, uint256 value) public onlyMaster returns (bool) { uint256 balance = balances[msg.sender]; uint256 totalValue = users.length * value; require(totalValue <= balance); balances[msg.sender] = balance - totalValue; address currentUser; uint256 currentOldBalance; uint256 currentNewBalance; for (uint256 i = 0; i < users.length; ++i) { currentUser = users[i]; currentOldBalance = balances[currentUser]; currentNewBalance = currentOldBalance + value; require(currentOldBalance <= currentNewBalance); balances[currentUser] = currentNewBalance; Transfer(msg.sender, currentUser, value); } return true; } } /** * A contract that defines the central business logic * which also mirrors the life of a Beercoin */ contract Beercoin is MasteredBeercoin { event Produce(uint256 newCaps); event Scan(address[] users, uint256[] caps); event Burn(uint256 value); /** * Construct the Beercoin contract and * assign the initial supply to the creator */ function Beercoin() public { balances[msg.sender] = INITIAL_SUPPLY; } /** * Increase the amounts of produced diamond, gold, silver, and * bronze bottle caps in respect to their occurrence probabilities * * This function is called if and only if a brewery has actually * ordered codes to produce the specified amount of bottle caps * * @param numberOfCaps the number of bottle caps to be produced */ function produce(uint64 numberOfCaps) public onlyMaster returns (bool) { require(numberOfCaps <= producibleCaps); uint256 producedCaps = packedProducedCaps; uint64 targetTotalCaps = numberOfCaps; targetTotalCaps += uint64(producedCaps >> 192); targetTotalCaps += uint64(producedCaps >> 128); targetTotalCaps += uint64(producedCaps >> 64); targetTotalCaps += uint64(producedCaps); uint64 targetDiamondCaps = (targetTotalCaps - (targetTotalCaps % 10000)) / 10000; uint64 targetGoldCaps = ((targetTotalCaps - (targetTotalCaps % 1000)) / 1000) - targetDiamondCaps; uint64 targetSilverCaps = ((targetTotalCaps - (targetTotalCaps % 10)) / 10) - targetDiamondCaps - targetGoldCaps; uint64 targetBronzeCaps = targetTotalCaps - targetDiamondCaps - targetGoldCaps - targetSilverCaps; uint256 targetProducedCaps = 0; targetProducedCaps |= uint256(targetDiamondCaps) << 192; targetProducedCaps |= uint256(targetGoldCaps) << 128; targetProducedCaps |= uint256(targetSilverCaps) << 64; targetProducedCaps |= uint256(targetBronzeCaps); producibleCaps -= numberOfCaps; packedProducedCaps = targetProducedCaps; Produce(targetProducedCaps - producedCaps); return true; } /** * Approve scans of multiple users and grant Beercoins * * This function is called periodically to mass-transfer Beercoins to * multiple users if and only if each of them has scanned codes that * our server has never verified before for the same or another user * * @param users the addresses of the users who scanned valid codes * @param caps the amounts of caps the users have scanned as single 256-bit values */ function scan(address[] users, uint256[] caps) public onlyMaster returns (bool) { require(users.length == caps.length); uint256 scannedCaps = packedScannedCaps; uint256 currentCaps; uint256 capsValue; for (uint256 i = 0; i < users.length; ++i) { currentCaps = caps[i]; capsValue = DIAMOND_VALUE * (currentCaps >> 192); capsValue += GOLD_VALUE * ((currentCaps >> 128) & 0xFFFFFFFFFFFFFFFF); capsValue += SILVER_VALUE * ((currentCaps >> 64) & 0xFFFFFFFFFFFFFFFF); capsValue += BRONZE_VALUE * (currentCaps & 0xFFFFFFFFFFFFFFFF); balances[users[i]] += capsValue; scannedCaps += currentCaps; } require(scannedCaps <= packedProducedCaps); packedScannedCaps = scannedCaps; Scan(users, caps); return true; } /** * Remove Beercoins from the system irreversibly * * @param value the amount of Beercoins to burn */ function burn(uint256 value) public onlyMaster returns (bool) { uint256 balance = balances[msg.sender]; require(value <= balance); balances[msg.sender] = balance - value; burntValue += value; Burn(value); return true; } }
* The amount of bronze caps scanned so far/
function scannedBronzeCaps() public view returns (uint64) { return uint64(packedScannedCaps); }
12,911,611
[ 1, 1986, 3844, 434, 324, 1949, 8489, 15788, 22711, 1427, 10247, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 22711, 38, 1949, 8489, 24193, 1435, 1071, 1476, 1135, 261, 11890, 1105, 13, 288, 203, 3639, 327, 2254, 1105, 12, 2920, 329, 1541, 10041, 24193, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x261ace754fba8af93e1fecdff13640540402940f //Contract name: Phila_Token //Balance: 0 Ether //Verification Date: 5/23/2018 //Transacion Count: 6 // CODE STARTS HERE pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // 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 Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ---------------------------------------------------------------------------- contract Phila_Token is ERC20Interface, Owned { string public constant symbol = "φιλα"; string public constant name = "φιλανθρωπία"; uint8 public constant decimals = 0; uint private constant _totalSupply = 10000000; address public vaultAddress; bool public fundingEnabled; uint public totalCollected; // In wei uint public tokenPrice; // In wei mapping(address => uint) balances; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { balances[this] = _totalSupply; emit Transfer(address(0), this, _totalSupply); } function setVaultAddress(address _vaultAddress) public onlyOwner { vaultAddress = _vaultAddress; return; } function setFundingEnabled(bool _fundingEnabled) public onlyOwner { fundingEnabled = _fundingEnabled; return; } function updateTokenPrice(uint _newTokenPrice) public onlyOwner { require(_newTokenPrice > 0); tokenPrice = _newTokenPrice; return; } // ------------------------------------------------------------------------ // 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) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // 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 // // THIS TOKENS ARE NOT TRANSFERRABLE. // // ------------------------------------------------------------------------ function approve(address, uint) public returns (bool) { revert(); return false; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // // THIS TOKENS ARE NOT TRANSFERRABLE. // // ------------------------------------------------------------------------ function allowance(address, address) public constant returns (uint) { return 0; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // // THIS TOKENS ARE NOT TRANSFERRABLE. // // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address _to, uint _amount) public returns (bool) { if (_amount == 0) { emit Transfer(msg.sender, _to, _amount); // Follow the spec to louch the event when transfer 0 return true; } revert(); return false; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // THIS TOKENS ARE NOT TRANSFERRABLE. // // ------------------------------------------------------------------------ function transferFrom(address, address, uint) public returns (bool) { revert(); return false; } function () public payable { require (fundingEnabled && (tokenPrice > 0) && (msg.value >= tokenPrice)); totalCollected += msg.value; //Send the ether to the vault vaultAddress.transfer(msg.value); uint tokens = msg.value / tokenPrice; // Do not allow transfer to 0x0 or the token contract itself require((msg.sender != 0) && (msg.sender != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws uint previousBalanceFrom = balances[this]; require(previousBalanceFrom >= tokens); // First update the balance array with the new value for the address // sending the tokens balances[this] = previousBalanceFrom - tokens; // Then update the balance array with the new value for the address // receiving the tokens uint previousBalanceTo = balances[msg.sender]; require(previousBalanceTo + tokens >= previousBalanceTo); // Check for overflow balances[msg.sender] = previousBalanceTo + tokens; // An event to make the transfer easy to find on the blockchain emit Transfer(this, msg.sender, tokens); return; } /// @notice This method can be used by the owner to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. // // THIS TOKENS ARE NOT TRANSFERRABLE. // function claimTokens(address _token) public onlyOwner { require(_token != address(this)); if (_token == 0x0) { owner.transfer(address(this).balance); return; } ERC20Interface token = ERC20Interface(_token); uint balance = token.balanceOf(this); token.transfer(owner, balance); emit ClaimedTokens(_token, owner, balance); } event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and an initial fixed supply ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract Phila_Token is ERC20Interface, Owned { string public constant symbol = "φιλα"; string public constant name = "φιλανθρωπία"; uint8 public constant decimals = 0; uint private constant _totalSupply = 10000000; address public vaultAddress; bool public fundingEnabled; mapping(address => uint) balances; constructor() public { balances[this] = _totalSupply; emit Transfer(address(0), this, _totalSupply); } function setVaultAddress(address _vaultAddress) public onlyOwner { vaultAddress = _vaultAddress; return; } function setFundingEnabled(bool _fundingEnabled) public onlyOwner { fundingEnabled = _fundingEnabled; return; } function updateTokenPrice(uint _newTokenPrice) public onlyOwner { require(_newTokenPrice > 0); tokenPrice = _newTokenPrice; return; } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint) { return balances[tokenOwner]; } function approve(address, uint) public returns (bool) { revert(); return false; } function allowance(address, address) public constant returns (uint) { return 0; } function transfer(address _to, uint _amount) public returns (bool) { if (_amount == 0) { return true; } revert(); return false; } function transfer(address _to, uint _amount) public returns (bool) { if (_amount == 0) { return true; } revert(); return false; } function transferFrom(address, address, uint) public returns (bool) { revert(); return false; } function () public payable { require (fundingEnabled && (tokenPrice > 0) && (msg.value >= tokenPrice)); totalCollected += msg.value; vaultAddress.transfer(msg.value); uint tokens = msg.value / tokenPrice; require((msg.sender != 0) && (msg.sender != address(this))); uint previousBalanceFrom = balances[this]; require(previousBalanceFrom >= tokens); balances[this] = previousBalanceFrom - tokens; uint previousBalanceTo = balances[msg.sender]; balances[msg.sender] = previousBalanceTo + tokens; emit Transfer(this, msg.sender, tokens); return; } function claimTokens(address _token) public onlyOwner { require(_token != address(this)); if (_token == 0x0) { owner.transfer(address(this).balance); return; } ERC20Interface token = ERC20Interface(_token); uint balance = token.balanceOf(this); token.transfer(owner, balance); emit ClaimedTokens(_token, owner, balance); } event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); function claimTokens(address _token) public onlyOwner { require(_token != address(this)); if (_token == 0x0) { owner.transfer(address(this).balance); return; } ERC20Interface token = ERC20Interface(_token); uint balance = token.balanceOf(this); token.transfer(owner, balance); emit ClaimedTokens(_token, owner, balance); } event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); }
945,770
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 392, 2172, 5499, 14467, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4360, 330, 69, 67, 1345, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 288, 203, 565, 533, 1071, 5381, 3273, 273, 315, 144, 233, 143, 122, 143, 124, 143, 114, 14432, 203, 565, 533, 1071, 5381, 508, 273, 315, 144, 233, 143, 122, 143, 124, 143, 114, 143, 126, 143, 121, 144, 228, 144, 236, 144, 227, 143, 112, 143, 114, 14432, 203, 565, 2254, 28, 1071, 5381, 15105, 273, 374, 31, 203, 565, 2254, 3238, 5381, 389, 4963, 3088, 1283, 273, 2130, 11706, 31, 203, 203, 565, 1758, 1071, 9229, 1887, 31, 203, 565, 1426, 1071, 22058, 1526, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 324, 26488, 63, 2211, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 333, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 565, 445, 444, 12003, 1887, 12, 2867, 389, 26983, 1887, 13, 1071, 1338, 5541, 288, 203, 3639, 9229, 1887, 273, 389, 26983, 1887, 31, 203, 3639, 327, 31, 203, 565, 289, 203, 203, 565, 445, 24340, 14351, 1526, 12, 6430, 389, 74, 14351, 1526, 13, 1071, 1338, 5541, 288, 203, 3639, 22058, 1526, 273, 389, 74, 14351, 1526, 31, 203, 3639, 327, 31, 203, 565, 289, 203, 203, 565, 445, 1089, 1345, 5147, 12, 11890, 389, 2704, 1345, 5147, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 2704, 1345, 5147, 405, 374, 1769, 203, 3639, 1147, 5147, 273, 389, 2 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@aave/core-v3/contracts/flashloan/base/FlashLoanReceiverBase.sol"; import "@aave/core-v3/contracts/interfaces/IPoolAddressesProvider.sol"; contract TryAaveV3 is FlashLoanReceiverBase { event Log(string message, uint256 amount); constructor(IPoolAddressesProvider _provider) FlashLoanReceiverBase(_provider) {} function test(address asset, uint256 amount) external { uint256 balance = IERC20(asset).balanceOf(address(this)); require(balance > amount, "balance <= amount"); address receiver = address(this); address[] memory assets = new address[](1); assets[0] = asset; uint256[] memory amounts = new uint256[](1); amounts[0] = amount; // 0 - don't open any debt, just revert if funds can't be transferred from the receiver // 1 - open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address // 2 - open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address uint256[] memory modes = new uint256[](1); modes[0] = 0; address onBehalfOf = address(this); bytes memory params = ""; uint16 referralCode = 0; POOL.flashLoan( receiver, assets, amounts, modes, onBehalfOf, params, referralCode ); } function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address, /*_initiator*/ bytes calldata /*_params*/ ) external returns (bool) { for (uint256 i = 0; i < assets.length; i++) { emit Log("borrowed", amounts[i]); emit Log("fee", premiums[i]); // do smth with the received funds... // repay the loan uint256 amountOwing = amounts[i] + premiums[i]; IERC20(assets[i]).approve(address(POOL), amountOwing); } return true; } }
do smth with the received funds... repay the loan
function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address, /*_initiator*/ bytes calldata /*_params*/ ) external returns (bool) { for (uint256 i = 0; i < assets.length; i++) { emit Log("borrowed", amounts[i]); emit Log("fee", premiums[i]); uint256 amountOwing = amounts[i] + premiums[i]; IERC20(assets[i]).approve(address(POOL), amountOwing); } return true; }
5,543,599
[ 1, 2896, 3029, 451, 598, 326, 5079, 284, 19156, 2777, 2071, 528, 326, 28183, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1836, 2988, 12, 203, 3639, 1758, 8526, 745, 892, 7176, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 30980, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 23020, 5077, 87, 16, 203, 3639, 1758, 16, 1748, 67, 2738, 10620, 5549, 203, 3639, 1731, 745, 892, 1748, 67, 2010, 5549, 203, 565, 262, 3903, 1135, 261, 6430, 13, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 7176, 18, 2469, 31, 277, 27245, 288, 203, 5411, 3626, 1827, 2932, 70, 15318, 329, 3113, 30980, 63, 77, 19226, 203, 5411, 3626, 1827, 2932, 21386, 3113, 23020, 5077, 87, 63, 77, 19226, 203, 203, 203, 5411, 2254, 5034, 3844, 3494, 310, 273, 30980, 63, 77, 65, 397, 23020, 5077, 87, 63, 77, 15533, 203, 5411, 467, 654, 39, 3462, 12, 9971, 63, 77, 65, 2934, 12908, 537, 12, 2867, 12, 20339, 3631, 3844, 3494, 310, 1769, 203, 3639, 289, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; /* Owned contract interface */ contract IOwned { // this function isn't abstract since the compiler emits automatically generated getter functions as external function owner() public view returns (address) {} function transferOwnership(address _newOwner) public; function acceptOwnership() public; } /* ERC20 Standard Token interface */ contract IERC20Token { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public view returns (string) {} function symbol() public view returns (string) {} function decimals() public view returns (uint8) {} function totalSupply() public view returns (uint256) {} function balanceOf(address _owner) public view returns (uint256) { _owner; } function allowance(address _owner, address _spender) public view returns (uint256) { _owner; _spender; } function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); } /* Contract Registry interface */ contract IContractRegistry { function getAddress(bytes32 _contractName) public view returns (address); } /* Contract Features interface */ contract IContractFeatures { function isSupported(address _contract, uint256 _features) public view returns (bool); function enableFeatures(uint256 _features, bool _enable) public; } /* Whitelist interface */ contract IWhitelist { function isWhitelisted(address _address) public view returns (bool); } /* Token Holder interface */ contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } /* Ether Token interface */ contract IEtherToken is ITokenHolder, IERC20Token { function deposit() public payable; function withdraw(uint256 _amount) public; function withdrawTo(address _to, uint256 _amount) public; } /* Smart Token interface */ contract ISmartToken is IOwned, IERC20Token { function disableTransfers(bool _disable) public; function issue(address _to, uint256 _amount) public; function destroy(address _from, uint256 _amount) public; } /* Bancor Gas Price Limit interface */ contract IBancorGasPriceLimit { function gasPrice() public view returns (uint256) {} function validateGasPrice(uint256) public view; } /* Bancor Converter interface */ contract IBancorConverter { function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256); function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); function conversionWhitelist() public view returns (IWhitelist) {} // deprecated, backward compatibility function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); } /* Bancor Network interface */ contract IBancorNetwork { function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256); function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256); function convertForPrioritized2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s) public payable returns (uint256); // deprecated, backward compatibility function convertForPrioritized( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public payable returns (uint256); } /* Utilities & Common Modifiers */ contract Utils { /** constructor */ function Utils() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != address(0)); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } // Overflow protected math functions /** @dev returns the sum of _x and _y, asserts if the calculation overflows @param _x value 1 @param _y value 2 @return sum */ function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x + _y; assert(z >= _x); return z; } /** @dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number @param _x minuend @param _y subtrahend @return difference */ function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) { assert(_x >= _y); return _x - _y; } /** @dev returns the product of multiplying _x by _y, asserts if the calculation overflows @param _x factor 1 @param _y factor 2 @return product */ function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x * _y; assert(_x == 0 || z / _x == _y); return z; } } /* Provides support and utilities for contract ownership */ contract Owned is IOwned { address public owner; address public newOwner; event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** @dev constructor */ function Owned() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { assert(msg.sender == owner); _; } /** @dev allows transferring the contract ownership the new owner still needs to accept the transfer can only be called by the contract owner @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public ownerOnly { require(_newOwner != owner); newOwner = _newOwner; } /** @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } /** Id definitions for bancor contracts Can be used in conjunction with the contract registry to get contract addresses */ contract ContractIds { bytes32 public constant BANCOR_NETWORK = "BancorNetwork"; bytes32 public constant BANCOR_FORMULA = "BancorFormula"; bytes32 public constant CONTRACT_FEATURES = "ContractFeatures"; } /** Id definitions for bancor contract features Can be used to query the ContractFeatures contract to check whether a certain feature is supported by a contract */ contract FeatureIds { // converter features uint256 public constant CONVERTER_CONVERSION_WHITELIST = 1 << 0; } /* We consider every contract to be a 'token holder' since it's currently not possible for a contract to deny receiving tokens. The TokenHolder's contract sole purpose is to provide a safety mechanism that allows the owner to send tokens that were sent to the contract by mistake back to their sender. */ contract TokenHolder is ITokenHolder, Owned, Utils { /** @dev constructor */ function TokenHolder() public { } /** @dev withdraws tokens held by the contract and sends them to an account can only be called by the owner @param _token ERC20 token contract address @param _to account to receive the new amount @param _amount amount to withdraw */ function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public ownerOnly validAddress(_token) validAddress(_to) notThis(_to) { assert(_token.transfer(_to, _amount)); } } /* The BancorNetwork contract is the main entry point for bancor token conversions. It also allows converting between any token in the bancor network to any other token in a single transaction by providing a conversion path. A note on conversion path - Conversion path is a data structure that's used when converting a token to another token in the bancor network when the conversion cannot necessarily be done by single converter and might require multiple 'hops'. The path defines which converters should be used and what kind of conversion should be done in each step. The path format doesn't include complex structure and instead, it is represented by a single array in which each 'hop' is represented by a 2-tuple - smart token & to token. In addition, the first element is always the source token. The smart token is only used as a pointer to a converter (since converter addresses are more likely to change). Format: [source token, smart token, to token, smart token, to token...] */ contract BancorNetwork is IBancorNetwork, TokenHolder, ContractIds, FeatureIds { address public signerAddress = 0x0; // verified address that allows conversions with higher gas price IContractRegistry public registry; // contract registry contract address IBancorGasPriceLimit public gasPriceLimit; // bancor universal gas price limit contract mapping (address => bool) public etherTokens; // list of all supported ether tokens mapping (bytes32 => bool) public conversionHashes; // list of conversion hashes, to prevent re-use of the same hash /** @dev constructor @param _registry address of a contract registry contract */ function BancorNetwork(IContractRegistry _registry) public validAddress(_registry) { registry = _registry; } // validates a conversion path - verifies that the number of elements is odd and that maximum number of 'hops' is 10 modifier validConversionPath(IERC20Token[] _path) { require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1); _; } /* @dev allows the owner to update the contract registry contract address @param _registry address of a contract registry contract */ function setContractRegistry(IContractRegistry _registry) public ownerOnly validAddress(_registry) notThis(_registry) { registry = _registry; } /* @dev allows the owner to update the gas price limit contract address @param _gasPriceLimit address of a bancor gas price limit contract */ function setGasPriceLimit(IBancorGasPriceLimit _gasPriceLimit) public ownerOnly validAddress(_gasPriceLimit) notThis(_gasPriceLimit) { gasPriceLimit = _gasPriceLimit; } /* @dev allows the owner to update the signer address @param _signerAddress new signer address */ function setSignerAddress(address _signerAddress) public ownerOnly validAddress(_signerAddress) notThis(_signerAddress) { signerAddress = _signerAddress; } /** @dev allows the owner to register/unregister ether tokens @param _token ether token contract address @param _register true to register, false to unregister */ function registerEtherToken(IEtherToken _token, bool _register) public ownerOnly validAddress(_token) notThis(_token) { etherTokens[_token] = _register; } /** @dev verifies that the signer address is trusted by recovering the address associated with the public key from elliptic curve signature, returns zero on error. notice that the signature is valid only for one conversion and expires after the give block. @return true if the signer is verified */ function verifyTrustedSender(IERC20Token[] _path, uint256 _amount, uint256 _block, address _addr, uint8 _v, bytes32 _r, bytes32 _s) private returns(bool) { bytes32 hash = keccak256(_block, tx.gasprice, _addr, msg.sender, _amount, _path); // checking that it is the first conversion with the given signature // and that the current block number doesn't exceeded the maximum block // number that's allowed with the current signature require(!conversionHashes[hash] && block.number <= _block); // recovering the signing address and comparing it to the trusted signer // address that was set in the contract bytes32 prefixedHash = keccak256("\x19Ethereum Signed Message:\n32", hash); bool verified = ecrecover(prefixedHash, _v, _r, _s) == signerAddress; // if the signer is the trusted signer - mark the hash so that it can't // be used multiple times if (verified) conversionHashes[hash] = true; return verified; } /** @dev converts the token to any other token in the bancor network by following a predefined conversion path and transfers the result tokens to a target account note that the converter should already own the source tokens @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _for account that will receive the conversion result @return tokens issued in return */ function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256) { return convertForPrioritized2(_path, _amount, _minReturn, _for, 0x0, 0x0, 0x0, 0x0); } /** @dev converts the token to any other token in the bancor network by following a predefined conversion path and transfers the result tokens to a target account. this version of the function also allows the verified signer to bypass the universal gas price limit. note that the converter should already own the source tokens @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _for account that will receive the conversion result @return tokens issued in return */ function convertForPrioritized2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s) public payable validConversionPath(_path) returns (uint256) { // if ETH is provided, ensure that the amount is identical to _amount and verify that the source token is an ether token IERC20Token fromToken = _path[0]; require(msg.value == 0 || (_amount == msg.value && etherTokens[fromToken])); // if ETH was sent with the call, the source is an ether token - deposit the ETH in it // otherwise, we assume we already have the tokens if (msg.value > 0) IEtherToken(fromToken).deposit.value(msg.value)(); return convertForInternal(_path, _amount, _minReturn, _for, _block, _v, _r, _s); } /** @dev converts token to any other token in the bancor network by following the predefined conversion paths and transfers the result tokens to a targeted account. this version of the function also allows multiple conversions in a single atomic transaction. note that the converter should already own the source tokens @param _paths merged conversion paths, i.e. [path1, path2, ...]. see conversion path format above @param _pathStartIndex each item in the array is the start index of the nth path in _paths @param _amounts amount to convert from (in the initial source token) for each path @param _minReturns minimum return for each path. if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _for account that will receive the conversions result @return amount of conversion result for each path */ function convertForMultiple(IERC20Token[] _paths, uint256[] _pathStartIndex, uint256[] _amounts, uint256[] _minReturns, address _for) public payable returns (uint256[]) { // if ETH is provided, ensure that the total amount was converted into other tokens uint256 convertedValue = 0; uint256 pathEndIndex; // iterate over the conversion paths for (uint256 i = 0; i < _pathStartIndex.length; i += 1) { pathEndIndex = i == (_pathStartIndex.length - 1) ? _paths.length : _pathStartIndex[i + 1]; // copy a single path from _paths into an array IERC20Token[] memory path = new IERC20Token[](pathEndIndex - _pathStartIndex[i]); for (uint256 j = _pathStartIndex[i]; j < pathEndIndex; j += 1) { path[j - _pathStartIndex[i]] = _paths[j]; } // if ETH is provided, ensure that the amount is lower than the path amount and // verify that the source token is an ether token. otherwise ensure that // the source is not an ether token IERC20Token fromToken = path[0]; require(msg.value == 0 || (_amounts[i] <= msg.value && etherTokens[fromToken]) || !etherTokens[fromToken]); // if ETH was sent with the call, the source is an ether token - deposit the ETH path amount in it. // otherwise, we assume we already have the tokens if (msg.value > 0 && etherTokens[fromToken]) { IEtherToken(fromToken).deposit.value(_amounts[i])(); convertedValue += _amounts[i]; } _amounts[i] = convertForInternal(path, _amounts[i], _minReturns[i], _for, 0x0, 0x0, 0x0, 0x0); } // if ETH was provided, ensure that the full amount was converted require(convertedValue == msg.value); return _amounts; } /** @dev converts token to any other token in the bancor network by following a predefined conversion paths and transfers the result tokens to a target account. @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _for account that will receive the conversion result @param _block if the current block exceeded the given parameter - it is cancelled @param _v (signature[128:130]) associated with the signer address and helps to validate if the signature is legit @param _r (signature[0:64]) associated with the signer address and helps to validate if the signature is legit @param _s (signature[64:128]) associated with the signer address and helps to validate if the signature is legit @return tokens issued in return */ function convertForInternal( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s ) private validConversionPath(_path) returns (uint256) { if (_v == 0x0 && _r == 0x0 && _s == 0x0) gasPriceLimit.validateGasPrice(tx.gasprice); else require(verifyTrustedSender(_path, _amount, _block, _for, _v, _r, _s)); // if ETH is provided, ensure that the amount is identical to _amount and verify that the source token is an ether token IERC20Token fromToken = _path[0]; IERC20Token toToken; (toToken, _amount) = convertByPath(_path, _amount, _minReturn, fromToken, _for); // finished the conversion, transfer the funds to the target account // if the target token is an ether token, withdraw the tokens and send them as ETH // otherwise, transfer the tokens as is if (etherTokens[toToken]) IEtherToken(toToken).withdrawTo(_for, _amount); else assert(toToken.transfer(_for, _amount)); return _amount; } /** @dev executes the actual conversion by following the conversion path @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _fromToken ERC20 token to convert from (the first element in the path) @param _for account that will receive the conversion result @return ERC20 token to convert to (the last element in the path) & tokens issued in return */ function convertByPath( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, IERC20Token _fromToken, address _for ) private returns (IERC20Token, uint256) { ISmartToken smartToken; IERC20Token toToken; IBancorConverter converter; // get the contract features address from the registry IContractFeatures features = IContractFeatures(registry.getAddress(ContractIds.CONTRACT_FEATURES)); // iterate over the conversion path uint256 pathLength = _path.length; for (uint256 i = 1; i < pathLength; i += 2) { smartToken = ISmartToken(_path[i]); toToken = _path[i + 1]; converter = IBancorConverter(smartToken.owner()); checkWhitelist(converter, _for, features); // if the smart token isn't the source (from token), the converter doesn't have control over it and thus we need to approve the request if (smartToken != _fromToken) ensureAllowance(_fromToken, converter, _amount); // make the conversion - if it's the last one, also provide the minimum return value _amount = converter.change(_fromToken, toToken, _amount, i == pathLength - 2 ? _minReturn : 1); _fromToken = toToken; } return (toToken, _amount); } /** @dev checks whether the given converter supports a whitelist and if so, ensures that the account that should receive the conversion result is actually whitelisted @param _converter converter to check for whitelist @param _for account that will receive the conversion result @param _features contract features contract address */ function checkWhitelist(IBancorConverter _converter, address _for, IContractFeatures _features) private view { IWhitelist whitelist; // check if the converter supports the conversion whitelist feature if (!_features.isSupported(_converter, FeatureIds.CONVERTER_CONVERSION_WHITELIST)) return; // get the whitelist contract from the converter whitelist = _converter.conversionWhitelist(); if (whitelist == address(0)) return; // check if the account that should receive the conversion result is actually whitelisted require(whitelist.isWhitelisted(_for)); } /** @dev claims the caller's tokens, converts them to any other token in the bancor network by following a predefined conversion path and transfers the result tokens to a target account note that allowance must be set beforehand @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _for account that will receive the conversion result @return tokens issued in return */ function claimAndConvertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public returns (uint256) { // we need to transfer the tokens from the caller to the converter before we follow // the conversion path, to allow it to execute the conversion on behalf of the caller // note: we assume we already have allowance IERC20Token fromToken = _path[0]; assert(fromToken.transferFrom(msg.sender, this, _amount)); return convertFor(_path, _amount, _minReturn, _for); } /** @dev converts the token to any other token in the bancor network by following a predefined conversion path and transfers the result tokens back to the sender note that the converter should already own the source tokens @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return tokens issued in return */ function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256) { return convertFor(_path, _amount, _minReturn, msg.sender); } /** @dev claims the caller's tokens, converts them to any other token in the bancor network by following a predefined conversion path and transfers the result tokens back to the sender note that allowance must be set beforehand @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return tokens issued in return */ function claimAndConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public returns (uint256) { return claimAndConvertFor(_path, _amount, _minReturn, msg.sender); } /** @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't @param _token token to check the allowance in @param _spender approved address @param _value allowance amount */ function ensureAllowance(IERC20Token _token, address _spender, uint256 _value) private { // check if allowance for the given amount already exists if (_token.allowance(this, _spender) >= _value) return; // if the allowance is nonzero, must reset it to 0 first if (_token.allowance(this, _spender) != 0) assert(_token.approve(_spender, 0)); // approve the new allowance assert(_token.approve(_spender, _value)); } // deprecated, backward compatibility function convertForPrioritized( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public payable returns (uint256) { convertForPrioritized2(_path, _amount, _minReturn, _for, _block, _v, _r, _s); } }
/ check if allowance for the given amount already exists if the allowance is nonzero, must reset it to 0 first approve the new allowance
function ensureAllowance(IERC20Token _token, address _spender, uint256 _value) private { if (_token.allowance(this, _spender) >= _value) return; if (_token.allowance(this, _spender) != 0) assert(_token.approve(_spender, 0)); assert(_token.approve(_spender, _value)); }
1,222,388
[ 1, 19, 866, 309, 1699, 1359, 364, 326, 864, 3844, 1818, 1704, 309, 326, 1699, 1359, 353, 16966, 16, 1297, 2715, 518, 358, 374, 1122, 6617, 537, 326, 394, 1699, 1359, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3387, 7009, 1359, 12, 45, 654, 39, 3462, 1345, 389, 2316, 16, 1758, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 3238, 288, 203, 3639, 309, 261, 67, 2316, 18, 5965, 1359, 12, 2211, 16, 389, 87, 1302, 264, 13, 1545, 389, 1132, 13, 203, 5411, 327, 31, 203, 203, 3639, 309, 261, 67, 2316, 18, 5965, 1359, 12, 2211, 16, 389, 87, 1302, 264, 13, 480, 374, 13, 203, 5411, 1815, 24899, 2316, 18, 12908, 537, 24899, 87, 1302, 264, 16, 374, 10019, 203, 203, 3639, 1815, 24899, 2316, 18, 12908, 537, 24899, 87, 1302, 264, 16, 389, 1132, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.22; // 0x40c914c3A8Fc4c3ccC1d3682828928515DFa631b, uses 64050 gas contract ModerateGasConsumingPayableFallback { function() public payable { for (uint i = 0; i < 1000; i++) {} } }
0x40c914c3A8Fc4c3ccC1d3682828928515DFa631b, uses 64050 gas
contract ModerateGasConsumingPayableFallback { function() public payable { } for (uint i = 0; i < 1000; i++) {} }
12,767,616
[ 1, 20, 92, 7132, 71, 29, 3461, 71, 23, 37, 28, 42, 71, 24, 71, 23, 952, 39, 21, 72, 5718, 28, 6030, 6030, 29, 6030, 25, 3600, 4577, 69, 4449, 21, 70, 16, 4692, 5178, 20, 3361, 16189, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3431, 12600, 27998, 11911, 310, 9148, 429, 12355, 288, 203, 203, 565, 445, 1435, 1071, 8843, 429, 288, 7010, 203, 203, 565, 289, 203, 377, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 4336, 31, 277, 27245, 2618, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/5/0xdE4c870F36a614E44bd00f987B22F4c4D48718F3/sources/contracts/base/MetawinERC721.sol
* @dev [View][Public] Return the alternative token URI @param _tokenId Token ID/
function tokenURI_alternative(uint256 _tokenId) public view virtual returns (string memory){ string memory baseURI = useMetawinUri ? getUri("base") : getUri("baseMW"); return getTokenURI(baseURI, _tokenId); }
16,866,959
[ 1, 63, 1767, 6362, 4782, 65, 2000, 326, 10355, 1147, 3699, 225, 389, 2316, 548, 3155, 1599, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1147, 3098, 67, 27071, 12, 11890, 5034, 389, 2316, 548, 13, 1071, 1476, 5024, 1135, 261, 1080, 3778, 15329, 203, 3639, 533, 3778, 1026, 3098, 273, 999, 2781, 8082, 3006, 692, 9713, 2932, 1969, 7923, 294, 9713, 2932, 1969, 49, 59, 8863, 203, 3639, 327, 9162, 3098, 12, 1969, 3098, 16, 389, 2316, 548, 1769, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT 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; /** * @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 Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // 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) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } else if (signature.length == 64) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } } else { revert("ECDSA: invalid signature length"); } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (governor) that can be granted exclusive access to * specific functions. * * By default, the governor account will be the one that deploys the contract. This * can later be changed with {transferGovernorship}. * */ contract Governed is Context, Initializable { address public governor; address private proposedGovernor; event UpdatedGovernor(address indexed previousGovernor, address indexed proposedGovernor); /** * @dev Initializes the contract setting the deployer as the initial governor. */ constructor() { address msgSender = _msgSender(); governor = msgSender; emit UpdatedGovernor(address(0), msgSender); } /** * @dev If inheriting child is using proxy then child contract can use * _initializeGoverned() function to initialization this contract */ function _initializeGoverned() internal initializer { address msgSender = _msgSender(); governor = msgSender; emit UpdatedGovernor(address(0), msgSender); } /** * @dev Throws if called by any account other than the governor. */ modifier onlyGovernor { require(governor == _msgSender(), "not-the-governor"); _; } /** * @dev Transfers governorship of the contract to a new account (`proposedGovernor`). * Can only be called by the current owner. */ function transferGovernorship(address _proposedGovernor) external onlyGovernor { require(_proposedGovernor != address(0), "proposed-governor-is-zero"); proposedGovernor = _proposedGovernor; } /** * @dev Allows new governor to accept governorship of the contract. */ function acceptGovernorship() external { require(proposedGovernor == _msgSender(), "not-the-proposed-governor"); emit UpdatedGovernor(governor, proposedGovernor); governor = proposedGovernor; proposedGovernor = address(0); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * */ contract Pausable is Context { event Paused(address account); event Shutdown(address account); event Unpaused(address account); event Open(address account); bool public paused; bool public stopEverything; modifier whenNotPaused() { require(!paused, "paused"); _; } modifier whenPaused() { require(paused, "not-paused"); _; } modifier whenNotShutdown() { require(!stopEverything, "shutdown"); _; } modifier whenShutdown() { require(stopEverything, "not-shutdown"); _; } /// @dev Pause contract operations, if contract is not paused. function _pause() internal virtual whenNotPaused { paused = true; emit Paused(_msgSender()); } /// @dev Unpause contract operations, allow only if contract is paused and not shutdown. function _unpause() internal virtual whenPaused whenNotShutdown { paused = false; emit Unpaused(_msgSender()); } /// @dev Shutdown contract operations, if not already shutdown. function _shutdown() internal virtual whenNotShutdown { stopEverything = true; paused = true; emit Shutdown(_msgSender()); } /// @dev Open contract operations, if contract is in shutdown state function _open() internal virtual whenShutdown { stopEverything = false; emit Open(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IAddressList { function add(address a) external returns (bool); function remove(address a) external returns (bool); function get(address a) external view returns (uint256); function contains(address a) external view returns (bool); function length() external view returns (uint256); function grantRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IAddressListFactory { function ours(address a) external view returns (bool); function listCount() external view returns (uint256); function listAt(uint256 idx) external view returns (address); function createList() external returns (address listaddr); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IPoolAccountant { function decreaseDebt(address _strategy, uint256 _decreaseBy) external; function migrateStrategy(address _old, address _new) external; function reportEarning( address _strategy, uint256 _profit, uint256 _loss, uint256 _payback ) external returns ( uint256 _actualPayback, uint256 _creditLine, uint256 _interestFee ); function reportLoss(address _strategy, uint256 _loss) external; function availableCreditLimit(address _strategy) external view returns (uint256); function excessDebt(address _strategy) external view returns (uint256); function getStrategies() external view returns (address[] memory); function getWithdrawQueue() external view returns (address[] memory); function strategy(address _strategy) external view returns ( bool _active, uint256 _interestFee, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio ); function totalDebt() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalDebtRatio() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IPoolRewards { /// Emitted after reward added event RewardAdded(uint256 reward); /// Emitted whenever any user claim rewards event RewardPaid(address indexed user, uint256 reward); /// Emitted when reward is ended event RewardEnded(address indexed dustReceiver, uint256 dust); // Emitted when pool governor update reward end time event UpdatedRewardEndTime(uint256 previousRewardEndTime, uint256 newRewardEndTime); function claimReward(address) external; function notifyRewardAmount(uint256 rewardAmount, uint256 endTime) external; function updateRewardEndTime() external; function updateReward(address) external; function withdrawRemaining(address _toAddress) external; function claimable(address) external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function rewardForDuration() external view returns (uint256); function rewardPerToken() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IStrategy { function rebalance() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function feeCollector() external view returns (address); function isReservedToken(address _token) external view returns (bool); function migrate(address _newStrategy) external; function token() external view returns (address); function totalValue() external view returns (uint256); function pool() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; /// @title Errors library library Errors { string public constant INVALID_COLLATERAL_AMOUNT = "1"; // Collateral must be greater than 0 string public constant INVALID_SHARE_AMOUNT = "2"; // Share must be greater than 0 string public constant INVALID_INPUT_LENGTH = "3"; // Input array length must be greater than 0 string public constant INPUT_LENGTH_MISMATCH = "4"; // Input array length mismatch with another array length string public constant NOT_WHITELISTED_ADDRESS = "5"; // Caller is not whitelisted to withdraw without fee string public constant MULTI_TRANSFER_FAILED = "6"; // Multi transfer of tokens has failed string public constant FEE_COLLECTOR_NOT_SET = "7"; // Fee Collector is not set string public constant NOT_ALLOWED_TO_SWEEP = "8"; // Token is not allowed to sweep string public constant INSUFFICIENT_BALANCE = "9"; // Insufficient balance to performs operations to follow string public constant INPUT_ADDRESS_IS_ZERO = "10"; // Input address is zero string public constant FEE_LIMIT_REACHED = "11"; // Fee must be less than MAX_BPS string public constant ALREADY_INITIALIZED = "12"; // Data structure, contract, or logic already initialized and can not be called again string public constant ADD_IN_LIST_FAILED = "13"; // Cannot add address in address list string public constant REMOVE_FROM_LIST_FAILED = "14"; // Cannot remove address from address list string public constant STRATEGY_IS_ACTIVE = "15"; // Strategy is already active, an inactive strategy is required string public constant STRATEGY_IS_NOT_ACTIVE = "16"; // Strategy is not active, an active strategy is required string public constant INVALID_STRATEGY = "17"; // Given strategy is not a strategy of this pool string public constant DEBT_RATIO_LIMIT_REACHED = "18"; // Debt ratio limit reached. It must be less than MAX_BPS string public constant TOTAL_DEBT_IS_NOT_ZERO = "19"; // Strategy total debt must be 0 string public constant LOSS_TOO_HIGH = "20"; // Strategy reported loss must be less than current debt } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/utils/Context.sol"; // solhint-disable reason-string, no-empty-blocks ///@title Pool ERC20 to use with proxy. Inspired by OpenZeppelin ERC20 abstract contract PoolERC20 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}. */ 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 decimals of the token. default to 18 */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev Returns total supply of the token. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by `account`. */ 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 {} function _setName(string memory name_) internal { _name = name_; } function _setSymbol(string memory symbol_) internal { _symbol = symbol_; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "./PoolERC20.sol"; ///@title Pool ERC20 Permit to use with proxy. Inspired by OpenZeppelin ERC20Permit // solhint-disable var-name-mixedcase abstract contract PoolERC20Permit is PoolERC20, IERC20Permit { bytes32 private constant _EIP712_VERSION = keccak256(bytes("1")); bytes32 private constant _EIP712_DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bytes32 private constant _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private _CACHED_DOMAIN_SEPARATOR; bytes32 private _HASHED_NAME; uint256 private _CACHED_CHAIN_ID; /** * @dev See {IERC20Permit-nonces}. */ mapping(address => uint256) public override nonces; /** * @dev Initializes the domain separator using the `name` parameter, and setting `version` to `"1"`. * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ function _initializePermit(string memory name_) internal { _HASHED_NAME = keccak256(bytes(name_)); _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(_EIP712_DOMAIN_TYPEHASH, _HASHED_NAME, _EIP712_VERSION); } /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); uint256 _currentNonce = nonces[owner]; bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _currentNonce, deadline)); bytes32 hash = keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); nonces[owner] = _currentNonce + 1; _approve(owner, spender, value); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() private view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_EIP712_DOMAIN_TYPEHASH, _HASHED_NAME, _EIP712_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 name, bytes32 version ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, name, version, block.chainid, address(this))); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./PoolERC20Permit.sol"; import "./PoolStorage.sol"; import "./Errors.sol"; import "../Governed.sol"; import "../Pausable.sol"; import "../interfaces/bloq/IAddressList.sol"; import "../interfaces/vesper/IPoolRewards.sol"; /// @title Holding pool share token // solhint-disable no-empty-blocks abstract contract PoolShareToken is Initializable, PoolStorageV1, PoolERC20Permit, Governed, Pausable, ReentrancyGuard { using SafeERC20 for IERC20; uint256 public constant MAX_BPS = 10_000; event Deposit(address indexed owner, uint256 shares, uint256 amount); event Withdraw(address indexed owner, uint256 shares, uint256 amount); constructor( string memory _name, string memory _symbol, address _token ) PoolERC20(_name, _symbol) { token = IERC20(_token); } /// @dev Equivalent to constructor for proxy. It can be called only once per proxy. function _initializePool( string memory _name, string memory _symbol, address _token ) internal initializer { _setName(_name); _setSymbol(_symbol); _initializePermit(_name); token = IERC20(_token); // Assuming token supports 18 or less decimals uint256 _decimals = IERC20Metadata(_token).decimals(); decimalConversionFactor = _decimals == 18 ? 1 : 10**(18 - _decimals); } /** * @notice Deposit ERC20 tokens and receive pool shares depending on the current share price. * @param _amount ERC20 token amount. */ function deposit(uint256 _amount) external virtual nonReentrant whenNotPaused { _deposit(_amount); } /** * @notice Deposit ERC20 tokens with permit aka gasless approval. * @param _amount ERC20 token amount. * @param _deadline The time at which signature will expire * @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 depositWithPermit( uint256 _amount, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external virtual nonReentrant whenNotPaused { IERC20Permit(address(token)).permit(_msgSender(), address(this), _amount, _deadline, _v, _r, _s); _deposit(_amount); } /** * @notice Withdraw collateral based on given shares and the current share price. * Withdraw fee, if any, will be deduced from given shares and transferred to feeCollector. * Burn remaining shares and return collateral. * @param _shares Pool shares. It will be in 18 decimals. */ function withdraw(uint256 _shares) external virtual nonReentrant whenNotShutdown { _withdraw(_shares); } /** * @notice Withdraw collateral based on given shares and the current share price. * @dev Burn shares and return collateral. No withdraw fee will be assessed * when this function is called. Only some white listed address can call this function. * @param _shares Pool shares. It will be in 18 decimals. */ function whitelistedWithdraw(uint256 _shares) external virtual nonReentrant whenNotShutdown { require(IAddressList(feeWhitelist).contains(_msgSender()), Errors.NOT_WHITELISTED_ADDRESS); _withdrawWithoutFee(_shares); } /** * @notice Transfer tokens to multiple recipient * @dev Address array and amount array are 1:1 and are in order. * @param _recipients array of recipient addresses * @param _amounts array of token amounts * @return true/false */ function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool) { require(_recipients.length == _amounts.length, Errors.INPUT_LENGTH_MISMATCH); for (uint256 i = 0; i < _recipients.length; i++) { require(transfer(_recipients[i], _amounts[i]), Errors.MULTI_TRANSFER_FAILED); } return true; } /** * @notice Get price per share * @dev Return value will be in token defined decimals. */ function pricePerShare() public view returns (uint256) { if (totalSupply() == 0 || totalValue() == 0) { return convertFrom18(1e18); } return (totalValue() * 1e18) / totalSupply(); } /// @dev Convert from 18 decimals to token defined decimals. function convertFrom18(uint256 _amount) public view virtual returns (uint256) { return _amount / decimalConversionFactor; } /// @dev Returns the token stored in the pool. It will be in token defined decimals. function tokensHere() public view virtual returns (uint256) { return token.balanceOf(address(this)); } /** * @dev Returns sum of token locked in other contracts and token stored in the pool. * Default tokensHere. It will be in token defined decimals. */ function totalValue() public view virtual returns (uint256); /** * @dev Hook that is called just before burning tokens. This withdraw collateral from withdraw queue * @param _share Pool share in 18 decimals */ function _beforeBurning(uint256 _share) internal virtual returns (uint256) {} /** * @dev Hook that is called just after burning tokens. * @param _amount Collateral amount in collateral token defined decimals. */ function _afterBurning(uint256 _amount) internal virtual returns (uint256) { token.safeTransfer(_msgSender(), _amount); return _amount; } /** * @dev Hook that is called just before minting new tokens. To be used i.e. * if the deposited amount is to be transferred from user to this contract. * @param _amount Collateral amount in collateral token defined decimals. */ function _beforeMinting(uint256 _amount) internal virtual { token.safeTransferFrom(_msgSender(), address(this), _amount); } /** * @dev Hook that is called just after minting new tokens. To be used i.e. * if the deposited amount is to be transferred to a different contract. * @param _amount Collateral amount in collateral token defined decimals. */ function _afterMinting(uint256 _amount) internal virtual {} /// @dev Update pool rewards of sender and receiver during transfer. function _transfer( address sender, address recipient, uint256 amount ) internal virtual override { if (poolRewards != address(0)) { IPoolRewards(poolRewards).updateReward(sender); IPoolRewards(poolRewards).updateReward(recipient); } super._transfer(sender, recipient, amount); } /** * @dev Calculate shares to mint based on the current share price and given amount. * @param _amount Collateral amount in collateral token defined decimals. * @return share amount in 18 decimal */ function _calculateShares(uint256 _amount) internal view returns (uint256) { require(_amount != 0, Errors.INVALID_COLLATERAL_AMOUNT); uint256 _share = ((_amount * 1e18) / pricePerShare()); return _amount > ((_share * pricePerShare()) / 1e18) ? _share + 1 : _share; } /// @notice claim rewards of account function _claimRewards(address _account) internal { if (poolRewards != address(0)) { IPoolRewards(poolRewards).claimReward(_account); } } /// @dev Deposit incoming token and mint pool token i.e. shares. function _deposit(uint256 _amount) internal { _claimRewards(_msgSender()); uint256 _shares = _calculateShares(_amount); _beforeMinting(_amount); _mint(_msgSender(), _shares); _afterMinting(_amount); emit Deposit(_msgSender(), _shares, _amount); } /// @dev Burns shares and returns the collateral value, after fee, of those. function _withdraw(uint256 _shares) internal { if (withdrawFee == 0) { _withdrawWithoutFee(_shares); } else { require(_shares != 0, Errors.INVALID_SHARE_AMOUNT); _claimRewards(_msgSender()); uint256 _fee = (_shares * withdrawFee) / MAX_BPS; uint256 _sharesAfterFee = _shares - _fee; uint256 _amountWithdrawn = _beforeBurning(_sharesAfterFee); // Recalculate proportional share on actual amount withdrawn uint256 _proportionalShares = _calculateShares(_amountWithdrawn); // Using convertFrom18() to avoid dust. // Pool share token is in 18 decimal and collateral token decimal is <=18. // Anything less than 10**(18-collateralTokenDecimal) is dust. if (convertFrom18(_proportionalShares) < convertFrom18(_sharesAfterFee)) { // Recalculate shares to withdraw, fee and shareAfterFee _shares = (_proportionalShares * MAX_BPS) / (MAX_BPS - withdrawFee); _fee = _shares - _proportionalShares; _sharesAfterFee = _proportionalShares; } _burn(_msgSender(), _sharesAfterFee); _transfer(_msgSender(), feeCollector, _fee); _afterBurning(_amountWithdrawn); emit Withdraw(_msgSender(), _shares, _amountWithdrawn); } } /// @dev Burns shares and returns the collateral value of those. function _withdrawWithoutFee(uint256 _shares) internal { require(_shares != 0, Errors.INVALID_SHARE_AMOUNT); _claimRewards(_msgSender()); uint256 _amountWithdrawn = _beforeBurning(_shares); uint256 _proportionalShares = _calculateShares(_amountWithdrawn); if (convertFrom18(_proportionalShares) < convertFrom18(_shares)) { _shares = _proportionalShares; } _burn(_msgSender(), _shares); _afterBurning(_amountWithdrawn); emit Withdraw(_msgSender(), _shares, _amountWithdrawn); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract PoolStorageV1 { IERC20 public token; // Collateral token address public poolAccountant; // PoolAccountant address address public poolRewards; // PoolRewards contract address address public feeWhitelist; // sol-address-list address which contains whitelisted addresses to withdraw without fee address public keepers; // sol-address-list address which contains addresses of keepers address public maintainers; // sol-address-list address which contains addresses of maintainers address public feeCollector; // Fee collector address uint256 public withdrawFee; // Withdraw fee for this pool uint256 public decimalConversionFactor; // It can be used in converting value to/from 18 decimals bool internal withdrawInETH; // This flag will be used by VETH pool as switch to withdraw ETH or WETH } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./VPoolBase.sol"; //solhint-disable no-empty-blocks contract VPool is VPoolBase { string public constant VERSION = "3.0.3"; constructor( string memory _name, string memory _symbol, address _token ) VPoolBase(_name, _symbol, _token) {} function initialize( string memory _name, string memory _symbol, address _token, address _poolAccountant, address _addressListFactory ) public initializer { _initializeBase(_name, _symbol, _token, _poolAccountant, _addressListFactory); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./Errors.sol"; import "./PoolShareToken.sol"; import "../interfaces/vesper/IPoolAccountant.sol"; import "../interfaces/vesper/IStrategy.sol"; import "../interfaces/bloq/IAddressListFactory.sol"; abstract contract VPoolBase is PoolShareToken { using SafeERC20 for IERC20; event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector); event UpdatedPoolRewards(address indexed previousPoolRewards, address indexed newPoolRewards); event UpdatedWithdrawFee(uint256 previousWithdrawFee, uint256 newWithdrawFee); constructor( string memory _name, string memory _symbol, address _token // solhint-disable-next-line no-empty-blocks ) PoolShareToken(_name, _symbol, _token) {} /// @dev Equivalent to constructor for proxy. It can be called only once per proxy. function _initializeBase( string memory _name, string memory _symbol, address _token, address _poolAccountant, address _addressListFactory ) internal initializer { _initializePool(_name, _symbol, _token); _initializeGoverned(); _initializeAddressLists(_addressListFactory); poolAccountant = _poolAccountant; } /** * @notice Create feeWhitelist, keeper and maintainer list * @dev Add caller into the keeper and maintainer list * @dev This function will be used as part of initializer * @param _addressListFactory To support same code in eth side chain, user _addressListFactory as param * ethereum - 0xded8217De022706A191eE7Ee0Dc9df1185Fb5dA3 * polygon - 0xD10D5696A350D65A9AA15FE8B258caB4ab1bF291 */ function _initializeAddressLists(address _addressListFactory) internal { require(address(keepers) == address(0), Errors.ALREADY_INITIALIZED); IAddressListFactory _factory = IAddressListFactory(_addressListFactory); feeWhitelist = _factory.createList(); keepers = _factory.createList(); maintainers = _factory.createList(); // List creator can do job of keeper and maintainer. IAddressList(keepers).add(_msgSender()); IAddressList(maintainers).add(_msgSender()); } modifier onlyKeeper() { require(IAddressList(keepers).contains(_msgSender()), "not-a-keeper"); _; } modifier onlyMaintainer() { require(IAddressList(maintainers).contains(_msgSender()), "not-a-maintainer"); _; } ////////////////////////////// Only Governor ////////////////////////////// /** * @notice Migrate existing strategy to new strategy. * @dev Migrating strategy aka old and new strategy should be of same type. * @param _old Address of strategy being migrated * @param _new Address of new strategy */ function migrateStrategy(address _old, address _new) external onlyGovernor { require( IStrategy(_new).pool() == address(this) && IStrategy(_old).pool() == address(this), Errors.INVALID_STRATEGY ); IPoolAccountant(poolAccountant).migrateStrategy(_old, _new); IStrategy(_old).migrate(_new); } /** * @notice Update fee collector address for this pool * @param _newFeeCollector new fee collector address */ function updateFeeCollector(address _newFeeCollector) external onlyGovernor { require(_newFeeCollector != address(0), Errors.INPUT_ADDRESS_IS_ZERO); emit UpdatedFeeCollector(feeCollector, _newFeeCollector); feeCollector = _newFeeCollector; } /** * @notice Update pool rewards address for this pool * @param _newPoolRewards new pool rewards address */ function updatePoolRewards(address _newPoolRewards) external onlyGovernor { require(_newPoolRewards != address(0), Errors.INPUT_ADDRESS_IS_ZERO); emit UpdatedPoolRewards(poolRewards, _newPoolRewards); poolRewards = _newPoolRewards; } /** * @notice Update withdraw fee for this pool * @dev Format: 1500 = 15% fee, 100 = 1% * @param _newWithdrawFee new withdraw fee */ function updateWithdrawFee(uint256 _newWithdrawFee) external onlyGovernor { require(feeCollector != address(0), Errors.FEE_COLLECTOR_NOT_SET); require(_newWithdrawFee <= MAX_BPS, Errors.FEE_LIMIT_REACHED); emit UpdatedWithdrawFee(withdrawFee, _newWithdrawFee); withdrawFee = _newWithdrawFee; } ///////////////////////////// Only Keeper /////////////////////////////// function pause() external onlyKeeper { _pause(); } function unpause() external onlyKeeper { _unpause(); } function shutdown() external onlyKeeper { _shutdown(); } function open() external onlyKeeper { _open(); } /** * @notice Add given address in provided address list. * @dev Use it to add keeper in keepers list and to add address in feeWhitelist * @param _listToUpdate address of AddressList contract. * @param _addressToAdd address which we want to add in AddressList. */ function addInList(address _listToUpdate, address _addressToAdd) external onlyKeeper { require(IAddressList(_listToUpdate).add(_addressToAdd), Errors.ADD_IN_LIST_FAILED); } /** * @notice Remove given address from provided address list. * @dev Use it to remove keeper from keepers list and to remove address from feeWhitelist * @param _listToUpdate address of AddressList contract. * @param _addressToRemove address which we want to remove from AddressList. */ function removeFromList(address _listToUpdate, address _addressToRemove) external onlyKeeper { require(IAddressList(_listToUpdate).remove(_addressToRemove), Errors.REMOVE_FROM_LIST_FAILED); } /////////////////////////////////////////////////////////////////////////// /** * @dev Strategy call this in regular interval. * @param _profit yield generated by strategy. Strategy get performance fee on this amount * @param _loss Reduce debt ,also reduce debtRatio, increase loss in record. * @param _payback strategy willing to payback outstanding above debtLimit. no performance fee on this amount. * when governance has reduced debtRatio of strategy, strategy will report profit and payback amount separately. */ function reportEarning( uint256 _profit, uint256 _loss, uint256 _payback ) external { (uint256 _actualPayback, uint256 _creditLine, uint256 _interestFee) = IPoolAccountant(poolAccountant).reportEarning(_msgSender(), _profit, _loss, _payback); uint256 _totalPayback = _profit + _actualPayback; // After payback, if strategy has credit line available then send more fund to strategy // If payback is more than available credit line then get fund from strategy if (_totalPayback < _creditLine) { token.safeTransfer(_msgSender(), _creditLine - _totalPayback); } else if (_totalPayback > _creditLine) { token.safeTransferFrom(_msgSender(), address(this), _totalPayback - _creditLine); } // Mint interest fee worth shares at strategy address if (_interestFee != 0) { _mint(_msgSender(), _calculateShares(_interestFee)); } } /** * @notice Report loss outside of rebalance activity. * @dev Some strategies pay deposit fee thus realizing loss at deposit. * For example: Curve's 3pool has some slippage due to deposit of one asset in 3pool. * Strategy may want report this loss instead of waiting for next rebalance. * @param _loss Loss that strategy want to report */ function reportLoss(uint256 _loss) external { IPoolAccountant(poolAccountant).reportLoss(_msgSender(), _loss); } /** * @dev Transfer given ERC20 token to feeCollector * @param _fromToken Token address to sweep */ function sweepERC20(address _fromToken) external virtual onlyKeeper { require(_fromToken != address(token), Errors.NOT_ALLOWED_TO_SWEEP); require(feeCollector != address(0), Errors.FEE_COLLECTOR_NOT_SET); IERC20(_fromToken).safeTransfer(feeCollector, IERC20(_fromToken).balanceOf(address(this))); } /** * @notice Get available credit limit of strategy. This is the amount strategy can borrow from pool * @dev Available credit limit is calculated based on current debt of pool and strategy, current debt limit of pool and strategy. * credit available = min(pool's debt limit, strategy's debt limit, max debt per rebalance) * when some strategy do not pay back outstanding debt, this impact credit line of other strategy if totalDebt of pool >= debtLimit of pool * @param _strategy Strategy address */ function availableCreditLimit(address _strategy) external view returns (uint256) { return IPoolAccountant(poolAccountant).availableCreditLimit(_strategy); } /** * @notice Debt above current debt limit * @param _strategy Address of strategy */ function excessDebt(address _strategy) external view returns (uint256) { return IPoolAccountant(poolAccountant).excessDebt(_strategy); } function getStrategies() public view returns (address[] memory) { return IPoolAccountant(poolAccountant).getStrategies(); } function getWithdrawQueue() public view returns (address[] memory) { return IPoolAccountant(poolAccountant).getWithdrawQueue(); } function strategy(address _strategy) external view returns ( bool _active, uint256 _interestFee, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio ) { return IPoolAccountant(poolAccountant).strategy(_strategy); } /// @notice Get total debt of pool function totalDebt() external view returns (uint256) { return IPoolAccountant(poolAccountant).totalDebt(); } /** * @notice Get total debt of given strategy * @param _strategy Strategy address */ function totalDebtOf(address _strategy) public view returns (uint256) { return IPoolAccountant(poolAccountant).totalDebtOf(_strategy); } /// @notice Get total debt ratio. Total debt ratio helps us keep buffer in pool function totalDebtRatio() external view returns (uint256) { return IPoolAccountant(poolAccountant).totalDebtRatio(); } /// @dev Returns total value of vesper pool, in terms of collateral token function totalValue() public view override returns (uint256) { return IPoolAccountant(poolAccountant).totalDebt() + tokensHere(); } function _withdrawCollateral(uint256 _amount) internal virtual { // Withdraw amount from queue uint256 _debt; uint256 _balanceAfter; uint256 _balanceBefore; uint256 _amountWithdrawn; uint256 _amountNeeded = _amount; uint256 _totalAmountWithdrawn; address[] memory _withdrawQueue = getWithdrawQueue(); for (uint256 i; i < _withdrawQueue.length; i++) { _debt = totalDebtOf(_withdrawQueue[i]); if (_debt == 0) { continue; } if (_amountNeeded > _debt) { // Should not withdraw more than current debt of strategy. _amountNeeded = _debt; } _balanceBefore = tokensHere(); //solhint-disable no-empty-blocks try IStrategy(_withdrawQueue[i]).withdraw(_amountNeeded) {} catch { continue; } _balanceAfter = tokensHere(); _amountWithdrawn = _balanceAfter - _balanceBefore; // Adjusting totalDebt. Assuming that during next reportEarning(), strategy will report loss if amountWithdrawn < _amountNeeded IPoolAccountant(poolAccountant).decreaseDebt(_withdrawQueue[i], _amountWithdrawn); _totalAmountWithdrawn += _amountWithdrawn; if (_totalAmountWithdrawn >= _amount) { // withdraw done break; } _amountNeeded = _amount - _totalAmountWithdrawn; } } /** * @dev Before burning hook. * withdraw amount from strategies */ function _beforeBurning(uint256 _share) internal override returns (uint256 actualWithdrawn) { uint256 _amount = (_share * pricePerShare()) / 1e18; uint256 _balanceNow = tokensHere(); if (_amount > _balanceNow) { _withdrawCollateral(_amount - _balanceNow); _balanceNow = tokensHere(); } actualWithdrawn = _balanceNow < _amount ? _balanceNow : _amount; } }
* @dev Returns the domain separator for the current chain./
function _domainSeparatorV4() private view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; return _buildDomainSeparator(_EIP712_DOMAIN_TYPEHASH, _HASHED_NAME, _EIP712_VERSION); } }
166,324
[ 1, 1356, 326, 2461, 4182, 364, 326, 783, 2687, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4308, 6581, 58, 24, 1435, 3238, 1476, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 309, 261, 2629, 18, 5639, 350, 422, 389, 3587, 15023, 67, 1792, 6964, 67, 734, 13, 288, 203, 5411, 327, 389, 3587, 15023, 67, 18192, 67, 4550, 31, 203, 5411, 327, 389, 3510, 3748, 6581, 24899, 41, 2579, 27, 2138, 67, 18192, 67, 2399, 15920, 16, 389, 15920, 2056, 67, 1985, 16, 389, 41, 2579, 27, 2138, 67, 5757, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * A loan taken out of a circle. */ contract Loan { /** * The amount that was loaned, in pence GBP. */ uint public amount; /** * The interest percentage in hundredths of a percent point. I.e. * a value of 1 means 0.01%. */ uint public interestPercentage; /** * The MoneyCircles userId that took out the loan. The userId is * the ID as present in the MoneyCircles database. */ string public userId; /** * SHA3 hash of the user ID for comparisons. * Type conversions between string and bytesN in Solidity * and between Solidity and Javascript are still pretty rough. */ bytes32 public userIdHash; /** * The Circle that this loan was taken out from. */ address public circle; /** * The Uphold transaction ID where this loan was payed out. */ string public payoutTransactionId; // How to check whether a string is null or empty? Using a == "" // is not allowed by the compiler (sees "" as bytes0) bool public isPaidOut; /** * The Uphold transaction ID where this loan was payed repaid. */ string public repaymentTransactionId; bool public isRepaid; /** * Returns the total amount of interest, rounded to pence GBP. */ function getInterestAmount() constant returns (uint interestAmount) { interestAmount = (interestPercentage * amount) / 10000; return interestAmount; } /** * Returns the total amount to be repaid including interest. */ function getRepaymentAmount() constant returns (uint repaymentAmount) { repaymentAmount = amount + getInterestAmount(); } /** * Confirm that the loan has been paid out by referring to the Uphold * transaction in which it was paid. */ function setPaidOut(string bitReserveTxId) { if(msg.sender != circle) return; // Don't allow updating the tx ID. // Weakness: as the contract has no window to the outside world, we // can't see whether this is a real transaction, has the right amount, // is sent to the right recipient etc. Hence the transaction ID has // to be correct on the first go. // // A possible way to improve this is to allow only a fixed of oracles // to set (or confirm) the repayment transaction ID after having // verified it in "the real world". Storing the tx id's could then be // a two-step process and the functionality would be more decentralized. if(isPaidOut) return; payoutTransactionId = bitReserveTxId; isPaidOut = true; } /** * Confirm that the loan has been repaid by referring to the Uphold * transaction in which it was paid. */ function setRepaid(string bitReserveTxId) { if(msg.sender != circle) return; // Only allow repayment after paying out. if(!isPaidOut) return; // Don't allow updating the tx ID. if(isRepaid) return; repaymentTransactionId = bitReserveTxId; isRepaid = true; } function Loan(string newUserId, uint newAmount, uint newInterestPercentage) { userId = newUserId; userIdHash = sha3(newUserId); amount = newAmount; // We store the sender of the message as the circle address. // This adds some form of security: if anyone else would create a // Loan, and the address would not be from a Circle contract, that // Loan is not considered valid. circle = msg.sender; interestPercentage = newInterestPercentage; } } /** * A single Money Circle. The entry contract for all properties. */ contract Circle { string public name; string public commonBond; address public creator; /** * The interest percentage for loans in hundredths of a percent * point. I.e. a value of 1 means 0.01%. */ uint public interestPercentage; /** * The minimal percentage of deposited funds that must remain in * the Circle. No loans can be taken out below this percentage. */ uint public constant minimumBalancePercentage = 20; function Circle(string newName, string newCommonBond, uint newInterestPercentage) { name = newName; commonBond = newCommonBond; creator = msg.sender; interestPercentage = newInterestPercentage; } struct Member { string id; string username; } /** * A deposit to the Circle funds. */ struct Deposit { /** * The member that the deposit is from. */ string memberId; bytes32 memberIdHash; /** * Amount in pence. */ uint amount; /** * The Uphold transaction of the member to the Circle. */ string transactionId; } /** * The member list. Join date/time can be derived from the blockchain. */ mapping(uint => Member) public members; uint public memberIndex; /** * Index of the members by sha3(id), for getting members by ID. * Not done as string => uint because not supported by Solidity. * This is probably very inefficient because of the sha3(). */ mapping(bytes32 => uint) public memberIndexByIdHash; /** * All loans of this circle. Loans aren't removed from this list * when they are repaid yet. */ mapping(uint => Loan) public loans; uint public loanIndex; /** * All deposits. */ mapping(uint => Deposit) public deposits; uint public depositIndex; /** * Add a new member to the Circle. */ function addMember(string id, string userName) { if(msg.sender != creator) return; // Don't allow adding the same user twice. if(memberIndexByIdHash[sha3(id)] > 0) return; memberIndex++; Member m = members[memberIndex]; m.id = id; m.username = userName; memberIndexByIdHash[sha3(id)] = memberIndex; } /** * Returns the amount available for new loans, taking into * account the minimum balance percentage. */ function getAvailableBalance() constant returns (uint amount){ uint minimumAvailableAmount = getTotalDepositsAmount() * minimumBalancePercentage / 100; return getBalance() - minimumAvailableAmount; } /** * Create a new loan for a member. */ function createLoan(string memberId, uint amount) returns (Loan l) { if(msg.sender != creator) return; // Only allow loans by members. if(memberIndexByIdHash[sha3(memberId)] == 0) return; // Only allow loans if they're within the available balance. if(amount > getAvailableBalance()) return; loanIndex++; l = new Loan(memberId, amount, interestPercentage); loans[loanIndex] = l; return l; } /** * Confirm that the loan has been paid out by referring to the Uphold * transaction in which it was paid. */ function setPaidOut(Loan l, string bitReserveTxId) { if(msg.sender != creator) return; // Check if this loan is ours. Note that the Loan does this too. // TODO l.setPaidOut(bitReserveTxId); } /** * Confirm that the loan has been repaid by referring to the Uphold * transaction in which it was paid. */ function setRepaid(Loan l, string bitReserveTxId) { if(msg.sender != creator) return; // The Loan checks whether it belongs to this circle. Hence // we just call it. l.setRepaid(bitReserveTxId); } /** * Register a deposit of a member. */ function createDeposit(string memberId, uint amount, string transactionId) { if(msg.sender != creator) return; // Only allow loans by members. if(memberIndexByIdHash[sha3(memberId)] == 0) return; depositIndex++; Deposit d = deposits[depositIndex]; d.memberId = memberId; d.memberIdHash = sha3(memberId); d.amount = amount; d.transactionId = transactionId; } /** * Fired when the total amount of deposits has been computed. * Uses an event because transactional methods can't return * data to the outside world. */ event DepositsAmountComputed(uint value); /** * Get the total amount of all deposits. */ function getTotalDepositsAmount() constant returns (uint totalDepositsAmount) { for (uint i = 1; i <= depositIndex; i++) { totalDepositsAmount += deposits[i].amount; } return totalDepositsAmount; } /** * Calculates the total amount of all deposits and emits it * using the event DepositsAmountComputed. More of a testing * function than anything else. */ function calculateTotalDepositsAmount() { uint totalDepositsAmount; for (uint i = 1; i <= depositIndex; i++) { totalDepositsAmount += deposits[i].amount; } DepositsAmountComputed(totalDepositsAmount); } /** * Get the total amount of all loans that have not been repaid. */ function getTotalActiveLoansAmount() constant returns (uint totalLoansAmount) { for (uint i = 1; i <= loanIndex; i++) { var l = loans[i]; if(!l.isRepaid()) { totalLoansAmount += l.amount(); } } return totalLoansAmount; } /** * Get the total amount of all loans, excluding the ones that haven't * been paid out. */ function getTotalPaidLoansAmount() constant returns (uint totalLoansAmount) { for (uint i = 1; i <= loanIndex; i++) { var l = loans[i]; if(l.isPaidOut() && !l.isRepaid()) { totalLoansAmount += l.amount(); } } return totalLoansAmount; } /** * Get the total amount of interest that has been repaid. */ function getTotalRepaidInterestAmount() constant returns (uint totalInterestAmount) { for (uint i = 1; i <= loanIndex; i++) { var l = loans[i]; if(l.isRepaid()) { totalInterestAmount += l.getInterestAmount(); } } return totalInterestAmount; } /** * Get the total amount of all loans, excluding the ones that haven't * been paid out. */ function getTotalRepaidLoansAmount() constant returns (uint totalLoansAmount) { for (uint i = 1; i <= loanIndex; i++) { var l = loans[i]; if(l.isRepaid()) { totalLoansAmount += l.getRepaymentAmount(); } } return totalLoansAmount; } /** * Get the current balance of the circle, i.e.: * [total deposit amount] - [total loan amount] + [total repaid interest amount] */ function getBalance() constant returns (uint balance) { balance = getTotalDepositsAmount() - getTotalActiveLoansAmount() + getTotalRepaidInterestAmount(); return balance; } /** * Returns the balance for a specific member. I.e. [total deposits] - * [total active loans] */ function getMemberBalance(string memberId) constant returns (uint amount){ uint totalDepositsAmount; uint totalLoansAmount; var memberIdHash = sha3(memberId); // All deposits of the member contribute to the balance. for (uint i = 1; i <= depositIndex; i++) { if(deposits[i].memberIdHash == memberIdHash) totalDepositsAmount += deposits[i].amount; } // Loans that have not been repaid are subtracted. for (uint j = 1; j <= loanIndex; j++) { Loan l = loans[j]; if(l.userIdHash() == memberIdHash && !l.isRepaid()) totalLoansAmount += loans[j].amount(); } // TODO: Add dividends, withdrawals amount = totalDepositsAmount - totalLoansAmount; return amount; } }
* Add a new member to the Circle./ Don't allow adding the same user twice.
function addMember(string id, string userName) { if(msg.sender != creator) return; if(memberIndexByIdHash[sha3(id)] > 0) return; memberIndex++; Member m = members[memberIndex]; m.id = id; m.username = userName; memberIndexByIdHash[sha3(id)] = memberIndex; }
12,811,806
[ 1, 986, 279, 394, 3140, 358, 326, 29046, 18, 19, 7615, 1404, 1699, 6534, 326, 1967, 729, 13605, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 4419, 12, 1080, 612, 16, 533, 12065, 13, 288, 203, 3639, 309, 12, 3576, 18, 15330, 480, 11784, 13, 203, 5411, 327, 31, 203, 203, 3639, 309, 12, 5990, 1016, 5132, 2310, 63, 7819, 23, 12, 350, 25887, 405, 374, 13, 203, 5411, 327, 31, 203, 203, 3639, 3140, 1016, 9904, 31, 203, 203, 3639, 8596, 312, 273, 4833, 63, 5990, 1016, 15533, 203, 3639, 312, 18, 350, 273, 612, 31, 203, 3639, 312, 18, 5053, 273, 12065, 31, 203, 3639, 3140, 1016, 5132, 2310, 63, 7819, 23, 12, 350, 25887, 273, 3140, 1016, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "./Exchange.sol"; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); // event Transfer(address indexed from, address indexed to, uint256 value); // event Approval(address indexed owner, address indexed spender, uint256 value); // } contract GovToken is IERC20 { string public constant name = "GOVToken"; string public constant symbol = "GOV"; uint8 public constant decimals = 2; event Approval( address indexed tokenOwner, address indexed spender, uint256 tokens ); event Transfer(address indexed from, address indexed to, uint256 tokens); mapping(address => uint256) balances; mapping(address => uint256) locked; mapping(address => mapping(address => uint256)) allowed; uint256 _totalSupply = 100000; address public creator; address public exchangeAddress; using SafeMath for uint256; constructor() { balances[msg.sender] = (_totalSupply * 20) / 100; balances[address(this)] = (_totalSupply * 40) / 100; exchangeAddress = address(new Exchange(address(this), 100000000000000)); // price is 0.0001 eth i.e. 1eth = 10000 tokens balances[exchangeAddress] = (_totalSupply * 40) / 100; creator = msg.sender; } modifier onlyCreator() { require(msg.sender == creator, "Only creator can call this function"); _; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address tokenOwner) public view override returns (uint256) { return balances[tokenOwner]; } function lockedOf(address tokenOwner) public view returns (uint256) { return locked[tokenOwner]; } function transfer(address receiver, uint256 numTokens) public override returns (bool) { require( numTokens <= balances[msg.sender] - locked[msg.sender], "Governance::transfer:Insufficient tokens" ); balances[msg.sender] = balances[msg.sender].sub(numTokens); balances[receiver] = balances[receiver].add(numTokens); emit Transfer(msg.sender, receiver, numTokens); return true; } function transferFromContract(address receiver, uint256 numTokens) internal returns (bool) { require( numTokens <= balances[address(this)], "Governance::transferFromContract:Insufficient tokens" ); balances[address(this)] = balances[address(this)].sub(numTokens); balances[receiver] = balances[receiver].add(numTokens); emit Transfer(address(this), receiver, numTokens); return true; } function approve(address delegate, uint256 numTokens) public override returns (bool) { allowed[msg.sender][delegate] = numTokens; emit Approval(msg.sender, delegate, numTokens); return true; } function allowance(address owner, address delegate) public view override returns (uint256) { return allowed[owner][delegate]; } function transferFrom( address owner, address receiver, uint256 numTokens ) public override returns (bool) { require( numTokens <= allowed[owner][msg.sender], "Governance::transferFrom:Not Allowed" ); require( numTokens <= balances[owner] - locked[owner], "Governance::transferFrom:Insufficient tokens" ); balances[owner] = balances[owner].sub(numTokens); allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens); balances[receiver] = balances[receiver].add(numTokens); emit Transfer(owner, receiver, numTokens); return true; } function mint(uint256 numTokens) public onlyCreator { require( msg.sender != address(0), "Governance::mint: mint to the zero address" ); _totalSupply += numTokens; balances[msg.sender] += numTokens; emit Transfer(address(0), msg.sender, numTokens); } function burn(uint256 numTokens) public { require( msg.sender != address(0), "Governance::burn: burn from the zero address" ); require( balances[msg.sender] - locked[msg.sender] >= numTokens, "Governance::burn: burn amount exceeds balance" ); balances[msg.sender] -= numTokens; _totalSupply -= numTokens; emit Transfer(msg.sender, address(0), numTokens); } uint256 public proposalCount; uint256 tokensReqdForProposal = 1000; uint256 declaringResultReward = 500; function quorumVotes() public pure returns (uint256) { return 30; } /// @notice The total number of proposals struct Proposal { // Unique id for looking up a proposal uint256 id; // Creator of the proposal address proposer; // Current number of votes in favor of this proposal uint256 forVotes; // Current number of votes in opposition to this proposal uint256 againstVotes; // Flag marking whether the proposal has been canceled bool canceled; // Flag marking whether the proposal has been announced bool announced; uint256 voterCount; // description of the proposal string description; //title of the proposal string title; //creation date uint256 dateOfCreation; //cancellation date or announcement date uint256 date; // Deadln=ine for voting uint256 deadlineForVoting; } /// @notice Ballot receipt record for a voter struct Receipt { // Hether or not a vote has been cast bool hasVoted; // Whether or not the voter supports the proposal bool support; // The number of votes the voter had, which were cast uint256 votes; } // The official record of all proposals ever proposed mapping(uint256 => Proposal) public proposals; // To store receipts of all voters on all proposals // proposalId => (voterAddress => Receipt) mapping(uint256 => mapping(address => Receipt)) receipts; // To store all voters on all proposals // proposalId => (voterIndex => voterAddress) mapping(uint256 => mapping(uint256 => address)) voters; /// @notice Possible states that a proposal may be in enum ProposalState { Active, Canceled, Accepted, Rejected } /// @notice An event emitted when a new proposal is created event ProposalCreated( uint256 id, address proposer, string description, string title, uint256 dateOfCreation ); /// @notice An event emitted when a vote has been cast on a proposal event VoteCast( address voter, uint256 proposalId, bool support, uint256 votes ); function propose(string memory title, string memory description) external { require( balances[msg.sender] - locked[msg.sender] >= tokensReqdForProposal, "Governance::propose: User doesn't have sufficient token to create a new proposal" ); bool sent = transfer(address(this), tokensReqdForProposal); require(sent, "Governance::propose: Failure in transferring tokens"); if (proposalCount != 0) { ProposalState latestProposalState = state(proposalCount); require( latestProposalState != ProposalState.Active, "Governance::propose: one live proposal at a time, found an already active proposal" ); } proposalCount++; Proposal memory newProposal = Proposal({ id: proposalCount, proposer: msg.sender, description: description, forVotes: 0, againstVotes: 0, canceled: false, announced: false, deadlineForVoting: block.timestamp + 2 minutes, voterCount: 0, title: title, dateOfCreation: block.timestamp, date: block.timestamp }); proposals[newProposal.id] = newProposal; emit ProposalCreated( newProposal.id, msg.sender, description, title, newProposal.dateOfCreation ); } function getReceipt(uint256 proposalId, address voter) external view returns (Receipt memory) { return receipts[proposalId][voter]; } function state(uint256 proposalId) public view returns (ProposalState) { require( proposalCount >= proposalId && proposalId > 0, "Governance::state: invalid proposal id" ); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (proposal.announced) { if ( proposal.forVotes > proposal.againstVotes && proposal.forVotes > quorumVotes() ) { return ProposalState.Accepted; } else { return ProposalState.Rejected; } } else { return ProposalState.Active; } } function castVote( uint256 proposalId, bool support, uint256 votes ) external { require( proposalCount >= proposalId && proposalId > 0, "Governance::castVote: invalid proposal id" ); Proposal storage proposal = proposals[proposalId]; require( block.timestamp <= proposal.deadlineForVoting, "Governance::castVote: Voting period has ended" ); require( balances[msg.sender] - locked[msg.sender] >= votes, "Governance::castVote: User doesn't have sufficient token to vote" ); Receipt storage receipt = receipts[proposalId][msg.sender]; require( (receipt.hasVoted == false || receipt.support == support), "Governance::castVote: You can't cast vote to both outcome" ); if (receipt.hasVoted == true) { receipt.votes = receipt.votes + votes; } else { receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; voters[proposalId][proposal.voterCount] = msg.sender; proposal.voterCount++; } if (support) { proposal.forVotes = proposal.forVotes.add(votes); } else { proposal.againstVotes = proposal.againstVotes.add(votes); } locked[msg.sender] += votes; receipts[proposalId][msg.sender] = receipt; emit VoteCast(msg.sender, proposalId, support, votes); } function declareResult(uint256 proposalId) external { require( proposalCount >= proposalId && proposalId > 0, "Governance::declareResult: invalid proposal id" ); Proposal storage proposal = proposals[proposalId]; require( block.timestamp > proposal.deadlineForVoting, "Governance::declareResult: Voting period has not yet ended" ); ProposalState _ProposalState = state(proposalId); require( _ProposalState != ProposalState.Canceled, "Governance::declareResult: Prososal is canceled" ); require( _ProposalState != ProposalState.Accepted && _ProposalState != ProposalState.Rejected, "Governance::declareResult: Result already announced" ); for (uint256 i = 0; i < proposal.voterCount; i++) { Receipt storage receipt = receipts[proposalId][ voters[proposalId][i] ]; locked[voters[proposalId][i]] -= receipt.votes; } proposal.announced = true; transferFromContract(msg.sender, declaringResultReward); if ( proposal.forVotes > proposal.againstVotes && proposal.forVotes > quorumVotes() ) { //winning transferFromContract(proposal.proposer, tokensReqdForProposal); } } function cancelProposal(uint256 proposalId) external { require( proposalCount >= proposalId && proposalId > 0, "Governance::cancelProposal: invalid proposal id" ); Proposal storage proposal = proposals[proposalId]; require( msg.sender == proposal.proposer, "Governance::cancelProposal: only creator can cancel the proposal" ); require( block.timestamp < proposal.deadlineForVoting, "Governance::cancelProposal: Proposal cannot be Canceled after voting time" ); ProposalState _ProposalState = state(proposalId); require( _ProposalState != ProposalState.Canceled, "Governance::declareResult: Prososal is already canceled" ); proposal.canceled = true; for (uint256 i = 0; i < proposal.voterCount; i++) { Receipt storage receipt = receipts[proposalId][ voters[proposalId][i] ]; locked[voters[proposalId][i]] -= receipt.votes; } } struct Vote { address voterAddress; bool support; uint256 votes; } function getVotes(uint256 proposalId) public view returns (Vote[] memory) { uint256 voterCount = proposals[proposalId].voterCount; Vote[] memory votes = new Vote[](voterCount); for (uint256 i = 0; i < voterCount; i++) { votes[i] = Vote( voters[proposalId][i], receipts[proposalId][voters[proposalId][i]].support, receipts[proposalId][voters[proposalId][i]].votes ); } return votes; } } library SafeMath { 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; } }
@notice Possible states that a proposal may be in
enum ProposalState { Active, Canceled, Accepted, Rejected } uint256 id, address proposer, string description, string title, uint256 dateOfCreation ); address voter, uint256 proposalId, bool support, uint256 votes );
6,465,200
[ 1, 13576, 5493, 716, 279, 14708, 2026, 506, 316, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2792, 19945, 1119, 288, 203, 3639, 8857, 16, 203, 3639, 10347, 329, 16, 203, 3639, 8662, 329, 16, 203, 3639, 868, 6059, 203, 565, 289, 203, 203, 3639, 2254, 5034, 612, 16, 203, 3639, 1758, 450, 5607, 16, 203, 3639, 533, 2477, 16, 203, 3639, 533, 2077, 16, 203, 3639, 2254, 5034, 1509, 951, 9906, 203, 565, 11272, 203, 203, 3639, 1758, 331, 20005, 16, 203, 3639, 2254, 5034, 14708, 548, 16, 203, 3639, 1426, 2865, 16, 203, 3639, 2254, 5034, 19588, 203, 565, 11272, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xb85849a0B793e2Acaeb619dDf844e574B169F1D2/sources/contracts/BaseRewardPool4626.sol
* @dev Returns the amount of tokens in existence./
function totalSupply() public view override(BaseRewardPool, IERC20) returns (uint256) { return BaseRewardPool.totalSupply(); }
3,904,973
[ 1, 1356, 326, 3844, 434, 2430, 316, 15782, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 3849, 12, 2171, 17631, 1060, 2864, 16, 467, 654, 39, 3462, 13, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 3360, 17631, 1060, 2864, 18, 4963, 3088, 1283, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xFe81ab6930A30BdaE731fe7b6C6ABFbEAFc014a8/sources/contracts/Registry.sol
* @notice Update the address of an existing strategy @param _strategy The strategy contract address; @param _strategyId The strategy ID;/
function updateStrategy(address _strategy, uint32 _strategyId) external onlyOwner { require(_strategy != address(0), "Invalid strategy"); require(strategyIndexToAddress[_strategyId] != address(0), "Strategy doesn't exist"); address previousStrategy = strategyIndexToAddress[_strategyId]; strategyAddressToIndex[previousStrategy] = 0; strategyAddressToIndex[_strategy] = _strategyId; strategyIndexToAddress[_strategyId] = _strategy; emit StrategyUpdated(previousStrategy, _strategy, _strategyId); }
3,049,213
[ 1, 1891, 326, 1758, 434, 392, 2062, 6252, 225, 389, 14914, 1021, 6252, 6835, 1758, 31, 225, 389, 14914, 548, 1021, 6252, 1599, 31, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 4525, 12, 2867, 389, 14914, 16, 2254, 1578, 389, 14914, 548, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 24899, 14914, 480, 1758, 12, 20, 3631, 315, 1941, 6252, 8863, 203, 3639, 2583, 12, 14914, 1016, 774, 1887, 63, 67, 14914, 548, 65, 480, 1758, 12, 20, 3631, 315, 4525, 3302, 1404, 1005, 8863, 203, 203, 3639, 1758, 2416, 4525, 273, 6252, 1016, 774, 1887, 63, 67, 14914, 548, 15533, 203, 3639, 6252, 1887, 19418, 63, 11515, 4525, 65, 273, 374, 31, 203, 3639, 6252, 1887, 19418, 63, 67, 14914, 65, 273, 389, 14914, 548, 31, 203, 3639, 6252, 1016, 774, 1887, 63, 67, 14914, 548, 65, 273, 389, 14914, 31, 203, 203, 3639, 3626, 19736, 7381, 12, 11515, 4525, 16, 389, 14914, 16, 389, 14914, 548, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // Sources flattened with hardhat v2.6.1 https://hardhat.org // File @openzeppelin/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File @openzeppelin/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/utils/cryptography/[email protected] pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // File contracts/CryptoCrooks.sol pragma solidity ^0.8.0; contract CryptoCrooks is ERC721, ERC721Enumerable, Ownable { string public LICENSE_TEXT = "ALL RIGHTS TO TOKEN HOLDER"; string public CROOKS_PROVENANCE = ""; // IPFS URL WILL BE ADDED WHEN CROOKS ARE REVEALED string public nftBaseURI = ""; bool licenseLocked = false; // TEAM CAN'T EDIT THE LICENSE AFTER THIS GETS TRUE bool public saleIsActive = false; bool public preSaleIsActive = false; bytes32 public merkleTreeRoot; mapping(uint => string) public crookNames; // Custom names mapping(uint => string) public crookScenes; // Provenanced Scenes mapping(address => bool) public hasClaimed; // Has user claimed presale? // Address to transfer Fund fees to upon minting address payable public daoVaultAddress = payable(0x54Bc506b4EB3570522c062539b35E5b61853AbEc); uint public constant MAX_CROOKS = 5000; uint public constant maxCrookPurchase = 10; uint public constant daoShare = 80; // in %, Percentage of minting fee thats being payed to DAO on minting uint public crookReserve = 500; // Reserve 500 Crooks for team - Giveaways/Prizes etc uint public crookPresaleReserve = 250; // Reserve 250 Crooks for minting @ discount during presale phase uint256 public constant crookPrice = 80000000000000000; // 0.08 ETH uint256 public constant crookPresalePrice = 50000000000000000; // 0.05 ETH uint256 public constant changeCrookNamePrice = 10000000000000000; // 0.01 ETH uint256 public constant changeCrookScenePrice = 10000000000000000;// 0.01 ETH event LicenseIsLocked(string _licenseText); event PreSaleActivated(bool isActive); event PreSaleClaimed(address _by, uint _amount); event SaleActivated(bool isActive); event MintNFT(address _by, uint _amount); event DaoVaultAddressChanged(address payable _to); event DaoVaultFunded(uint256 amount); event CrookNameChanged(address _by, uint _tokenId, string _name); event CrookSceneChanged(address _by, uint _tokenId, string _name); constructor( bytes32 _merkleTreeRoot, address payable _daoVaultAddress, string memory _nftBaseURI ) ERC721("CryptoCrooksDAO", "CROOK") { merkleTreeRoot = _merkleTreeRoot; daoVaultAddress = _daoVaultAddress; nftBaseURI = _nftBaseURI; } /** START ERC721Enumerable Overrides **/ function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } /** END ERC721Enumerable Overrides **/ /** START MerkleTree **/ // Checks if a user is part of presale whitelist (using pre-generated MerkleTree) function verify(uint256 _amount, bytes32[] memory _proof) public view returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(msg.sender, _amount)); return MerkleProof.verify(_proof, merkleTreeRoot, leaf); } /** END MerkleTree **/ /** Custom baseURI **/ function baseURI () public view returns (string memory _uri) { return _baseURI(); } function setBaseURI (string memory _uri) public onlyOwner { nftBaseURI = _uri; } function _baseURI() internal view override returns (string memory) { return nftBaseURI; } /** END Custom baseURI **/ function setDaoVaultAddress(address payable _daoVaultAddress) public onlyOwner { daoVaultAddress = _daoVaultAddress; emit DaoVaultAddressChanged(_daoVaultAddress); } function setProvenanceHash(string memory _provenanceHash) public onlyOwner { CROOKS_PROVENANCE = _provenanceHash; } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(owner()).transfer(balance); } function flipPreSaleState() public onlyOwner { preSaleIsActive = !preSaleIsActive; emit PreSaleActivated(preSaleIsActive); } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; preSaleIsActive = false; // End presale emit SaleActivated(saleIsActive); } function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = this.balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = super.tokenOfOwnerByIndex(_owner, index); } return result; } } // Returns the license for tokens function tokenLicense(uint _id) public view returns(string memory) { require(_id < this.totalSupply(), "Choose a crook within range"); return LICENSE_TEXT; } // Locks the license to prevent further changes function lockLicense() public onlyOwner { licenseLocked = true; emit LicenseIsLocked(LICENSE_TEXT); } // Change the license function changeLicense(string memory _license) public onlyOwner { require(licenseLocked == false, "License already locked"); LICENSE_TEXT = _license; } // Overwriting forwardFunds function because otherwise we get a failed gas estimation error function _forwardFunds(uint256 _amount) internal { // Call returns a boolean value indicating success or failure. // This is the current recommended method to use. (bool success,) = daoVaultAddress.call{value: _amount}(''); require(success, 'Failed to forward funds'); } function _mintLoop(address _to, uint256 _amountToMint) internal { for (uint i = 0; i < _amountToMint; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_CROOKS) { _safeMint(_to, mintIndex); } } } // Mints amount of Crooks to specified address, and pays its funding to the DAO function _mintNFT(uint _amount) internal { uint256 fundAmount = (msg.value / 100) * daoShare; // Calculate 80% of sent funds _forwardFunds(fundAmount); // Transfer to DAO Vault emit DaoVaultFunded(fundAmount); _mintLoop(msg.sender, _amount); } // TEAM RESERVE MINT function mintTeamReserveNFTs(uint _reserveAmount) public onlyOwner { mintTeamReserveNFTsToAddress(msg.sender, _reserveAmount); } function mintTeamReserveNFTsToAddress(address _address, uint _reserveAmount) public onlyOwner { require(_reserveAmount > 0 && _reserveAmount <= crookReserve, "Trying to claim illegal amount"); crookReserve = crookReserve - _reserveAmount; _mintLoop(_address, _reserveAmount); } // FOR WHITELISTED PRESALE USERS (= Mentioned in MerkleTree) function claimPreSaleNFT(uint256 _amount, bytes32[] memory _proof) public payable { require(preSaleIsActive, "Presale must be active to reserve Crooks"); // Checks if user is part of presale Merkle Tree require(verify(_amount, _proof), "You have no presale claim"); require(!hasClaimed[msg.sender], "You have already claimed"); require(_amount > 0, "You need to claim more than 0 Crooks"); require(crookPresaleReserve > 0, "All presale Crooks have been claimed"); require(crookPresaleReserve - _amount >= 0, "Not enough presale Crooks left"); require(msg.value >= _amount * crookPresalePrice, "Ether value sent is not sufficient"); hasClaimed[msg.sender] = true; crookPresaleReserve = crookPresaleReserve - _amount; // Mint and transfer part of sent funds to CryptoCrooks DAO Vault _mintNFT(_amount); emit PreSaleClaimed(msg.sender, _amount); } // REGULAR MINTING function mintNFT(uint _amount) public payable { require(saleIsActive, "Sale must be active to mint Crooks"); require(_amount > 0 && _amount <= maxCrookPurchase, "You can only mint 10 crooks per transaction"); require(totalSupply() + _amount <= MAX_CROOKS, "Purchase would exceed max supply of Crooks"); require(msg.value >= crookPrice * _amount, "Ether value sent is not sufficient"); // Mint and transfer part of sent funds to CryptoCrooks DAO Vault _mintNFT(_amount); emit MintNFT(msg.sender, _amount); } function changeCrookName(uint _tokenId, string memory _name) public payable { require(ownerOf(_tokenId) == msg.sender, "Your wallet doesn't own this crook"); require(msg.value >= changeCrookNamePrice, "Ether value sent is not sufficient"); require(sha256(bytes(_name)) != sha256(bytes(crookNames[_tokenId])), "New name is same as current one"); crookNames[_tokenId] = _name; emit CrookNameChanged(msg.sender, _tokenId, _name); } function changeCrookScene(uint _tokenId, string memory _scene) public payable { require(this.ownerOf(_tokenId) == msg.sender, "Your wallet doesn't own this crook"); require(msg.value >= changeCrookScenePrice, "Ether value sent is not sufficient"); require(sha256(bytes(_scene)) != sha256(bytes(crookScenes[_tokenId])), "New scene is same as current one"); crookScenes[_tokenId] = _scene; emit CrookSceneChanged(msg.sender, _tokenId, _scene); } function getCrookScene(uint _tokenId) public view returns( string memory){ require( _tokenId < this.totalSupply(), "Choose a crook within range" ); return crookScenes[_tokenId]; } function getCrookName(uint _tokenId) public view returns( string memory ){ require( _tokenId < this.totalSupply(), "Choose a crook within range" ); return crookNames[_tokenId]; } // GET ALL CROOKS OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH function crookNamesOfOwner(address _owner) external view returns(string[] memory ) { uint256 tokenCount = this.balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new string[](0); } else { string[] memory result = new string[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = crookNames[this.tokenOfOwnerByIndex(_owner, index)] ; } return result; } } }
IPFS URL WILL BE ADDED WHEN CROOKS ARE REVEALED
string public CROOKS_PROVENANCE = "";
9,963,863
[ 1, 2579, 4931, 1976, 678, 15125, 9722, 11738, 7660, 29707, 385, 1457, 3141, 55, 432, 862, 2438, 3412, 37, 6687, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 533, 1071, 385, 1457, 3141, 55, 67, 3373, 58, 1157, 4722, 273, 1408, 31, 3639, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0x88D478CF7b25E40b17abAc7F0C63EA6c55bfE4eb/sources/contracts/JMPMural.sol
The addresses current bid
uint256 bids;
4,576,885
[ 1, 1986, 6138, 783, 9949, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 30534, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x2B8Da5Aa8B4FF47cC0D490bdc9a02BC02D630655/sources/UpkeepRegistryOwner.sol
@dev retrieves feed data for fast gas/eth and link/eth prices. if the feed data is stale it uses the configured fallback price. once a price is picked for gas it takes the min of gas price in the transaction or the fast gas price in order to reduce costs for the upkeep clients./
function getFeedData() private view returns ( int256 gasWei, int256 linkEth ) { uint32 stalenessSeconds = s_config.stalenessSeconds; bool staleFallback = stalenessSeconds > 0; uint256 timestamp; (,gasWei,,timestamp,) = FAST_GAS_FEED.latestRoundData(); if (staleFallback && stalenessSeconds < block.timestamp - timestamp) { gasWei = s_fallbackGasPrice; } (,linkEth,,timestamp,) = LINK_ETH_FEED.latestRoundData(); if (staleFallback && stalenessSeconds < block.timestamp - timestamp) { linkEth = s_fallbackLinkPrice; } return (gasWei, linkEth); }
3,370,089
[ 1, 14580, 3324, 4746, 501, 364, 4797, 16189, 19, 546, 471, 1692, 19, 546, 19827, 18, 309, 326, 4746, 501, 353, 14067, 518, 4692, 326, 4351, 5922, 6205, 18, 3647, 279, 6205, 353, 25534, 364, 16189, 518, 5530, 326, 1131, 434, 16189, 6205, 316, 326, 2492, 578, 326, 4797, 16189, 6205, 316, 1353, 358, 5459, 22793, 364, 326, 731, 10102, 7712, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 13683, 329, 751, 1435, 203, 565, 3238, 203, 565, 1476, 203, 565, 1135, 261, 203, 1377, 509, 5034, 16189, 3218, 77, 16, 203, 1377, 509, 5034, 1692, 41, 451, 203, 565, 262, 203, 225, 288, 203, 565, 2254, 1578, 384, 287, 15681, 6762, 273, 272, 67, 1425, 18, 334, 287, 15681, 6762, 31, 203, 565, 1426, 14067, 12355, 273, 384, 287, 15681, 6762, 405, 374, 31, 203, 565, 2254, 5034, 2858, 31, 203, 565, 261, 16, 31604, 3218, 77, 16408, 5508, 16, 13, 273, 24239, 67, 43, 3033, 67, 29195, 18, 13550, 11066, 751, 5621, 203, 565, 309, 261, 334, 5349, 12355, 597, 384, 287, 15681, 6762, 411, 1203, 18, 5508, 300, 2858, 13, 288, 203, 1377, 16189, 3218, 77, 273, 272, 67, 16471, 27998, 5147, 31, 203, 565, 289, 203, 565, 261, 16, 1232, 41, 451, 16408, 5508, 16, 13, 273, 22926, 67, 1584, 44, 67, 29195, 18, 13550, 11066, 751, 5621, 203, 565, 309, 261, 334, 5349, 12355, 597, 384, 287, 15681, 6762, 411, 1203, 18, 5508, 300, 2858, 13, 288, 203, 1377, 1692, 41, 451, 273, 272, 67, 16471, 2098, 5147, 31, 203, 565, 289, 203, 565, 327, 261, 31604, 3218, 77, 16, 1692, 41, 451, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Resolver to Wipe & Coll any CDP pragma solidity 0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "Assertion Failed"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "Assertion Failed"); uint256 c = a / b; return c; } } interface IERC20 { function balanceOf(address who) 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); } interface AddressRegistry { function getAddr(string name) external view returns(address); } interface MakerCDP { function join(uint wad) external; // Join PETH function lock(bytes32 cup, uint wad) external; function wipe(bytes32 cup, uint wad) external; function per() external view returns (uint ray); } interface PriceInterface { function peek() external view returns (bytes32, bool); } interface WETHFace { function deposit() external payable; function withdraw(uint wad) external; } interface InstaKyber { function executeTrade( address src, address dest, uint srcAmt, uint minConversionRate, uint maxDestAmt ) external payable returns (uint destAmt); function getExpectedPrice( address src, address dest, uint srcAmt ) external view returns (uint, uint); } contract Registry { address public addressRegistry; modifier onlyAdmin() { require( msg.sender == getAddress("admin"), "Permission Denied" ); _; } function getAddress(string name) internal view returns(address) { AddressRegistry addrReg = AddressRegistry(addressRegistry); return addrReg.getAddr(name); } } contract Helper is Registry { using SafeMath for uint; using SafeMath for uint256; address public cdpAddr; address public eth; address public weth; address public peth; address public mkr; address public dai; address public kyber; function pethPEReth(uint ethNum) public view returns (uint rPETH) { MakerCDP loanMaster = MakerCDP(cdpAddr); rPETH = (ethNum.mul(10 ** 27)).div(loanMaster.per()); } } contract Lock is Helper { event LockedETH(uint cdpNum, address lockedBy, uint lockETH, uint lockPETH); function lockETH(uint cdpNum) public payable { MakerCDP loanMaster = MakerCDP(cdpAddr); WETHFace wethTkn = WETHFace(weth); wethTkn.deposit.value(msg.value)(); // ETH to WETH uint pethToLock = pethPEReth(msg.value); loanMaster.join(pethToLock); // WETH to PETH loanMaster.lock(bytes32(cdpNum), pethToLock); // PETH to CDP emit LockedETH( cdpNum, msg.sender, msg.value, pethToLock ); } } contract Wipe is Lock { event WipedDAI(uint cdpNum, address wipedBy, uint daiWipe, uint mkrCharged); function wipeDAI(uint cdpNum, uint daiWipe) public payable { IERC20 daiTkn = IERC20(dai); IERC20 mkrTkn = IERC20(mkr); uint contractMKR = mkrTkn.balanceOf(address(this)); // contract MKR balance before wiping daiTkn.transferFrom(msg.sender, address(this), daiWipe); // get DAI to pay the debt MakerCDP loanMaster = MakerCDP(cdpAddr); loanMaster.wipe(bytes32(cdpNum), daiWipe); // wipe DAI uint mkrCharged = contractMKR - mkrTkn.balanceOf(address(this)); // MKR fee = before wiping bal - after wiping bal // claiming paid MKR back if (msg.value > 0) { // Interacting with Kyber to swap ETH with MKR swapETHMKR( mkrCharged, msg.value ); } else { // take MKR directly from address mkrTkn.transferFrom(msg.sender, address(this), mkrCharged); // user paying MKR fees } emit WipedDAI( cdpNum, msg.sender, daiWipe, mkrCharged ); } function swapETHMKR( uint mkrCharged, uint ethQty ) internal { InstaKyber instak = InstaKyber(kyber); uint minRate; (, minRate) = instak.getExpectedPrice(eth, mkr, ethQty); uint mkrBought = instak.executeTrade.value(ethQty)( eth, mkr, ethQty, minRate, mkrCharged ); require(mkrCharged == mkrBought, "ETH not sufficient to cover the MKR fees."); if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } } contract ApproveTkn is Wipe { function approveERC20() public { IERC20 wethTkn = IERC20(weth); wethTkn.approve(cdpAddr, 2**256 - 1); IERC20 pethTkn = IERC20(peth); pethTkn.approve(cdpAddr, 2**256 - 1); IERC20 mkrTkn = IERC20(mkr); mkrTkn.approve(cdpAddr, 2**256 - 1); IERC20 daiTkn = IERC20(dai); daiTkn.approve(cdpAddr, 2**256 - 1); } } contract PublicCDP is ApproveTkn { event MKRCollected(uint amount); constructor(address rAddr) public { addressRegistry = rAddr; cdpAddr = getAddress("cdp"); eth = getAddress("eth"); weth = getAddress("weth"); peth = getAddress("peth"); mkr = getAddress("mkr"); dai = getAddress("dai"); kyber = getAddress("InstaKyber"); approveERC20(); } function () public payable {} // collecting MKR token kept as balance to pay fees function collectMKR(uint amount) public onlyAdmin { IERC20 mkrTkn = IERC20(mkr); mkrTkn.transfer(msg.sender, amount); emit MKRCollected(amount); } }
collecting MKR token kept as balance to pay fees
function collectMKR(uint amount) public onlyAdmin { IERC20 mkrTkn = IERC20(mkr); mkrTkn.transfer(msg.sender, amount); emit MKRCollected(amount); }
15,283,560
[ 1, 14676, 310, 490, 47, 54, 1147, 16555, 487, 11013, 358, 8843, 1656, 281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3274, 49, 47, 54, 12, 11890, 3844, 13, 1071, 1338, 4446, 288, 203, 3639, 467, 654, 39, 3462, 5028, 86, 56, 21112, 273, 467, 654, 39, 3462, 12, 24816, 86, 1769, 203, 3639, 5028, 86, 56, 21112, 18, 13866, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 3639, 3626, 490, 47, 54, 10808, 329, 12, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/10/0x391a45F31c1837E3d837c23e05F42A098329D50d/sources/contracts/utils/proxy/solidity-0.8.0/ProxyReentrancyGuard.sol
* @dev Contract module that helps prevent reentrant calls to a function. Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier available, which can be aplied to functions to make sure there are no nested (reentrant) calls to them. Note that because there is a single `nonReentrant` guard, functions marked as `nonReentrant` may not call one another. This can be worked around by making those functions `private`, and then adding `external` `nonReentrant` entry points to them./
contract ProxyReentrancyGuard { uint256 private _guardCounter; bool private _initialized; pragma solidity ^0.8.0; function initNonReentrant() public { require(!_initialized, "Already initialized"); _initialized = true; _guardCounter = 1; } modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } }
3,778,344
[ 1, 8924, 1605, 716, 21814, 5309, 283, 8230, 970, 4097, 358, 279, 445, 18, 25953, 310, 628, 1375, 426, 8230, 12514, 16709, 68, 903, 1221, 326, 1375, 5836, 426, 8230, 970, 68, 9606, 2319, 16, 1492, 848, 506, 279, 3110, 358, 4186, 358, 1221, 3071, 1915, 854, 1158, 4764, 261, 2842, 313, 970, 13, 4097, 358, 2182, 18, 3609, 716, 2724, 1915, 353, 279, 2202, 1375, 5836, 426, 8230, 970, 68, 11026, 16, 4186, 9350, 487, 1375, 5836, 426, 8230, 970, 68, 2026, 486, 745, 1245, 4042, 18, 1220, 848, 506, 28613, 6740, 635, 10480, 5348, 4186, 1375, 1152, 9191, 471, 1508, 6534, 1375, 9375, 68, 1375, 5836, 426, 8230, 970, 68, 1241, 3143, 358, 2182, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7659, 426, 8230, 12514, 16709, 288, 203, 565, 2254, 5034, 3238, 389, 24594, 4789, 31, 203, 565, 1426, 3238, 389, 13227, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 445, 1208, 3989, 426, 8230, 970, 1435, 1071, 288, 203, 3639, 2583, 12, 5, 67, 13227, 16, 315, 9430, 6454, 8863, 203, 3639, 389, 13227, 273, 638, 31, 203, 3639, 389, 24594, 4789, 273, 404, 31, 203, 565, 289, 203, 203, 565, 9606, 1661, 426, 8230, 970, 1435, 288, 203, 3639, 389, 24594, 4789, 1011, 404, 31, 203, 3639, 2254, 5034, 1191, 4789, 273, 389, 24594, 4789, 31, 203, 3639, 389, 31, 203, 3639, 2583, 12, 3729, 4789, 422, 389, 24594, 4789, 16, 315, 426, 8230, 12514, 16709, 30, 283, 8230, 970, 745, 8863, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT /** MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMWWWWWWWWWWWWWWWMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMWWNXXKKKKKKKXXXXKKKKKKXXNWWMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMWNXKKKKXXNWWWWMMWWWWMWWWWNXXXKKKXNWMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMWNXKKKXNWMMMMMMMMMNOdxKWMMMMMMMMWNXKKKXNWMMMMMMMMMMMMMM MMMMMMMMMMMMMWXKKKNWMMMMMMMMMMMMNx:;;l0WMMMMMMMMMMMWNK0KXWMMMMMMMMMMMM MMMMMMMMMMMWXKKXWMMMMMMMMMMMMMMXd:;;;;cOWMMMMMMMMMMMMMWXKKXWMMMMMMMMMM MMMMMMMMMWNKKXWMMMMMMMMMMMMMMWKo;;col:;:kNMMMMMMMMMMMMMMWX0KNWMMMMMMMM MMMMMMMMWX0XWMMMMMMMMMMMMMMMWOl;;oKWXkc;:dXMMMMMMMMMMMMMMMWX0XWMMMMMMM MMMMMMMNKKNWMMMMMMMMMMMMMMMNkc;:dXMMMWOc;;oKWMMMMMMMMMMMMMMWNKKNMMMMMM MMMMMMNKKNMMMMMMMMMMMMMMMMNx:;:xNMMMMMW0l;;l0WMMMMMMMWMMMMMMMNKKNMMMMM MMMMMNKKNMMMMMMMMMMMMMMMMXd:;ckNMMMMMMMMKo:;cOWMMMMXkxkXWMMMMMNKKNMMMM MMMMWK0NMMMMMMMMMMMMMMMWKo;;l0WMMMMMMMMMMXx:;:xNMMW0lccxXMMMMMMN0KWMMM MMMMX0XWMMMMMMWWMMMMMMWOl;;oKWMMMMMMMMMMMMNkc;:dXMMNklcoKMMMMMMMX0XMMM MMMWKKNMMWK0OkkkkkkKWNkc;:dXMMMMMMMMMMMMMMMWOl;;oKWMXdcxNMMMMMMMNKKWMM MMMN0XWMMWNXX0OdlccdKOc;:xNMMMWXKKXNWNNNNWWMW0o;;l0WNkdKWMMMMMMMWX0NMM MMMX0XMMMMMMMMMN0dlcdOxoONMMMMW0xdddddodxk0KNWXd:;l0Kx0WMMMMMMMMMX0XMM MMMX0NMMMMMMMMMMWXxlcoOXWMMMMWKkolclodkKNNNNWWMNxcxOkKWMMMMMMMMMMX0XMM MMMX0XMMMMMMMMMMMMNklclkNMMWXklccodxdodKWMMMMMMMNKOkKWMMMMMMMMMMMX0XMM MMMN0XWMMMMMMMMMMMMNOoclxXN0occcdKX0xlco0WMMMMMMNOOXMMMMMMMMMMMMMX0NMM MMMWKKWMMMMMMMMMMMMMW0dccoxocccdKWMWNklclONMMMMXOONMMMMMMMMMMMMMWKKWMM MMMMX0XMMMMMMMMMMMMMMWKdcccccco0WMMMMNOoclkNWWKk0NMMMMMMMMMMMMMMX0XWMM MMMMWKKNMMMMMMMMMMMMMMMXxlcccckNMMMMMMW0oclxK0kKWMMMMMMMMMMMMMMNKKWMMM MMMMMN0KWMMMMMMMMMMMMMMMNklccoKWMMMMMMMWKdlcoxKWMMMMMMMMMMMMMMWK0NMMMM MMMMMMN0KWMMMMMMMMMMMMMMMNOod0KXWMMMMMMNK0xoxXWMMMMMMMMMMMMMMWK0NMMMMM MMMMMMMN0KNMMMMMMMMMMMMMMMWXKkll0WMMMMXdcoOKNMMMMMMMMMMMMMMMNK0NMMMMMM MMMMMMMMNK0XWMMMMMMMMMMMMMMMNd:;cOWMWKo:;c0WMMMMMMMMMMMMMMWX0KNMMMMMMM MMMMMMMMMWXKKNWMMMMMMMMMMMMMMXd:;cx0kl;;l0WMMMMMMMMMMMMMWNKKXWMMMMMMMM MMMMMMMMMMMWX0KNWMMMMMMMMMMMMMNkc;;::;:oKWMMMMMMMMMMMMWNK0XWMMMMMMMMMM MMMMMMMMMMMMMNXKKXNWMMMMMMMMMMMWOc;;;:dXMMMMMMMMMMMWNXKKXWMMMMMMMMMMMM MMMMMMMMMMMMMMMWNKKKXNWMMMMMMMMMW0l:ckNMMMMMMMMMWNXKKKNWMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMWNXKKKXXNWWWMMMMX0KWMMMWWWNXXKKKXNWMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMWWNXXKKKKKXXXXXXXXXXKKKKXXNWWMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMWWNNNNNNNNNNNNWWWMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM ---------------------- [ WPSmartContracts.com ] ---------------------- [ Blockchain Made Easy ] | | ERC-721 NFT Token Marketplace | |---------------------------- | | Flavors | | > Suika v.2: Standard ERC-721 Token with Marketplace | Supports Payment with Tokens, and royalties | */ pragma solidity ^0.8.2; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @title ERC-721 Non-Fungible Token Standard, optional 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); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @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); } /** * @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(); } } /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(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), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @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 override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } /** * @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; } /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @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) external view returns (address); /** * @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) external view returns (uint256); } /** * @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 override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } /** * @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; } } /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } } /** * @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; } } contract ERC721Mochi is ERC721, ERC721Enumerable, ERC721URIStorage, AccessControlEnumerable, ERC721Burnable { using Counters for Counters.Counter; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); Counters.Counter private _tokenIdCounter; bool public anyoneCanMint; constructor(address owner, string memory name, string memory symbol, bool _anyoneCanMint) ERC721(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, owner); _setupRole(MINTER_ROLE, owner); anyoneCanMint = _anyoneCanMint; } function autoMint(string memory _tokenURI, address to) public onlyMinter { uint id; do { _tokenIdCounter.increment(); id = _tokenIdCounter.current(); } while(_exists(id)); _mint(to, id); _setTokenURI(id, _tokenURI); } function mint(address to, uint256 tokenId) public onlyMinter { _mint(to, tokenId); } function safeMint(address to, uint256 tokenId) public onlyMinter { _safeMint(to, tokenId); } function isMinter(address account) public view returns (bool) { return hasRole(MINTER_ROLE, account); } function safeMint(address to, uint256 tokenId, bytes memory _data) public onlyMinter { _safeMint(to, tokenId, _data); } function _burn(uint256 tokenId) internal virtual override(ERC721, ERC721URIStorage) { ERC721URIStorage._burn(tokenId); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable, AccessControlEnumerable) returns (bool) { return super.supportsInterface(interfaceId); } function addMinter(address account) public onlyRole(MINTER_ROLE) { grantRole(MINTER_ROLE, account); } function canIMint() public view returns (bool) { return anyoneCanMint || isMinter(msg.sender); } /** * Open modifier to anyone can mint possibility */ modifier onlyMinter() { string memory mensaje; require( canIMint(), "MinterRole: caller does not have the Minter role" ); _; } } /** * @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; } } // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } contract EIP20 { uint256 public totalSupply; uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; /* 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. string public symbol; //An identifier: eg SBX event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); constructor( uint256 _initialAmount, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol ) { 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 } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 _allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && _allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (_allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view 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); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title ERC721Suika * ERC-721 Marketplace with tokens and royalties support */ contract ERC721Suika is ERC721Mochi, ReentrancyGuard { using SafeMath for uint256; using Address for address payable; using Address for address; // admin address, the owner of the marketplace address payable admin; address public contract_owner; // ERC20 token to be used for payments EIP20 public payment_token; // commission rate is a value from 0 to 100 uint256 commissionRate; // royalties commission rate is a value from 0 to 100 uint256 royaltiesCommissionRate; // nft item creators list, used to pay royalties mapping(uint256 => address) public creators; // last price sold or auctioned mapping(uint256 => uint256) public soldFor; // Mapping from token ID to sell price in Ether or to bid price, depending if it is an auction or not mapping(uint256 => uint256) public sellBidPrice; // Mapping payment address for tokenId mapping(uint256 => address payable) private _wallets; event Sale(uint256 indexed tokenId, address indexed from, address indexed to, uint256 value); event Commission(uint256 indexed tokenId, address indexed to, uint256 value, uint256 rate, uint256 total); event Royalty(uint256 indexed tokenId, address indexed to, uint256 value, uint256 rate, uint256 total); // Auction data struct Auction { // Parameters of the auction. Times are either // absolute unix timestamps (seconds since 1970-01-01) // or time periods in seconds. address payable beneficiary; uint auctionEnd; // Current state of the auction. address payable highestBidder; uint highestBid; // Set to true at the end, disallows any change bool open; // minimum reserve price in wei uint256 reserve; } // mapping auctions for each tokenId mapping(uint256 => Auction) public auctions; // Events that will be fired on changes. event Refund(address bidder, uint amount); event HighestBidIncreased(address indexed bidder, uint amount, uint256 tokenId); event AuctionEnded(address winner, uint amount); event LimitSell(address indexed from, address indexed to, uint256 amount); event LimitBuy(address indexed from, address indexed to, uint256 amount); event MarketSell(address indexed from, address indexed to, uint256 amount); event MarketBuy(address indexed from, address indexed to, uint256 amount); constructor( EIP20 _payment_token, address _owner, address payable _admin, uint256 _commissionRate, uint256 _royaltiesCommissionRate, string memory name, string memory symbol, bool _anyoneCanMint) ERC721Mochi(_owner, name, symbol, _anyoneCanMint) { admin = _admin; contract_owner = _owner; require(_commissionRate<=100, "ERC721Suika: Commission rate has to be between 0 and 100"); commissionRate = _commissionRate; royaltiesCommissionRate = _royaltiesCommissionRate; payment_token = _payment_token; } function canSell(uint256 tokenId) public view returns (bool) { return (ownerOf(tokenId)==msg.sender && !auctions[tokenId].open); } // Sell option for a fixed price function sell(uint256 tokenId, uint256 price, address payable wallet) public { // onlyOwner require(ownerOf(tokenId)==msg.sender, "ERC721Suika: Only owner can sell this item"); // cannot set a price if auction is activated require(!auctions[tokenId].open, "ERC721Suika: Cannot sell an item which has an active auction"); // set sell price for index sellBidPrice[tokenId] = price; // If price is zero, means not for sale if (price>0) { // approve the Index to the current contract approve(address(this), tokenId); // set wallet payment _wallets[tokenId] = wallet; } } // simple function to return the price of a tokenId // returns: sell price, bid price, sold price, only one can be non zero function getPrice(uint256 tokenId) public view returns (uint256, uint256, uint256) { if (sellBidPrice[tokenId]>0) return (sellBidPrice[tokenId], 0, 0); if (auctions[tokenId].highestBid>0) return (0, auctions[tokenId].highestBid, 0); return (0, 0, soldFor[tokenId]); } function canBuy(uint256 tokenId) public view returns (uint256) { if (!auctions[tokenId].open && sellBidPrice[tokenId]>0 && sellBidPrice[tokenId]>0 && getApproved(tokenId) == address(this)) { return sellBidPrice[tokenId]; } else { return 0; } } // Buy option function buy(uint256 tokenId) public nonReentrant { // is on sale require(!auctions[tokenId].open && sellBidPrice[tokenId]>0, "ERC721Suika: The collectible is not for sale"); // transfer ownership address owner = ownerOf(tokenId); require(msg.sender!=owner, "ERC721Suika: The seller cannot buy his own collectible"); // we need to call a transferFrom from this contract, which is the one with permission to sell the NFT callOptionalReturn(this, abi.encodeWithSelector(this.transferFrom.selector, owner, msg.sender, tokenId)); // calculate amounts uint256 amount4admin = sellBidPrice[tokenId].mul(commissionRate).div(100); uint256 amount4creator = sellBidPrice[tokenId].mul(royaltiesCommissionRate).div(100); uint256 amount4owner = sellBidPrice[tokenId].sub(amount4admin).sub(amount4creator); // to owner require(payment_token.transferFrom(msg.sender, _wallets[tokenId], amount4owner), "Transfer failed."); // to creator if (amount4creator>0) { require(payment_token.transferFrom(msg.sender, creators[tokenId], amount4creator), "Transfer failed."); } // to admin if (amount4admin>0) { require(payment_token.transferFrom(msg.sender, admin, amount4admin), "Transfer failed."); } emit Sale(tokenId, owner, msg.sender, sellBidPrice[tokenId]); emit Commission(tokenId, owner, sellBidPrice[tokenId], commissionRate, amount4admin); emit Royalty(tokenId, owner, sellBidPrice[tokenId], royaltiesCommissionRate, amount4creator); soldFor[tokenId] = sellBidPrice[tokenId]; // close the sell sellBidPrice[tokenId] = 0; delete _wallets[tokenId]; } function canAuction(uint256 tokenId) public view returns (bool) { return (ownerOf(tokenId)==msg.sender && !auctions[tokenId].open && sellBidPrice[tokenId]==0); } // Instantiate an auction contract for a tokenId function createAuction(uint256 tokenId, uint _closingTime, address payable _beneficiary, uint256 _reservePrice) public { require(sellBidPrice[tokenId]==0, "ERC721Suika: The selected NFT is open for sale, cannot be auctioned"); require(!auctions[tokenId].open, "ERC721Suika: The selected NFT already has an auction"); require(ownerOf(tokenId)==msg.sender, "ERC721Suika: Only owner can auction this item"); auctions[tokenId].beneficiary = _beneficiary; auctions[tokenId].auctionEnd = _closingTime; auctions[tokenId].reserve = _reservePrice; auctions[tokenId].open = true; // approve the Index to the current contract approve(address(this), tokenId); } function canBid(uint256 tokenId) public view returns (bool) { if (!msg.sender.isContract() && auctions[tokenId].open && block.timestamp <= auctions[tokenId].auctionEnd && msg.sender != ownerOf(tokenId) && getApproved(tokenId) == address(this) ) { return true; } else { return false; } } /// Overrides minting function to keep track of item creators function _mint(address to, uint256 tokenId) override internal { creators[tokenId] = msg.sender; super._mint(to, tokenId); } /// Bid on the auction with the value sent /// together with this transaction. /// The value will only be refunded if the /// auction is not won. function bid(uint256 tokenId, uint256 bid_value) public nonReentrant { // Contracts cannot bid, because they can block the auction with a reentrant attack require(!msg.sender.isContract(), "No script kiddies"); // auction has to be opened require(auctions[tokenId].open, "No opened auction found"); // approve was lost require(getApproved(tokenId) == address(this), "Cannot complete the auction"); // Revert the call if the bidding // period is over. require( block.timestamp <= auctions[tokenId].auctionEnd, "Auction already ended." ); // If the bid is not higher, send the // money back. require( bid_value > auctions[tokenId].highestBid, "There already is a higher bid." ); address owner = ownerOf(tokenId); require(msg.sender!=owner, "ERC721Suika: The owner cannot bid his own collectible"); // return the funds to the previous bidder, if there is one if (auctions[tokenId].highestBid>0) { require(payment_token.transfer(auctions[tokenId].highestBidder, auctions[tokenId].highestBid), "Transfer failed."); emit Refund(auctions[tokenId].highestBidder, auctions[tokenId].highestBid); } // now store the bid data auctions[tokenId].highestBidder = payable(msg.sender); // transfer tokens to contract require(payment_token.transferFrom(msg.sender, address(this), bid_value), "Transfer failed."); // register the highest bid value auctions[tokenId].highestBid = bid_value; emit HighestBidIncreased(msg.sender, bid_value, tokenId); } // anyone can execute withdraw if auction is opened and // the bid time expired and the reserve was not met // or // the auction is openen but the contract is unable to transfer function canWithdraw(uint256 tokenId) public view returns (bool) { if (auctions[tokenId].open && ( ( block.timestamp >= auctions[tokenId].auctionEnd && auctions[tokenId].highestBid > 0 && auctions[tokenId].highestBid<auctions[tokenId].reserve ) || getApproved(tokenId) != address(this) ) ) { return true; } else { return false; } } /// Withdraw a bid when the auction is not finalized function withdraw(uint256 tokenId) public nonReentrant { require(canWithdraw(tokenId), "Conditions to withdraw are not met"); // transfer funds to highest bidder always if (auctions[tokenId].highestBid > 0) { require(payment_token.transfer(auctions[tokenId].highestBidder, auctions[tokenId].highestBid), "Transfer failed."); } // finalize the auction delete auctions[tokenId]; } function canFinalize(uint256 tokenId) public view returns (bool) { if (auctions[tokenId].open && block.timestamp >= auctions[tokenId].auctionEnd && ( auctions[tokenId].highestBid>=auctions[tokenId].reserve || auctions[tokenId].highestBid==0 ) ) { return true; } else { return false; } } // implement the auctionFinalize including the NFT transfer logic function auctionFinalize(uint256 tokenId) public nonReentrant { require(canFinalize(tokenId), "Cannot finalize"); if (auctions[tokenId].highestBid>0) { // transfer the ownership of token to the highest bidder address payable _highestBidder = auctions[tokenId].highestBidder; // calculate payment amounts uint256 amount4admin = auctions[tokenId].highestBid.mul(commissionRate).div(100); uint256 amount4creator = auctions[tokenId].highestBid.mul(royaltiesCommissionRate).div(100); uint256 amount4owner = auctions[tokenId].highestBid.sub(amount4admin).sub(amount4creator); // to owner require(payment_token.transfer(auctions[tokenId].beneficiary, amount4owner), "Transfer failed."); // to creator if (amount4creator>0) { require(payment_token.transfer(creators[tokenId], amount4creator), "Transfer failed."); } // to admin if (amount4admin>0) { require(payment_token.transfer(admin, amount4admin), "Transfer failed."); } emit Sale(tokenId, auctions[tokenId].beneficiary, _highestBidder, auctions[tokenId].highestBid); emit Royalty(tokenId, auctions[tokenId].beneficiary, auctions[tokenId].highestBid, royaltiesCommissionRate, amount4creator); emit Commission(tokenId, auctions[tokenId].beneficiary, auctions[tokenId].highestBid, commissionRate, amount4admin); // transfer ownership address owner = ownerOf(tokenId); // we need to call a transferFrom from this contract, which is the one with permission to sell the NFT // transfer the NFT to the auction's highest bidder callOptionalReturn(this, abi.encodeWithSelector(this.transferFrom.selector, owner, _highestBidder, tokenId)); soldFor[tokenId] = auctions[tokenId].highestBid; } emit AuctionEnded(auctions[tokenId].highestBidder, auctions[tokenId].highestBid); // finalize the auction delete auctions[tokenId]; } // Bid query functions function highestBidder(uint256 tokenId) public view returns (address payable) { return auctions[tokenId].highestBidder; } function highestBid(uint256 tokenId) public view returns (uint256) { return auctions[tokenId].highestBid; } /** * @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(IERC721 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(), "SafeERC721: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC721: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC721: ERC20 operation did not succeed"); } } // update contract fields function updateAdmin(address payable _admin, uint256 _commissionRate, uint256 _royaltiesCommissionRate, bool _anyoneCanMint, EIP20 _payment_token) public { require(msg.sender==contract_owner, "Only contract owner can do this"); admin = _admin; commissionRate = _commissionRate; royaltiesCommissionRate = _royaltiesCommissionRate; anyoneCanMint = _anyoneCanMint; payment_token = _payment_token; } // update owner function updateOwner(address _contract_owner) public { require(msg.sender==contract_owner, "Only contract owner can do this"); // grant roles to new owner _setupRole(DEFAULT_ADMIN_ROLE, _contract_owner); _setupRole(MINTER_ROLE, _contract_owner); // revoke roles of old owner revokeRole(MINTER_ROLE, contract_owner); _setupRole(DEFAULT_ADMIN_ROLE, contract_owner); // change ownership contract_owner = _contract_owner; } }
update contract fields
function updateAdmin(address payable _admin, uint256 _commissionRate, uint256 _royaltiesCommissionRate, bool _anyoneCanMint, EIP20 _payment_token) public { require(msg.sender==contract_owner, "Only contract owner can do this"); admin = _admin; commissionRate = _commissionRate; royaltiesCommissionRate = _royaltiesCommissionRate; anyoneCanMint = _anyoneCanMint; payment_token = _payment_token; }
1,140,441
[ 1, 2725, 6835, 1466, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 4446, 12, 2867, 8843, 429, 389, 3666, 16, 2254, 5034, 389, 832, 3951, 4727, 16, 2254, 5034, 389, 3800, 2390, 606, 799, 3951, 4727, 16, 1426, 389, 2273, 476, 2568, 49, 474, 16, 512, 2579, 3462, 389, 9261, 67, 2316, 13, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 631, 16351, 67, 8443, 16, 315, 3386, 6835, 3410, 848, 741, 333, 8863, 203, 3639, 3981, 273, 389, 3666, 31, 203, 3639, 1543, 19710, 4727, 273, 389, 832, 3951, 4727, 31, 203, 3639, 721, 93, 2390, 606, 799, 3951, 4727, 273, 389, 3800, 2390, 606, 799, 3951, 4727, 31, 203, 3639, 1281, 476, 2568, 49, 474, 273, 389, 2273, 476, 2568, 49, 474, 31, 203, 3639, 5184, 67, 2316, 273, 389, 9261, 67, 2316, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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); } } // SPDX-License-Identifier: GPL-3.0 // Docgen-SOLC: 0.8.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "../../utils/ContractRegistryAccess.sol"; import "../../utils/ACLAuth.sol"; import "../../utils/KeeperIncentivized.sol"; import "../../../externals/interfaces/YearnVault.sol"; import "../../../externals/interfaces/BasicIssuanceModule.sol"; import "../../../externals/interfaces/ISetToken.sol"; import "../../../externals/interfaces/CurveContracts.sol"; import "../../interfaces/IStaking.sol"; import "../../interfaces/IKeeperIncentive.sol"; /* * @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own, * which not only takes long but mainly costs enormous amounts of gas. * The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken. * This means multiple approvals and deposits are necessary to mint one Butter. * We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly. */ contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess { using SafeERC20 for YearnVault; using SafeERC20 for ISetToken; using SafeERC20 for IERC20; /** * @notice Defines if the Batch will mint or redeem Butter */ enum BatchType { Mint, Redeem } /** * @notice Defines if the Batch will mint or redeem Butter * @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV * @param crvLPToken The LP-Token of the CurveMetapool */ struct CurvePoolTokenPair { CurveMetapool curveMetaPool; IERC20 crvLPToken; } struct ProcessingThreshold { uint256 batchCooldown; uint256 mintThreshold; uint256 redeemThreshold; } struct RedemptionFee { uint256 accumulated; uint256 rate; address recipient; } struct Slippage { uint256 mintBps; // in bps uint256 redeemBps; // in bps } /** * @notice The Batch structure is used both for Batches of Minting and Redeeming * @param batchType Determines if this Batch is for Minting or Redeeming Butter * @param batchId bytes32 id of the batch * @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable * @param unclaimedShares The total amount of unclaimed shares in this batch * @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter) * @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter) * @param tokenAddress The address of the the token to be claimed * @param shareBalance The individual share balance per user that has deposited token */ struct Batch { BatchType batchType; bytes32 batchId; bool claimable; uint256 unclaimedShares; uint256 suppliedTokenBalance; uint256 claimableTokenBalance; address suppliedTokenAddress; address claimableTokenAddress; } /* ========== STATE VARIABLES ========== */ bytes32 public immutable contractName = "ButterBatchProcessing"; IStaking public staking; ISetToken public setToken; IERC20 public threeCrv; CurveMetapool public threePool; BasicIssuanceModule public setBasicIssuanceModule; mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs; /** * @notice This maps batch ids to addresses with share balances */ mapping(bytes32 => mapping(address => uint256)) public accountBalances; mapping(address => bytes32[]) public accountBatches; mapping(bytes32 => Batch) public batches; bytes32[] public batchIds; uint256 public lastMintedAt; uint256 public lastRedeemedAt; bytes32 public currentMintBatchId; bytes32 public currentRedeemBatchId; Slippage public slippage; ProcessingThreshold public processingThreshold; RedemptionFee public redemptionFee; mapping(address => bool) public sweethearts; /* ========== EVENTS ========== */ event Deposit(address indexed from, uint256 deposit); event Withdrawal(address indexed to, uint256 amount); event SlippageUpdated(Slippage prev, Slippage current); event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount); event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount); event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken); event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to); event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account); event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs); event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold); event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient); event SweetheartUpdated(address sweetheart, bool isSweeheart); event StakingUpdated(address beforeAddress, address afterAddress); /* ========== CONSTRUCTOR ========== */ constructor( IContractRegistry _contractRegistry, IStaking _staking, ISetToken _setToken, IERC20 _threeCrv, CurveMetapool _threePool, BasicIssuanceModule _basicIssuanceModule, address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs, ProcessingThreshold memory _processingThreshold ) ContractRegistryAccess(_contractRegistry) { staking = _staking; setToken = _setToken; threeCrv = _threeCrv; threePool = _threePool; setBasicIssuanceModule = _basicIssuanceModule; _setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs); processingThreshold = _processingThreshold; lastMintedAt = block.timestamp; lastRedeemedAt = block.timestamp; _generateNextBatch(bytes32("mint"), BatchType.Mint); _generateNextBatch(bytes32("redeem"), BatchType.Redeem); slippage.mintBps = 7; slippage.redeemBps = 7; } /* ========== VIEWS ========== */ /** * @notice Get ids for all batches that a user has interacted with * @param _account The address for whom we want to retrieve batches */ function getAccountBatches(address _account) external view returns (bytes32[] memory) { return accountBatches[_account]; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Deposits funds in the current mint batch * @param _amount Amount of 3cr3CRV to use for minting * @param _depositFor User that gets the shares attributed to (for use in zapper contract) */ function depositForMint(uint256 _amount, address _depositFor) external nonReentrant whenNotPaused onlyApprovedContractOrEOA { require( _hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor, "you cant transfer other funds" ); require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance"); threeCrv.transferFrom(msg.sender, address(this), _amount); _deposit(_amount, currentMintBatchId, _depositFor); } /** * @notice deposits funds in the current redeem batch * @param _amount amount of Butter to be redeemed */ function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA { require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance"); setToken.transferFrom(msg.sender, address(this), _amount); _deposit(_amount, currentRedeemBatchId, msg.sender); } /** * @notice This function allows a user to withdraw their funds from a batch before that batch has been processed * @param _batchId From which batch should funds be withdrawn from * @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch) * @param _withdrawFor User that gets the shares attributed to (for use in zapper contract) */ function withdrawFromBatch( bytes32 _batchId, uint256 _amountToWithdraw, address _withdrawFor ) external { address recipient = _getRecipient(_withdrawFor); Batch storage batch = batches[_batchId]; uint256 accountBalance = accountBalances[_batchId][_withdrawFor]; require(batch.claimable == false, "already processed"); require(accountBalance >= _amountToWithdraw, "account has insufficient funds"); //At this point the account balance is equal to the supplied token and can be used interchangeably accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw; batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw; batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw; if (batch.batchType == BatchType.Mint) { threeCrv.safeTransfer(recipient, _amountToWithdraw); } else { setToken.safeTransfer(recipient, _amountToWithdraw); } emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor); } /** * @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch) * @param _batchId Id of batch to claim from * @param _claimFor User that gets the shares attributed to (for use in zapper contract) */ function claim(bytes32 _batchId, address _claimFor) external returns (uint256) { (address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim( _batchId, _claimFor ); //Transfer token if (batchType == BatchType.Mint) { setToken.safeTransfer(recipient, tokenAmountToClaim); } else { //We only want to apply a fee on redemption of Butter //Sweethearts are partner addresses that we want to exclude from this fee if (!sweethearts[_claimFor]) { //Fee is deducted from threeCrv -- This allows it to work with the Zapper //Fes are denominated in BasisPoints uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000; redemptionFee.accumulated += fee; tokenAmountToClaim = tokenAmountToClaim - fee; } threeCrv.safeTransfer(recipient, tokenAmountToClaim); } emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim); return tokenAmountToClaim; } /** * @notice Claims BTR after batch has been processed and stakes it in Staking.sol * @param _batchId Id of batch to claim from * @param _claimFor User that gets the shares attributed to (for use in zapper contract) */ function claimAndStake(bytes32 _batchId, address _claimFor) external { (address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim( _batchId, _claimFor ); emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim); //Transfer token require(batchType == BatchType.Mint, "Can only stake BTR"); staking.stakeFor(tokenAmountToClaim, recipient); } /** * @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin. * @param _batchIds the ids of each batch where butter should be moved from * @param _shares how many shares should redeemed in each of the batches * @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter) * @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend) */ function moveUnclaimedDepositsIntoCurrentBatch( bytes32[] calldata _batchIds, uint256[] calldata _shares, BatchType _batchType ) external whenNotPaused { require(_batchIds.length == _shares.length, "array lengths must match"); uint256 totalAmount; for (uint256 i; i < _batchIds.length; i++) { Batch storage batch = batches[_batchIds[i]]; uint256 accountBalance = accountBalances[batch.batchId][msg.sender]; //Check that the user has enough funds and that the batch was already minted //Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance //Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch require(batch.claimable == true, "has not yet been processed"); require(batch.batchType == _batchType, "incorrect batchType"); require(accountBalance >= _shares[i], "account has insufficient funds"); uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares; batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim; batch.unclaimedShares = batch.unclaimedShares - _shares[i]; accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i]; totalAmount = totalAmount + tokenAmountToClaim; } require(totalAmount > 0, "totalAmount must be larger 0"); if (BatchType.Mint == _batchType) { _deposit(totalAmount, currentRedeemBatchId, msg.sender); } if (BatchType.Redeem == _batchType) { _deposit(totalAmount, currentMintBatchId, msg.sender); } emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender); } /** * @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter * @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter * @dev This process leaves some leftovers which are partially used in the next mint batches. * @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool * @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol) */ function batchMint() external whenNotPaused keeperIncentive(contractName, 0) { Batch storage batch = batches[currentMintBatchId]; //Check if there was enough time between the last batch minting and this attempt... //...or if enough 3CRV was deposited to make the minting worthwhile //This is to prevent excessive gas consumption and costs as we will pay keeper to call this function require( ((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown || (batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0, "can not execute batch mint yet" ); //Check if the Batch got already processed -- should technically not be possible require(batch.claimable == false, "already minted"); //Check if this contract has enough 3CRV -- should technically not be necessary require( threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance, "account has insufficient balance of token to mint" ); //Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token) (address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule .getRequiredComponentUnitsForIssue(setToken, 1e18); //The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`) uint256 setValue = valueOfComponents(tokenAddresses, quantities); uint256 threeCrvValue = threePool.get_virtual_price(); //Remaining amount of 3CRV in this batch which hasnt been allocated yet uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18; //Temporary allocation of 3CRV to be deployed in curveMetapools uint256[] memory poolAllocations = new uint256[](quantities.length); //Ratio of 3CRV needed to mint 1 BTR uint256[] memory ratios = new uint256[](quantities.length); for (uint256 i; i < tokenAddresses.length; i++) { // prettier-ignore (uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue); poolAllocations[i] = allocation; ratios[i] = ratio; remainingBatchBalanceValue -= allocation; } for (uint256 i; i < tokenAddresses.length; i++) { uint256 poolAllocation; //RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches //since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers if (remainingBatchBalanceValue > 0) { poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]); } //Pool 3CRV to get crvLPToken _sendToCurve( ((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool ); //Deposit crvLPToken to get yToken _sendToYearn( curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)), YearnVault(tokenAddresses[i]) ); //Approve yToken for minting YearnVault(tokenAddresses[i]).safeIncreaseAllowance( address(setBasicIssuanceModule), YearnVault(tokenAddresses[i]).balanceOf(address(this)) ); } //Get the minimum amount of butter that we can mint with our balances of yToken uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0]; for (uint256 i = 1; i < tokenAddresses.length; i++) { butterAmount = Math.min( butterAmount, (YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i] ); } require( butterAmount >= getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps), "slippage too high" ); //Mint Butter setBasicIssuanceModule.issue(setToken, butterAmount, address(this)); //Save the minted amount Butter as claimable token for the batch batch.claimableTokenBalance = butterAmount; //Set claimable to true so users can claim their Butter batch.claimable = true; //Update lastMintedAt for cooldown calculations lastMintedAt = block.timestamp; emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount); //Create the next mint batch _generateNextBatch(currentMintBatchId, BatchType.Mint); } /** * @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV * @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV * @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool * @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol) */ function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) { Batch storage batch = batches[currentRedeemBatchId]; //Check if there was enough time between the last batch redemption and this attempt... //...or if enough Butter was deposited to make the redemption worthwhile //This is to prevent excessive gas consumption and costs as we will pay keeper to call this function require( ((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) || (batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0, "can not execute batch redeem yet" ); //Check if the Batch got already processed require(batch.claimable == false, "already redeemed"); //Get tokenAddresses for mapping of underlying (address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule .getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance); //Allow setBasicIssuanceModule to use Butter _setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance); //Redeem Butter for yToken setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this)); //Check our balance of 3CRV since we could have some still around from previous batches uint256 oldBalance = threeCrv.balanceOf(address(this)); for (uint256 i; i < tokenAddresses.length; i++) { //Deposit yToken to receive crvLPToken _withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i])); uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)); //Deposit crvLPToken to receive 3CRV _withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool); } //Save the redeemed amount of 3CRV as claimable token for the batch batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance; require( batch.claimableTokenBalance >= getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps), "slippage too high" ); emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance); //Set claimable to true so users can claim their Butter batch.claimable = true; //Update lastRedeemedAt for cooldown calculations lastRedeemedAt = block.timestamp; //Create the next redeem batch id _generateNextBatch(currentRedeemBatchId, BatchType.Redeem); } /** * @notice sets approval for contracts that require access to assets held by this contract */ function setApprovals() external { (address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18); for (uint256 i; i < tokenAddresses.length; i++) { IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken; CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool; YearnVault yearnVault = YearnVault(tokenAddresses[i]); _maxApprove(curveLpToken, address(curveMetapool)); _maxApprove(curveLpToken, address(yearnVault)); _maxApprove(threeCrv, address(curveMetapool)); } _maxApprove(IERC20(address(setToken)), address(staking)); } /** * @notice returns the min amount of butter that should be minted given an amount of 3crv * @dev this controls slippage in the minting process */ function getMinAmountToMint( uint256 _valueOfBatch, uint256 _valueOfComponentsPerUnit, uint256 _slippage ) public pure returns (uint256) { uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit; uint256 _delta = (_mintAmount * _slippage) / 10_000; return _mintAmount - _delta; } /** * @notice returns the min amount of 3crv that should be redeemed given an amount of butter * @dev this controls slippage in the redeeming process */ function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) { uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price(); uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000; return _threeCrvToReceive - _delta; } /** * @notice returns the value of butter in virtualPrice */ function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities) public view returns (uint256) { uint256 value; for (uint256 i = 0; i < _tokenAddresses.length; i++) { value += (((YearnVault(_tokenAddresses[i]).pricePerShare() * curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) / 1e18; } return value; } /** * @notice returns the value of an amount of 3crv in virtualPrice */ function valueOf3Crv(uint256 _units) public view returns (uint256) { return (_units * threePool.get_virtual_price()) / 1e18; } /* ========== RESTRICTED FUNCTIONS ========== */ /** * @notice sets max allowance given a token and a spender * @param _token the token which gets approved to be spend * @param _spender the spender which gets a max allowance to spend `_token` */ function _maxApprove(IERC20 _token, address _spender) internal { _token.safeApprove(_spender, 0); _token.safeApprove(_spender, type(uint256).max); } function _getPoolAllocationAndRatio( address _component, uint256 _quantity, Batch memory _batch, uint256 _setValue, uint256 _threePoolPrice ) internal view returns (uint256 poolAllocation, uint256 ratio) { //Calculate the virtualPrice of one yToken uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() * curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18; //Calculate the value of quantity (of yToken) in virtualPrice uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18; //Calculate the value of leftover yToken in virtualPrice uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) / 1e18; ratio = (componentValuePerSet * 1e18) / _setValue; poolAllocation = _getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) - componentValueHeldByContract; return (poolAllocation, ratio); } /** * @notice returns the amount of 3CRV that should be allocated for a curveMetapool * @param _balance the max amount of 3CRV that is available in this iteration * @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter */ function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) { return ((_balance * _ratio) / 1e18); } /** * @notice sets allowance for basic issuance module * @param _amount amount to approve */ function _setBasicIssuanceModuleAllowance(uint256 _amount) internal { setToken.safeApprove(address(setBasicIssuanceModule), 0); setToken.safeApprove(address(setBasicIssuanceModule), _amount); } /** * @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token * @param _account is the address which gets withdrawn from * @dev returns recipient of the withdrawn funds * @dev By default a user should set _account to their address * @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user */ function _getRecipient(address _account) internal view returns (address) { //Make sure that only zapper can withdraw from someone else require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds"); //Set recipient per default to _account address recipient = _account; //set the recipient to zapper if its called by the zapper if (_hasRole(keccak256("ButterZapper"), msg.sender)) { recipient = msg.sender; } return recipient; } /** * @notice Generates the next batch id for new deposits * @param _currentBatchId takes the current mint or redeem batch id * @param _batchType BatchType of the newly created id */ function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) { bytes32 id = _generateNextBatchId(_currentBatchId); batchIds.push(id); Batch storage batch = batches[id]; batch.batchType = _batchType; batch.batchId = id; if (BatchType.Mint == _batchType) { currentMintBatchId = id; batch.suppliedTokenAddress = address(threeCrv); batch.claimableTokenAddress = address(setToken); } if (BatchType.Redeem == _batchType) { currentRedeemBatchId = id; batch.suppliedTokenAddress = address(setToken); batch.claimableTokenAddress = address(threeCrv); } return id; } /** * @notice Deposit either Butter or 3CRV in their respective batches * @param _amount The amount of 3CRV or Butter a user is depositing * @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed * @param _depositFor User that gets the shares attributed to (for use in zapper contract) * @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication */ function _deposit( uint256 _amount, bytes32 _currentBatchId, address _depositFor ) internal { Batch storage batch = batches[_currentBatchId]; //Add the new funds to the batch batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount; batch.unclaimedShares = batch.unclaimedShares + _amount; accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount; //Save the batchId for the user so they can be retrieved to claim the batch if ( accountBatches[_depositFor].length == 0 || accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId ) { accountBatches[_depositFor].push(_currentBatchId); } emit Deposit(_depositFor, _amount); } /** * @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens * @param _batchId Id of batch to claim from * @param _claimFor User that gets the shares attributed to (for use in zapper contract) */ function _prepareClaim(bytes32 _batchId, address _claimFor) internal returns ( address, BatchType, uint256, uint256 ) { Batch storage batch = batches[_batchId]; require(batch.claimable, "not yet claimable"); address recipient = _getRecipient(_claimFor); uint256 accountBalance = accountBalances[_batchId][_claimFor]; require(accountBalance <= batch.unclaimedShares, "claiming too many shares"); //Calculate how many token will be claimed uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares; //Subtract the claimed token from the batch batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim; batch.unclaimedShares = batch.unclaimedShares - accountBalance; accountBalances[_batchId][_claimFor] = 0; return (recipient, batch.batchType, accountBalance, tokenAmountToClaim); } /** * @notice Deposit 3CRV in a curve metapool for its LP-Token * @param _amount The amount of 3CRV that gets deposited * @param _curveMetapool The metapool where we want to provide liquidity */ function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal { //Takes 3CRV and sends lpToken to this contract //Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second. //The second variable determines the min amount of LP-Token we want to receive (slippage control) _curveMetapool.add_liquidity([0, _amount], 0); } /** * @notice Withdraws 3CRV for deposited crvLPToken * @param _amount The amount of crvLPToken that get deposited * @param _curveMetapool The metapool where we want to provide liquidity */ function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal { //Takes lp Token and sends 3CRV to this contract //The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV) //The third variable determines min amount of token we want to receive (slippage control) _curveMetapool.remove_liquidity_one_coin(_amount, 1, 0); } /** * @notice Deposits crvLPToken for yToken * @param _amount The amount of crvLPToken that get deposited * @param _yearnVault The yearn Vault in which we deposit */ function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal { //Mints yToken and sends them to msg.sender (this contract) _yearnVault.deposit(_amount); } /** * @notice Withdraw crvLPToken from yearn * @param _amount The amount of crvLPToken which we deposit * @param _yearnVault The yearn Vault in which we deposit */ function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal { //Takes yToken and sends crvLPToken to this contract _yearnVault.withdraw(_amount); } /** * @notice Generates the next batch id for new deposits * @param _currentBatchId takes the current mint or redeem batch id */ function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) { return keccak256(abi.encodePacked(block.timestamp, _currentBatchId)); } /* ========== ADMIN ========== */ /** * @notice This function allows the owner to change the composition of underlying token of the Butter * @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter * @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool */ function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs) public onlyRole(DAO_ROLE) { _setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs); } /** * @notice This function defines which underlying token and pools are needed to mint a butter token * @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter * @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool * @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set * @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down */ function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs) internal { emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs); for (uint256 i; i < _yTokenAddresses.length; i++) { curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i]; } } /** * @notice Changes the the ProcessingThreshold * @param _cooldown Cooldown in seconds * @param _mintThreshold Amount of MIM necessary to mint immediately * @param _redeemThreshold Amount of Butter necessary to mint immediately * @dev The cooldown is the same for redeem and mint batches */ function setProcessingThreshold( uint256 _cooldown, uint256 _mintThreshold, uint256 _redeemThreshold ) public onlyRole(DAO_ROLE) { ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({ batchCooldown: _cooldown, mintThreshold: _mintThreshold, redeemThreshold: _redeemThreshold }); emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold); processingThreshold = newProcessingThreshold; } /** * @notice sets slippage for mint and redeem * @param _mintSlippage amount in bps (e.g. 50 = 0.5%) * @param _redeemSlippage amount in bps (e.g. 50 = 0.5%) */ function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) { require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high"); Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage }); emit SlippageUpdated(slippage, newSlippage); slippage = newSlippage; } /** * @notice Changes the redemption fee rate and the fee recipient * @param _feeRate Redemption fee rate in basis points * @param _recipient The recipient which receives these fees (Should be DAO treasury) * @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function */ function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) { require(_feeRate <= 100, "dont get greedy"); redemptionFee.rate = _feeRate; redemptionFee.recipient = _recipient; emit RedemptionFeeUpdated(_feeRate, _recipient); } /** * @notice Claims all accumulated redemption fees in 3CRV */ function claimRedemptionFee() external { threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated); redemptionFee.accumulated = 0; } /** * @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches * @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process * @param _yTokenAddress address of the yToken that should be recovered * @param _amount amount of yToken that should recovered */ function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) { require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist"); IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount); } /** * @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee) * @param _sweetheart The address that shall become/lose their sweetheart status */ function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) { sweethearts[_sweetheart] = _enabled; emit SweetheartUpdated(_sweetheart, _enabled); } /** * @notice Pauses the contract. * @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem */ function pause() external onlyRole(DAO_ROLE) { _pause(); } /** * @notice Unpauses the contract. * @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem */ function unpause() external onlyRole(DAO_ROLE) { _unpause(); } /** * @notice Updates the staking contract */ function setStaking(address _staking) external onlyRole(DAO_ROLE) { emit StakingUpdated(address(staking), _staking); staking = IStaking(_staking); } function _getContract(bytes32 _name) internal view override(ACLAuth, KeeperIncentivized, ContractRegistryAccess) returns (address) { return super._getContract(_name); } } // SPDX-License-Identifier: GPL-3.0 // Docgen-SOLC: 0.8.0 pragma solidity >0.6.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IACLRegistry { /** * @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 `true` if `account` has been granted `permission`. */ function hasPermission(bytes32 permission, 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; function setRoleAdmin(bytes32 role, bytes32 adminRole) external; function grantPermission(bytes32 permission, address account) external; function revokePermission(bytes32 permission) external; function requireApprovedContractOrEOA(address account) external view; function requireRole(bytes32 role, address account) external view; function requirePermission(bytes32 permission, address account) external view; function isRoleAdmin(bytes32 role, address account) external view; } // SPDX-License-Identifier: GPL-3.0 // Docgen-SOLC: 0.8.0 pragma solidity >0.6.0; /** * @dev External interface of ContractRegistry. */ interface IContractRegistry { function getContract(bytes32 _name) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 // Docgen-SOLC: 0.8.0 pragma solidity ^0.8.0; interface IKeeperIncentive { function handleKeeperIncentive( bytes32 _contractName, uint8 _i, address _keeper ) external; } // SPDX-License-Identifier: GPL-3.0 // Docgen-SOLC: 0.8.0 pragma solidity ^0.8.0; interface IStaking { function balanceOf(address account) external view returns (uint256); function stake(uint256 amount) external; function stakeFor(uint256 amount, address account) external; function withdraw(uint256 amount) external; function notifyRewardAmount(uint256 reward) external; } // SPDX-License-Identifier: GPL-3.0 // Docgen-SOLC: 0.8.0 pragma solidity ^0.8.0; import "../interfaces/IACLRegistry.sol"; /** * @notice Provides modifiers and internal functions for interacting with the `ACLRegistry` * @dev Derived contracts using `ACLAuth` must also inherit `ContractRegistryAccess` * and override `_getContract`. */ abstract contract ACLAuth { /** * @dev Equal to keccak256("Keeper") */ bytes32 internal constant KEEPER_ROLE = 0x4f78afe9dfc9a0cb0441c27b9405070cd2a48b490636a7bdd09f355e33a5d7de; /** * @dev Equal to keccak256("DAO") */ bytes32 internal constant DAO_ROLE = 0xd0a4ad96d49edb1c33461cebc6fb2609190f32c904e3c3f5877edb4488dee91e; /** * @dev Equal to keccak256("ApprovedContract") */ bytes32 internal constant APPROVED_CONTRACT_ROLE = 0xfb639edf4b4a4724b8b9fb42a839b712c82108c1edf1beb051bcebce8e689dc4; /** * @dev Equal to keccak256("ACLRegistry") */ bytes32 internal constant ACL_REGISTRY_ID = 0x15fa0125f52e5705da1148bfcf00974823c4381bee4314203ede255f9477b73e; /** * @notice Require that `msg.sender` has given role * @param role bytes32 role ID */ modifier onlyRole(bytes32 role) { _requireRole(role); _; } /** * @notice Require that `msg.sender` has given permission * @param role bytes32 permission ID */ modifier onlyPermission(bytes32 role) { _requirePermission(role); _; } /** * @notice Require that `msg.sender` has the `ApprovedContract` role or is an EOA * @dev This EOA check requires that `tx.origin == msg.sender` if caller does not have the `ApprovedContract` role. * This limits compatibility with contract-based wallets for functions protected with this modifier. */ modifier onlyApprovedContractOrEOA() { _requireApprovedContractOrEOA(msg.sender); _; } /** * @notice Check whether a given account has been granted this bytes32 role * @param role bytes32 role ID * @param account address of account to check for role * @return Whether account has been granted specified role. */ function _hasRole(bytes32 role, address account) internal view returns (bool) { return _aclRegistry().hasRole(role, account); } /** * @notice Require that `msg.sender` has given role * @param role bytes32 role ID */ function _requireRole(bytes32 role) internal view { _requireRole(role, msg.sender); } /** * @notice Require that given account has specified role * @param role bytes32 role ID * @param account address of account to check for role */ function _requireRole(bytes32 role, address account) internal view { _aclRegistry().requireRole(role, account); } /** * @notice Check whether a given account has been granted this bytes32 permission * @param permission bytes32 permission ID * @param account address of account to check for permission * @return Whether account has been granted specified permission. */ function _hasPermission(bytes32 permission, address account) internal view returns (bool) { return _aclRegistry().hasPermission(permission, account); } /** * @notice Require that `msg.sender` has specified permission * @param permission bytes32 permission ID */ function _requirePermission(bytes32 permission) internal view { _requirePermission(permission, msg.sender); } /** * @notice Require that given account has specified permission * @param permission bytes32 permission ID * @param account address of account to check for permission */ function _requirePermission(bytes32 permission, address account) internal view { _aclRegistry().requirePermission(permission, account); } /** * @notice Require that `msg.sender` has the `ApprovedContract` role or is an EOA * @dev This EOA check requires that `tx.origin == msg.sender` if caller does not have the `ApprovedContract` role. * This limits compatibility with contract-based wallets for functions protected with this modifier. */ function _requireApprovedContractOrEOA() internal view { _requireApprovedContractOrEOA(msg.sender); } /** * @notice Require that `account` has the `ApprovedContract` role or is an EOA * @param account address of account to check for role/EOA * @dev This EOA check requires that `tx.origin == msg.sender` if caller does not have the `ApprovedContract` role. * This limits compatibility with contract-based wallets for functions protected with this modifier. */ function _requireApprovedContractOrEOA(address account) internal view { _aclRegistry().requireApprovedContractOrEOA(account); } /** * @notice Return an IACLRegistry interface to the registered ACLRegistry contract * @return IACLRegistry interface to ACLRegistry contract */ function _aclRegistry() internal view returns (IACLRegistry) { return IACLRegistry(_getContract(ACL_REGISTRY_ID)); } /** * @notice Get a contract address by name from the contract registry * @param _name bytes32 contract name * @return contract address * @dev Users of this abstract contract should also inherit from `ContractRegistryAccess` * and override `_getContract` in their implementation. */ function _getContract(bytes32 _name) internal view virtual returns (address); } // SPDX-License-Identifier: GPL-3.0 // Docgen-SOLC: 0.8.0 pragma solidity ^0.8.0; import "../interfaces/IContractRegistry.sol"; /** * @notice Provides an internal `_getContract` helper function to access the `ContractRegistry` */ abstract contract ContractRegistryAccess { IContractRegistry internal _contractRegistry; constructor(IContractRegistry contractRegistry_) { _contractRegistry = contractRegistry_; } /** * @notice Get a contract address by bytes32 name * @param _name bytes32 contract name * @dev contract name should be a keccak256 hash of the name string, e.g. `keccak256("ContractName")` * @return contract address */ function _getContract(bytes32 _name) internal view virtual returns (address) { return _contractRegistry.getContract(_name); } } // SPDX-License-Identifier: GPL-3.0 // Docgen-SOLC: 0.8.0 pragma solidity ^0.8.0; import "../interfaces/IKeeperIncentive.sol"; /** * @notice Provides modifiers and internal functions for processing keeper incentives * @dev Derived contracts using `KeeperIncentivized` must also inherit `ContractRegistryAccess` * and override `_getContract`. */ abstract contract KeeperIncentivized { /** * @notice Role ID for KeeperIncentive * @dev Equal to keccak256("KeeperIncentive") */ bytes32 public constant KEEPER_INCENTIVE = 0x35ed2e1befd3b2dcf1ec7a6834437fa3212881ed81fd3a13dc97c3438896e1ba; /** * @notice Process the specified incentive with `msg.sender` as the keeper address * @param _contractName bytes32 name of calling contract * @param _index uint8 incentive ID */ modifier keeperIncentive(bytes32 _contractName, uint8 _index) { _handleKeeperIncentive(_contractName, _index, msg.sender); _; } /** * @notice Process a keeper incentive * @param _contractName bytes32 name of calling contract * @param _index uint8 incentive ID * @param _keeper address of keeper to reward */ function _handleKeeperIncentive( bytes32 _contractName, uint8 _index, address _keeper ) internal { _keeperIncentive().handleKeeperIncentive(_contractName, _index, _keeper); } /** * @notice Return an IKeeperIncentive interface to the registered KeeperIncentive contract * @return IKeeperIncentive keeper incentive interface */ function _keeperIncentive() internal view returns (IKeeperIncentive) { return IKeeperIncentive(_getContract(KEEPER_INCENTIVE)); } /** * @notice Get a contract address by name from the contract registry * @param _name bytes32 contract name * @return contract address * @dev Users of this abstract contract should also inherit from `ContractRegistryAccess` * and override `_getContract` in their implementation. */ function _getContract(bytes32 _name) internal view virtual returns (address); } // SPDX-License-Identifier: GPL-3.0 // Docgen-SOLC: 0.8.0 pragma solidity ^0.8.0; import "./ISetToken.sol"; interface BasicIssuanceModule { function getRequiredComponentUnitsForIssue(ISetToken _setToken, uint256 _quantity) external view returns (address[] memory, uint256[] memory); function issue( ISetToken _setToken, uint256 _quantity, address _to ) external; function redeem( ISetToken _setToken, uint256 _quantity, address _to ) external; } // SPDX-License-Identifier: GPL-3.0 // Docgen-SOLC: 0.8.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; interface CurveAddressProvider { function get_registry() external view returns (address); } interface CurveRegistry { function get_pool_from_lp_token(address lp_token) external view returns (address); } interface CurveMetapool { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amounts) external returns (uint256); function add_liquidity( uint256[2] calldata _amounts, uint256 _min_mint_amounts, address _receiver ) external returns (uint256); function remove_liquidity_one_coin( uint256 amount, int128 i, uint256 min_underlying_amount ) external returns (uint256); function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); } interface ThreeCrv is IERC20 {} interface CrvLPToken is IERC20 {} // SPDX-License-Identifier: Apache-2.0 // Docgen-SOLC: 0.8.0 /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit( address _component, address _positionModule, int256 _realUnit ) external; function editExternalPositionData( address _component, address _positionModule, bytes calldata _data ) external; function invoke( address _target, uint256 _value, bytes calldata _data ) external returns (bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns (int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns (int256); function getComponents() external view returns (address[] memory); function getExternalPositionModules(address _component) external view returns (address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns (bytes memory); function isExternalPositionModule(address _component, address _module) external view returns (bool); function isComponent(address _component) external view returns (bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns (int256); function isInitializedModule(address _module) external view returns (bool); function isPendingModule(address _module) external view returns (bool); function isLocked() external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 // Docgen-SOLC: 0.6.0 pragma solidity >=0.6.0; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; interface YearnVault is IERC20 { function token() external view returns (address); function deposit(uint256 amount) external; function withdraw(uint256 amount) external; function pricePerShare() external view returns (uint256); }
* @notice This function allows the owner to change the composition of underlying token of the Butter @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs) public onlyRole(DAO_ROLE) { _setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs); }
14,402,638
[ 1, 2503, 445, 5360, 326, 3410, 358, 2549, 326, 16919, 434, 6808, 1147, 434, 326, 12484, 387, 225, 389, 93, 1345, 7148, 1922, 526, 434, 6138, 364, 326, 677, 1345, 3577, 358, 312, 474, 12484, 387, 225, 389, 16683, 2864, 1345, 10409, 1922, 526, 8179, 16868, 6808, 677, 1345, 16, 4422, 90, 1345, 471, 8882, 5100, 438, 1371, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 444, 9423, 2864, 1345, 10409, 12, 2867, 8526, 3778, 389, 93, 1345, 7148, 16, 22901, 2864, 1345, 4154, 8526, 745, 892, 389, 16683, 2864, 1345, 10409, 13, 203, 565, 1071, 203, 565, 1338, 2996, 12, 18485, 67, 16256, 13, 203, 225, 288, 203, 565, 389, 542, 9423, 2864, 1345, 10409, 24899, 93, 1345, 7148, 16, 389, 16683, 2864, 1345, 10409, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/44787/0xcc9C556FbF52e7F1ca8e0E3eB7311ea21d893512/sources/contracts/MirrorNFT.sol
require(_owner == msg.sender, 'Only can claim by owner');
uint256 mNFTId = mapId[tokenAddress][tokenId];
13,256,730
[ 1, 6528, 24899, 8443, 422, 1234, 18, 15330, 16, 296, 3386, 848, 7516, 635, 3410, 8284, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 312, 50, 4464, 548, 273, 852, 548, 63, 2316, 1887, 6362, 2316, 548, 15533, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import {NonReceivableInitializedProxy} from "./NonReceivableInitializedProxy.sol"; import {CollectionParty} from "./CollectionParty.sol"; import {Structs} from "./Structs.sol"; /** * @title CollectionParty Factory * @author Anna Carroll */ contract CollectionPartyFactory { //======== Events ======== event CollectionPartyDeployed( address indexed partyProxy, address indexed creator, address indexed nftContract, uint256 maxPrice, uint256 secondsToTimeout, address[] deciders, address splitRecipient, uint256 splitBasisPoints, address gatedToken, uint256 gatedTokenAmount, string name, string symbol ); //======== Immutable storage ========= address public immutable logic; address public immutable partyDAOMultisig; address public immutable tokenVaultFactory; address public immutable weth; //======== Mutable storage ========= // PartyBid proxy => block number deployed at mapping(address => uint256) public deployedAt; //======== Constructor ========= constructor( address _partyDAOMultisig, address _tokenVaultFactory, address _weth, address _allowList ) { partyDAOMultisig = _partyDAOMultisig; tokenVaultFactory = _tokenVaultFactory; weth = _weth; // deploy logic contract CollectionParty _logicContract = new CollectionParty( _partyDAOMultisig, _tokenVaultFactory, _weth, _allowList ); // store logic contract address logic = address(_logicContract); } //======== Deploy function ========= function startParty( address _nftContract, uint256 _maxPrice, uint256 _secondsToTimeout, address[] calldata _deciders, Structs.AddressAndAmount calldata _split, Structs.AddressAndAmount calldata _tokenGate, string memory _name, string memory _symbol ) external returns (address partyProxy) { bytes memory _initializationCalldata = abi.encodeWithSelector( CollectionParty.initialize.selector, _nftContract, _maxPrice, _secondsToTimeout, _deciders, _split, _tokenGate, _name, _symbol ); partyProxy = address( new NonReceivableInitializedProxy(logic, _initializationCalldata) ); deployedAt[partyProxy] = block.number; emit CollectionPartyDeployed( partyProxy, msg.sender, _nftContract, _maxPrice, _secondsToTimeout, _deciders, _split.addr, _split.amount, _tokenGate.addr, _tokenGate.amount, _name, _symbol ); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @title NonReceivableInitializedProxy * @author Anna Carroll */ contract NonReceivableInitializedProxy { // address of logic contract address public immutable logic; // ======== Constructor ========= constructor(address _logic, bytes memory _initializationCalldata) { logic = _logic; // Delegatecall into the logic contract, supplying initialization calldata (bool _ok, bytes memory returnData) = _logic.delegatecall( _initializationCalldata ); // Revert if delegatecall to implementation reverts require(_ok, string(returnData)); } // ======== Fallback ========= fallback() external payable { address _impl = logic; assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } /* .-'''-. _______ ' _ \ _________ _...._ \ ___ `'. / /` '. \ \ |.' '-. .-. .-' |--.\ \ . | \ ' \ .'```'. '. .-,.--. .|\ \ / /| | \ ' | ' | ' \ | \ \ __ | .-. | .' |_\ \ / / | | | ' __ \ \ / / | | | |.:--.'. | | | | .' |\ \ / / | | | | .:--.'.`. ` ..' / | \ / ./ | \ | | | | |'--. .-' \ \ / / | | ' .'/ | \ | '-...-'` | |\`'-.-' .' `" __ | | | | '- | | \ ` / | |___.' /' `" __ | | | | '-....-'` .'.''| | | | | | \ / /_______.'/ .'.''| | .' '. / / | |_| | | '.' / / \_______|/ / / | |_ '-----------' \ \._,\ '/|_| | /|`-' / \ \._,\ '/ `--' `" `'-' '..' `--' `" Anna Carroll for PartyDAO */ // SPDX-License-Identifier: MIT pragma solidity 0.8.9; // ============ External Imports: External Contracts & Contract Interfaces ============ import {Party} from "./Party.sol"; import {Structs} from "./Structs.sol"; import {IAllowList} from "./IAllowList.sol"; contract CollectionParty is Party { // partyStatus Transitions: // (1) PartyStatus.ACTIVE on deploy // (2) PartyStatus.WON after successful buy() // (3) PartyStatus.LOST after successful expire() // ============ Internal Constants ============ // Collection Party version 1 uint16 public constant VERSION = 1; string public constant PARTY_TYPE = "Collection"; // ============ Immutables ============ IAllowList public immutable allowList; // ============ Public Not-Mutated Storage ============ // the timestamp at which the Party is no longer active uint256 public expiresAt; // the maximum price that the party is willing to // spend on an item in the collection. // NOTE: to remove the maximum price cap, set maxPrice to 0. // by default, CollectionParties shouldn't need a maxPrice // because the deciders should already be trusted to buy well-priced items. // NOTE: the party can accept *UP TO* 102.5% of maxPrice in total, // and will not accept more contributions after this. uint256 public maxPrice; // decider => true if this address is a decider mapping(address => bool) public isDecider; // ============ Events ============ // emitted when a token is successfully bought event Bought( uint256 tokenId, address triggeredBy, address targetAddress, uint256 ethSpent, uint256 ethFeePaid, uint256 totalContributed ); // emitted if the Party fails to buy the token before expiresAt // and someone expires the Party so folks can reclaim ETH event Expired(address triggeredBy); // ======== Constructor ========= constructor( address _partyDAOMultisig, address _tokenVaultFactory, address _weth, address _allowList ) Party(_partyDAOMultisig, _tokenVaultFactory, _weth) { allowList = IAllowList(_allowList); } // ======== Initializer ========= function initialize( address _nftContract, uint256 _maxPrice, uint256 _secondsToTimeout, address[] calldata _deciders, Structs.AddressAndAmount calldata _split, Structs.AddressAndAmount calldata _tokenGate, string memory _name, string memory _symbol ) external initializer { // initialize & validate shared Party variables __Party_init(_nftContract, _split, _tokenGate, _name, _symbol); // set PartyBuy-specific state variables expiresAt = block.timestamp + _secondsToTimeout; maxPrice = _maxPrice; // attempt to calculate maximum contributions to ensure this value won't overflow later getMaximumContributions(); // set deciders list require( _deciders.length > 0, "PartyBuy::initialize: set at least one decider" ); for (uint256 i = 0; i < _deciders.length; i++) { isDecider[_deciders[i]] = true; } } // ======== External: Contribute ========= /** * @notice Contribute to the Party's treasury * while the Party is still active * @dev Emits a Contributed event upon success; callable by anyone */ function contribute() external payable nonReentrant { // require that the new total contributed is not greater than // the maximum amount the Party is willing to spend require( totalContributedToParty + msg.value <= getMaximumContributions(), "PartyBuy::contribute: cannot contribute more than max" ); // continue with shared _contribute flow // shared _contribute flow _contribute(); } // ======== External: Buy ========= /** * @notice Buy the token by calling targetContract with calldata supplying value * @dev Emits a Bought event upon success; reverts otherwise. callable by anyone */ function buy( uint256 _tokenId, uint256 _value, address _targetContract, bytes calldata _calldata ) external nonReentrant { require( partyStatus == PartyStatus.ACTIVE, "PartyBuy::buy: party not active" ); // ensure the caller is a decider require(isDecider[msg.sender], "PartyBuy::buy: caller not a decider"); // ensure the target contract is on allow list require( allowList.allowed(_targetContract), "PartyBuy::buy: targetContract not on AllowList" ); // check that value is not zero (else, token will be burned in TokenVault) require(_value > 0, "PartyBuy::buy: can't spend zero"); // check that value is not more than the maximum price set at deploy time require( maxPrice == 0 || _value <= maxPrice, "PartyBuy::buy: can't spend over max price" ); // check that value is not more than // the maximum amount the party can spend while paying ETH fee require( _value <= getMaximumSpend(), "PartyBuy::buy: insuffucient funds to buy token plus fee" ); // set tokenId variable before _getOwner tokenId = _tokenId; // require that the NFT is NOT owned by the Party require( _getOwner() != address(this), "PartyBuy::buy: own token before call" ); // execute the calldata on the target contract (bool _success, bytes memory _returnData) = address(_targetContract) .call{value: _value}(_calldata); // require that the external call succeeded require(_success, string(_returnData)); // require that the NFT is owned by the Party require( _getOwner() == address(this), "PartyBuy::buy: failed to buy token" ); // set partyStatus to WON partyStatus = PartyStatus.WON; // record totalSpent, // send ETH fees to PartyDAO, // fractionalize the Token // send Token fees to PartyDAO & split proceeds to split recipient uint256 _ethFee = _closeSuccessfulParty(_value); // emit Bought event emit Bought( _tokenId, msg.sender, _targetContract, _value, _ethFee, totalContributedToParty ); } // ======== External: Fail ========= /** * @notice If the token couldn't be successfully bought * within the specified period of time, move to FAILED state * so users can reclaim their funds. * @dev Emits a Expired event upon finishing; reverts otherwise. * callable by anyone after expiresAt */ function expire() external nonReentrant { require( partyStatus == PartyStatus.ACTIVE, "PartyBuy::expire: party not active" ); require( expiresAt <= block.timestamp, "PartyBuy::expire: party has not timed out" ); // set partyStatus to LOST partyStatus = PartyStatus.LOST; // emit Expired event emit Expired(msg.sender); } // ============ Internal ============ /** * @notice Get the maximum amount that can be contributed to the Party * @return _maxContributions the maximum amount that can be contributed to the party */ function getMaximumContributions() public view returns (uint256 _maxContributions) { uint256 _price = maxPrice; if (_price == 0) { return 2**256 - 1; // max-int } _maxContributions = _price + _getEthFee(_price); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface Structs { struct AddressAndAmount { address addr; uint256 amount; } } /* __/\\\\\\\\\\\\\_____________________________________________________________/\\\\\\\\\\\\________/\\\\\\\\\__________/\\\\\______ _\/\\\/////////\\\__________________________________________________________\/\\\////////\\\____/\\\\\\\\\\\\\______/\\\///\\\____ _\/\\\_______\/\\\__________________________________/\\\_________/\\\__/\\\_\/\\\______\//\\\__/\\\/////////\\\___/\\\/__\///\\\__ _\/\\\\\\\\\\\\\/___/\\\\\\\\\_____/\\/\\\\\\\___/\\\\\\\\\\\___\//\\\/\\\__\/\\\_______\/\\\_\/\\\_______\/\\\__/\\\______\//\\\_ _\/\\\/////////____\////////\\\___\/\\\/////\\\_\////\\\////_____\//\\\\\___\/\\\_______\/\\\_\/\\\\\\\\\\\\\\\_\/\\\_______\/\\\_ _\/\\\_______________/\\\\\\\\\\__\/\\\___\///_____\/\\\__________\//\\\____\/\\\_______\/\\\_\/\\\/////////\\\_\//\\\______/\\\__ _\/\\\______________/\\\/////\\\__\/\\\____________\/\\\_/\\___/\\_/\\\_____\/\\\_______/\\\__\/\\\_______\/\\\__\///\\\__/\\\____ _\/\\\_____________\//\\\\\\\\/\\_\/\\\____________\//\\\\\___\//\\\\/______\/\\\\\\\\\\\\/___\/\\\_______\/\\\____\///\\\\\/_____ _\///_______________\////////\//__\///______________\/////_____\////________\////////////_____\///________\///_______\/////_______ Anna Carroll for PartyDAO */ // SPDX-License-Identifier: MIT pragma solidity 0.8.9; // ============ External Imports: Inherited Contracts ============ // NOTE: we inherit from OpenZeppelin upgradeable contracts // because of the proxy structure used for cheaper deploys // (the proxies are NOT actually upgradeable) import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import {ERC721HolderUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol"; // ============ External Imports: External Contracts & Contract Interfaces ============ import {IERC721VaultFactory} from "./external/interfaces/IERC721VaultFactory.sol"; import {ITokenVault} from "./external/interfaces/ITokenVault.sol"; import {IWETH} from "./external/interfaces/IWETH.sol"; import {IERC721Metadata} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // ============ Internal Imports ============ import {Structs} from "./Structs.sol"; contract Party is ReentrancyGuardUpgradeable, ERC721HolderUpgradeable { // ============ Enums ============ // State Transitions: // (0) ACTIVE on deploy // (1) WON if the Party has won the token // (2) LOST if the Party is over & did not win the token enum PartyStatus { ACTIVE, WON, LOST } // ============ Structs ============ struct Contribution { uint256 amount; uint256 previousTotalContributedToParty; } // ============ Internal Constants ============ // tokens are minted at a rate of 1 ETH : 1000 tokens uint16 internal constant TOKEN_SCALE = 1000; // PartyDAO receives an ETH fee equal to 2.5% of the amount spent uint16 internal constant ETH_FEE_BASIS_POINTS = 250; // PartyDAO receives a token fee equal to 2.5% of the total token supply uint16 internal constant TOKEN_FEE_BASIS_POINTS = 250; // token is relisted on Fractional with an // initial reserve price equal to 2x the price of the token uint8 internal constant RESALE_MULTIPLIER = 2; // ============ Immutables ============ address public immutable partyFactory; address public immutable partyDAOMultisig; IERC721VaultFactory public immutable tokenVaultFactory; IWETH public immutable weth; // ============ Public Not-Mutated Storage ============ // NFT contract IERC721Metadata public nftContract; // ID of token within NFT contract uint256 public tokenId; // Fractionalized NFT vault responsible for post-purchase experience ITokenVault public tokenVault; // the address that will receive a portion of the tokens // if the Party successfully buys the token address public splitRecipient; // percent of the total token supply // taken by the splitRecipient uint256 public splitBasisPoints; // address of token that users need to hold to contribute // address(0) if party is not token gated IERC20 public gatedToken; // amount of token that users need to hold to contribute // 0 if party is not token gated uint256 public gatedTokenAmount; // ERC-20 name and symbol for fractional tokens string public name; string public symbol; // ============ Public Mutable Storage ============ // state of the contract PartyStatus public partyStatus; // total ETH deposited by all contributors uint256 public totalContributedToParty; // the total spent buying the token; // 0 if the NFT is not won; price of token + 2.5% PartyDAO fee if NFT is won uint256 public totalSpent; // contributor => array of Contributions mapping(address => Contribution[]) public contributions; // contributor => total amount contributed mapping(address => uint256) public totalContributed; // contributor => true if contribution has been claimed mapping(address => bool) public claimed; // ============ Events ============ event Contributed( address indexed contributor, uint256 amount, uint256 previousTotalContributedToParty, uint256 totalFromContributor ); event Claimed( address indexed contributor, uint256 totalContributed, uint256 excessContribution, uint256 tokenAmount ); // ======== Modifiers ========= modifier onlyPartyDAO() { require( msg.sender == partyDAOMultisig, "Party:: only PartyDAO multisig" ); _; } // ======== Constructor ========= constructor( address _partyDAOMultisig, address _tokenVaultFactory, address _weth ) { partyFactory = msg.sender; partyDAOMultisig = _partyDAOMultisig; tokenVaultFactory = IERC721VaultFactory(_tokenVaultFactory); weth = IWETH(_weth); } // ======== Internal: Initialize ========= function __Party_init( address _nftContract, Structs.AddressAndAmount calldata _split, Structs.AddressAndAmount calldata _tokenGate, string memory _name, string memory _symbol ) internal { require( msg.sender == partyFactory, "Party::__Party_init: only factory can init" ); // if split is non-zero, if (_split.addr != address(0) && _split.amount != 0) { // validate that party split won't retain the total token supply uint256 _remainingBasisPoints = 10000 - TOKEN_FEE_BASIS_POINTS; require( _split.amount < _remainingBasisPoints, "Party::__Party_init: basis points can't take 100%" ); splitBasisPoints = _split.amount; splitRecipient = _split.addr; } // if token gating is non-zero if (_tokenGate.addr != address(0) && _tokenGate.amount != 0) { // call totalSupply to verify that address is ERC-20 token contract IERC20(_tokenGate.addr).totalSupply(); gatedToken = IERC20(_tokenGate.addr); gatedTokenAmount = _tokenGate.amount; } // initialize ReentrancyGuard and ERC721Holder __ReentrancyGuard_init(); __ERC721Holder_init(); // set storage variables nftContract = IERC721Metadata(_nftContract); name = _name; symbol = _symbol; } // ======== Internal: Contribute ========= /** * @notice Contribute to the Party's treasury * while the Party is still active * @dev Emits a Contributed event upon success; callable by anyone */ function _contribute() internal { require( partyStatus == PartyStatus.ACTIVE, "Party::contribute: party not active" ); address _contributor = msg.sender; uint256 _amount = msg.value; // if token gated, require that contributor has balance of gated tokens if (address(gatedToken) != address(0)) { require( gatedToken.balanceOf(_contributor) >= gatedTokenAmount, "Party::contribute: must hold tokens to contribute" ); } require(_amount > 0, "Party::contribute: must contribute more than 0"); // get the current contract balance uint256 _previousTotalContributedToParty = totalContributedToParty; // add contribution to contributor's array of contributions Contribution memory _contribution = Contribution({ amount: _amount, previousTotalContributedToParty: _previousTotalContributedToParty }); contributions[_contributor].push(_contribution); // add to contributor's total contribution totalContributed[_contributor] = totalContributed[_contributor] + _amount; // add to party's total contribution & emit event totalContributedToParty = _previousTotalContributedToParty + _amount; emit Contributed( _contributor, _amount, _previousTotalContributedToParty, totalContributed[_contributor] ); } // ======== External: Claim ========= /** * @notice Claim the tokens and excess ETH owed * to a single contributor after the party has ended * @dev Emits a Claimed event upon success * callable by anyone (doesn't have to be the contributor) * @param _contributor the address of the contributor */ function claim(address _contributor) external nonReentrant { // ensure party has finalized require( partyStatus != PartyStatus.ACTIVE, "Party::claim: party not finalized" ); // ensure contributor submitted some ETH require( totalContributed[_contributor] != 0, "Party::claim: not a contributor" ); // ensure the contributor hasn't already claimed require( !claimed[_contributor], "Party::claim: contribution already claimed" ); // mark the contribution as claimed claimed[_contributor] = true; // calculate the amount of fractional NFT tokens owed to the user // based on how much ETH they contributed towards the party, // and the amount of excess ETH owed to the user (uint256 _tokenAmount, uint256 _ethAmount) = getClaimAmounts( _contributor ); // transfer tokens to contributor for their portion of ETH used _transferTokens(_contributor, _tokenAmount); // if there is excess ETH, send it back to the contributor _transferETHOrWETH(_contributor, _ethAmount); emit Claimed( _contributor, totalContributed[_contributor], _ethAmount, _tokenAmount ); } // ======== External: Emergency Escape Hatches (PartyDAO Multisig Only) ========= /** * @notice Escape hatch: in case of emergency, * PartyDAO can use emergencyWithdrawEth to withdraw * ETH stuck in the contract */ function emergencyWithdrawEth(uint256 _value) external onlyPartyDAO { _transferETHOrWETH(partyDAOMultisig, _value); } /** * @notice Escape hatch: in case of emergency, * PartyDAO can use emergencyCall to call an external contract * (e.g. to withdraw a stuck NFT or stuck ERC-20s) */ function emergencyCall(address _contract, bytes memory _calldata) external onlyPartyDAO returns (bool _success, bytes memory _returnData) { (_success, _returnData) = _contract.call(_calldata); require(_success, string(_returnData)); } /** * @notice Escape hatch: in case of emergency, * PartyDAO can force the Party to finalize with status LOST * (e.g. if finalize is not callable) */ function emergencyForceLost() external onlyPartyDAO { // set partyStatus to LOST partyStatus = PartyStatus.LOST; } // ======== Public: Utility Calculations ========= /** * @notice Convert ETH value to equivalent token amount */ function valueToTokens(uint256 _value) public pure returns (uint256 _tokens) { _tokens = _value * TOKEN_SCALE; } /** * @notice The maximum amount that can be spent by the Party * while paying the ETH fee to PartyDAO * @return _maxSpend the maximum spend */ function getMaximumSpend() public view returns (uint256 _maxSpend) { _maxSpend = (totalContributedToParty * 10000) / (10000 + ETH_FEE_BASIS_POINTS); } /** * @notice Calculate the amount of fractional NFT tokens owed to the contributor * based on how much ETH they contributed towards buying the token, * and the amount of excess ETH owed to the contributor * based on how much ETH they contributed *not* used towards buying the token * @param _contributor the address of the contributor * @return _tokenAmount the amount of fractional NFT tokens owed to the contributor * @return _ethAmount the amount of excess ETH owed to the contributor */ function getClaimAmounts(address _contributor) public view returns (uint256 _tokenAmount, uint256 _ethAmount) { require( partyStatus != PartyStatus.ACTIVE, "Party::getClaimAmounts: party still active; amounts undetermined" ); uint256 _totalContributed = totalContributed[_contributor]; if (partyStatus == PartyStatus.WON) { // calculate the amount of this contributor's ETH // that was used to buy the token uint256 _totalEthUsed = totalEthUsed(_contributor); if (_totalEthUsed > 0) { _tokenAmount = valueToTokens(_totalEthUsed); } // the rest of the contributor's ETH should be returned _ethAmount = _totalContributed - _totalEthUsed; } else { // if the token wasn't bought, no ETH was spent; // all of the contributor's ETH should be returned _ethAmount = _totalContributed; } } /** * @notice Calculate the total amount of a contributor's funds * that were used towards the buying the token * @dev always returns 0 until the party has been finalized * @param _contributor the address of the contributor * @return _total the sum of the contributor's funds that were * used towards buying the token */ function totalEthUsed(address _contributor) public view returns (uint256 _total) { require( partyStatus != PartyStatus.ACTIVE, "Party::totalEthUsed: party still active; amounts undetermined" ); // load total amount spent once from storage uint256 _totalSpent = totalSpent; // get all of the contributor's contributions Contribution[] memory _contributions = contributions[_contributor]; for (uint256 i = 0; i < _contributions.length; i++) { // calculate how much was used from this individual contribution uint256 _amount = _ethUsed(_totalSpent, _contributions[i]); // if we reach a contribution that was not used, // no subsequent contributions will have been used either, // so we can stop calculating to save some gas if (_amount == 0) break; _total = _total + _amount; } } // ============ Internal ============ function _closeSuccessfulParty(uint256 _nftCost) internal returns (uint256 _ethFee) { // calculate PartyDAO fee & record total spent _ethFee = _getEthFee(_nftCost); totalSpent = _nftCost + _ethFee; // transfer ETH fee to PartyDAO _transferETHOrWETH(partyDAOMultisig, _ethFee); // deploy fractionalized NFT vault // and mint fractional ERC-20 tokens _fractionalizeNFT(_nftCost); } /** * @notice Calculate ETH fee for PartyDAO * NOTE: Remove this fee causes a critical vulnerability * allowing anyone to exploit a Party via price manipulation. * See Security Review in README for more info. * @return _fee the portion of _amount represented by scaling to ETH_FEE_BASIS_POINTS */ function _getEthFee(uint256 _amount) internal pure returns (uint256 _fee) { _fee = (_amount * ETH_FEE_BASIS_POINTS) / 10000; } /** * @notice Calculate token amount for specified token recipient * @return _totalSupply the total token supply * @return _partyDAOAmount the amount of tokens for partyDAO fee, * which is equivalent to TOKEN_FEE_BASIS_POINTS of total supply * @return _splitRecipientAmount the amount of tokens for the token recipient, * which is equivalent to splitBasisPoints of total supply */ function _getTokenInflationAmounts(uint256 _amountSpent) internal view returns ( uint256 _totalSupply, uint256 _partyDAOAmount, uint256 _splitRecipientAmount ) { // the token supply will be inflated to provide a portion of the // total supply for PartyDAO, and a portion for the splitRecipient uint256 inflationBasisPoints = TOKEN_FEE_BASIS_POINTS + splitBasisPoints; _totalSupply = valueToTokens( (_amountSpent * 10000) / (10000 - inflationBasisPoints) ); // PartyDAO receives TOKEN_FEE_BASIS_POINTS of the total supply _partyDAOAmount = (_totalSupply * TOKEN_FEE_BASIS_POINTS) / 10000; // splitRecipient receives splitBasisPoints of the total supply _splitRecipientAmount = (_totalSupply * splitBasisPoints) / 10000; } /** * @notice Query the NFT contract to get the token owner * @dev nftContract must implement the ERC-721 token standard exactly: * function ownerOf(uint256 _tokenId) external view returns (address); * See https://eips.ethereum.org/EIPS/eip-721 * @dev Returns address(0) if NFT token or NFT contract * no longer exists (token burned or contract self-destructed) * @return _owner the owner of the NFT */ function _getOwner() internal view returns (address _owner) { (bool _success, bytes memory _returnData) = address(nftContract) .staticcall(abi.encodeWithSignature("ownerOf(uint256)", tokenId)); if (_success && _returnData.length > 0) { _owner = abi.decode(_returnData, (address)); } } /** * @notice Upon winning the token, transfer the NFT * to fractional.art vault & mint fractional ERC-20 tokens */ function _fractionalizeNFT(uint256 _amountSpent) internal { // approve fractionalized NFT Factory to withdraw NFT nftContract.approve(address(tokenVaultFactory), tokenId); // Party "votes" for a reserve price on Fractional // equal to 2x the price of the token uint256 _listPrice = RESALE_MULTIPLIER * _amountSpent; // users receive tokens at a rate of 1:TOKEN_SCALE for each ETH they contributed that was ultimately spent // partyDAO receives a percentage of the total token supply equivalent to TOKEN_FEE_BASIS_POINTS // splitRecipient receives a percentage of the total token supply equivalent to splitBasisPoints ( uint256 _tokenSupply, uint256 _partyDAOAmount, uint256 _splitRecipientAmount ) = _getTokenInflationAmounts(totalSpent); // deploy fractionalized NFT vault uint256 vaultNumber = tokenVaultFactory.mint( name, symbol, address(nftContract), tokenId, _tokenSupply, _listPrice, 0 ); // store token vault address to storage tokenVault = ITokenVault(tokenVaultFactory.vaults(vaultNumber)); // transfer curator to null address (burn the curator role) tokenVault.updateCurator(address(0)); // transfer tokens to PartyDAO multisig _transferTokens(partyDAOMultisig, _partyDAOAmount); // transfer tokens to token recipient if (splitRecipient != address(0)) { _transferTokens(splitRecipient, _splitRecipientAmount); } } // ============ Internal: Claim ============ /** * @notice Calculate the amount of a single Contribution * that was used towards buying the token * @param _contribution the Contribution struct * @return the amount of funds from this contribution * that were used towards buying the token */ function _ethUsed(uint256 _totalSpent, Contribution memory _contribution) internal pure returns (uint256) { if ( _contribution.previousTotalContributedToParty + _contribution.amount <= _totalSpent ) { // contribution was fully used return _contribution.amount; } else if ( _contribution.previousTotalContributedToParty < _totalSpent ) { // contribution was partially used return _totalSpent - _contribution.previousTotalContributedToParty; } // contribution was not used return 0; } // ============ Internal: TransferTokens ============ /** * @notice Transfer tokens to a recipient * @param _to recipient of tokens * @param _value amount of tokens */ function _transferTokens(address _to, uint256 _value) internal { // skip if attempting to send 0 tokens if (_value == 0) { return; } // guard against rounding errors; // if token amount to send is greater than contract balance, // send full contract balance uint256 _partyBalance = tokenVault.balanceOf(address(this)); if (_value > _partyBalance) { _value = _partyBalance; } tokenVault.transfer(_to, _value); } // ============ Internal: TransferEthOrWeth ============ /** * @notice Attempt to transfer ETH to a recipient; * if transferring ETH fails, transfer WETH insteads * @param _to recipient of ETH or WETH * @param _value amount of ETH or WETH */ function _transferETHOrWETH(address _to, uint256 _value) internal { // skip if attempting to send 0 ETH if (_value == 0) { return; } // guard against rounding errors; // if ETH amount to send is greater than contract balance, // send full contract balance if (_value > address(this).balance) { _value = address(this).balance; } // Try to transfer ETH to the given recipient. if (!_attemptETHTransfer(_to, _value)) { // If the transfer fails, wrap and send as WETH weth.deposit{value: _value}(); weth.transfer(_to, _value); // At this point, the recipient can unwrap WETH. } } /** * @notice Attempt to transfer ETH to a recipient * @dev Sending ETH is not guaranteed to succeed * this method will return false if it fails. * We will limit the gas used in transfers, and handle failure cases. * @param _to recipient of ETH * @param _value amount of ETH */ function _attemptETHTransfer(address _to, uint256 _value) internal returns (bool) { // Here increase the gas limit a reasonable amount above the default, and try // to send ETH to the recipient. // NOTE: This might allow the recipient to attempt a limited reentrancy attack. (bool success, ) = _to.call{value: _value, gas: 30000}(""); return success; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @title IAllowList * @author Anna Carroll */ interface IAllowList { function allowed(address _addr) external view returns (bool _bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721ReceiverUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable { function __ERC721Holder_init() internal initializer { __ERC721Holder_init_unchained(); } function __ERC721Holder_init_unchained() internal initializer { } /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } uint256[50] private __gap; } //SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface IERC721VaultFactory { /// @notice the mapping of vault number to vault address function vaults(uint256) external returns (address); /// @notice the function to mint a new vault /// @param _name the desired name of the vault /// @param _symbol the desired sumbol of the vault /// @param _token the ERC721 token address fo the NFT /// @param _id the uint256 ID of the token /// @param _listPrice the initial price of the NFT /// @return the ID of the vault function mint(string memory _name, string memory _symbol, address _token, uint256 _id, uint256 _supply, uint256 _listPrice, uint256 _fee) external returns(uint256); } //SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface ITokenVault { /// @notice allow curator to update the curator address /// @param _curator the new curator function updateCurator(address _curator) external; /** * @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) external returns (bool); /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); } // 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 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 // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../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; /** * @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); }
* @notice Contribute to the Party's treasury while the Party is still active @dev Emits a Contributed event upon success; callable by anyone/ require that the new total contributed is not greater than the maximum amount the Party is willing to spend continue with shared _contribute flow shared _contribute flow
function contribute() external payable nonReentrant { require( totalContributedToParty + msg.value <= getMaximumContributions(), "PartyBuy::contribute: cannot contribute more than max" ); _contribute(); }
14,508,264
[ 1, 442, 887, 358, 326, 6393, 93, 1807, 9787, 345, 22498, 1323, 326, 6393, 93, 353, 4859, 2695, 225, 7377, 1282, 279, 735, 11050, 871, 12318, 2216, 31, 4140, 635, 1281, 476, 19, 2583, 716, 326, 394, 2078, 356, 11050, 353, 486, 6802, 2353, 326, 4207, 3844, 326, 6393, 93, 353, 903, 310, 358, 17571, 1324, 598, 5116, 389, 591, 887, 4693, 5116, 389, 591, 887, 4693, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 356, 887, 1435, 3903, 8843, 429, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 12, 203, 5411, 2078, 442, 11050, 774, 17619, 397, 1234, 18, 1132, 1648, 25194, 442, 15326, 9334, 203, 5411, 315, 17619, 38, 9835, 2866, 591, 887, 30, 2780, 356, 887, 1898, 2353, 943, 6, 203, 3639, 11272, 203, 3639, 389, 591, 887, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x4a513fE4Ca37E9756b3B96FBc9f7Be7863A69f9F/sources/contracts/RodContract.sol
just a test amount
_charityWalletAddress.transfer(1);
8,130,763
[ 1, 3732, 279, 1842, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 3001, 560, 16936, 1887, 18, 13866, 12, 21, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x3f877eF029b7Ea03e51eC0EbC2031Ce382A50Fdd/sources/contracts/BoxV2.sol
Emitted when the stored value changes Stores a new value in the contract
contract Box { uint256 private _value; event ValueChanged(uint256 value); pragma solidity ^0.8.0; function store1(uint256 value) public { _value = value; emit ValueChanged(value); } function retrieve() public view returns (uint256) { return _value; } function retrieve1() public view returns (uint256) { return _value +1 ; } function increment() public { _value = _value + 1; emit ValueChanged(_value); } }
760,900
[ 1, 1514, 11541, 1347, 326, 4041, 460, 3478, 20296, 455, 279, 394, 460, 316, 326, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 8549, 288, 203, 565, 2254, 5034, 3238, 389, 1132, 31, 203, 203, 565, 871, 1445, 5033, 12, 11890, 5034, 460, 1769, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 445, 1707, 21, 12, 11890, 5034, 460, 13, 1071, 288, 203, 3639, 389, 1132, 273, 460, 31, 203, 3639, 3626, 1445, 5033, 12, 1132, 1769, 203, 565, 289, 203, 203, 565, 445, 4614, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 1132, 31, 203, 565, 289, 203, 203, 565, 445, 4614, 21, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 1132, 397, 21, 274, 203, 565, 289, 203, 203, 565, 445, 5504, 1435, 1071, 288, 203, 3639, 389, 1132, 273, 389, 1132, 397, 404, 31, 203, 3639, 3626, 1445, 5033, 24899, 1132, 1769, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.2; import "AccessControlUpgradeable.sol"; import "UUPSUpgradeable.sol"; import "PausableUpgradeable.sol"; import "SafeERC20.sol"; import "ERC20.sol"; import { Address } from "Address.sol"; import { XYWrappedToken } from "XYWrappedToken.sol"; import "IGasPriceConsumer.sol"; /// @title YPoolVault provides cross-chain liquidity for swap between chains. /// Users are allowed to supply the designated deposit token to the pool to earn /// cross-chain swap fees, and request to withdraw anytime. contract YPoolVault is AccessControlUpgradeable, UUPSUpgradeable, PausableUpgradeable { using SafeERC20 for IERC20; /* ========== STRUCTURE ========== */ // request to deposit struct DepositRequest { // amount of the deposit token uint256 amountDepositToken; // depositor address sender; // is the request completed yet bool isComplete; } // request to withdraw struct WithdrawalRequest { // amount of xy-wrapped token to be withdrawn uint256 amountXYWrappedToken; // withdrawer address sender; // is the request completed yet bool isComplete; } /* ========== STATE VARIABLES ========== */ // Roles in this contract // Owner: able to upgrade contract and change swapper contract address bytes32 public constant ROLE_OWNER = keccak256("ROLE_OWNER"); // Manager: able to pause/unpause contract, set gas provider / gas collector address bytes32 public constant ROLE_MANAGER = keccak256("ROLE_MANAGER"); // Staff: able to set required gas for different requests bytes32 public constant ROLE_STAFF = keccak256("ROLE_STAFF"); // Liquidity Worker: complete the requests bytes32 public constant ROLE_LIQUIDITY_WORKER = keccak256("ROLE_LIQUIDITY_WORKER"); // Native token address address public constant ETHER_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // XY token deciamls uint256 public constant XY_TOKEN_DECIMALS = 18; // Yield rate decimals uint256 public constant YIELD_RATE_DECIMALS = 8; // Max yield rate bound of deposit/withdraw uint256 public maxYieldRateBound; // Min yield rate bound of deposit/withdraw uint256 public minYieldRateBound; // Swapper address address public swapper; // The address receive the collected gas fee address public gasFeeReceiver; // The address of token to deposit IERC20 public depositToken; // Deposit token decimal uint8 public depositTokenDecimal; // XY-Wrapped token address XYWrappedToken public xyWrappedToken; // Address of gas consumer address public gasPriceConsumer; // Gas limit that YPool need to proceed deposit request uint256 public completeDepositGasLimit; // Gas limit that YPool need to proceed withdraw request uint256 public completeWithdrawGasLimit; // Current fees collected from deposit and withdraw request gas fee uint256 public depositAndWithdrawFees; // Swap fees current accumulated uint256 public closeSwapGasFees; // Number of the deposits uint256 public numDeposits; // Number of the withdrawal uint256 public numWithdrawals; // Mapping of the depsit ID to deposit request struct mapping (uint256 => DepositRequest) public depositRequests; // Mapping of the withdraw ID to withdraw request struct mapping (uint256 => WithdrawalRequest) public withdrawalRequests; receive() external payable {} function _authorizeUpgrade(address) internal override onlyRole(ROLE_OWNER) {} /// @notice Initialize YPoolVault by owner, manager, staff, liquidity worker, deposit token address, wrapped token address, and deposit token decimal /// @param owner The owner address /// @param manager The manager address /// @param staff The staff address /// @param liquidityWorker The liquidity worker address /// @param _depositToken The deposit token address /// @param _xyWrappedToken The XY-Wrapped token address /// @param _depositTokenDecimal The deposit token decimal function initialize(address owner, address manager, address staff, address liquidityWorker, address _depositToken, address _xyWrappedToken, uint8 _depositTokenDecimal) initializer public { if (_depositToken != ETHER_ADDRESS) { require(Address.isContract(_depositToken), "ERR_DEPOSIT_TOKEN_NOT_CONTRACT"); } require(Address.isContract(_xyWrappedToken), "ERR_XY_WRPAPPED_TOKEN_NOT_CONTRACT"); depositToken = IERC20(_depositToken); xyWrappedToken = XYWrappedToken(_xyWrappedToken); depositTokenDecimal = _depositTokenDecimal; _setRoleAdmin(ROLE_OWNER, ROLE_OWNER); _setRoleAdmin(ROLE_MANAGER, ROLE_OWNER); _setRoleAdmin(ROLE_STAFF, ROLE_OWNER); _setRoleAdmin(ROLE_LIQUIDITY_WORKER, ROLE_OWNER); _setupRole(ROLE_OWNER, owner); _setupRole(ROLE_MANAGER, manager); _setupRole(ROLE_STAFF, staff); _setupRole(ROLE_LIQUIDITY_WORKER, liquidityWorker); } /* ========== MODIFIERS ========== */ modifier onlySwapper() { require(msg.sender == swapper, "ERR_NOT_SWAPPER"); _; } /* ========== PRIVATE FUNCTIONS ========== */ /// @notice Get currnet gas price from price consumer function _getGasPrice() private view returns (uint256) { require(gasPriceConsumer != address(0), "ERR_GAS_PRICE_CONSUMER_NOT_SET"); return uint256(IGasPriceConsumer(gasPriceConsumer).getLatestGasPrice()); } /// @notice Unify transfer interface for native token and ERC20 token /// @param receiver The address to reveice token /// @param token The token to be transferred /// @param amount Amount of the token to be transferred function _safeTransferAsset(address receiver, IERC20 token, uint256 amount) private { if (address(token) == ETHER_ADDRESS) { payable(receiver).transfer(amount); } else { token.safeTransfer(receiver, amount); } } /// @notice Transfer ERC20 token from sender to receiver /// @param token The token to be transferred /// @param sender The address to transfer token from /// @param receiver The address to receive token /// @param amount Amount of the token to be transferred function _safeTransferAssetFrom(IERC20 token, address sender, address receiver, uint256 amount) private { require(address(token) != ETHER_ADDRESS, "ERR_TOKEN_ADDRESS"); uint256 bal = token.balanceOf(receiver); token.safeTransferFrom(sender, receiver, amount); bal = token.balanceOf(receiver) - bal; require(bal == amount, "ERR_AMOUNT_NOT_ENOUGH"); } /// @notice Transfer collected deposit and withdraw request fees to receiver /// @param receiver The address to receive fees function _collectDepositAndWithdrawGasFees(address receiver) private { uint256 _depositAndWithdrawFees = depositAndWithdrawFees; depositAndWithdrawFees = 0; payable(receiver).transfer(_depositAndWithdrawFees); emit DepositAndWithdrawGasFeesCollected(receiver, _depositAndWithdrawFees); } /// @notice Transfer collected swap fees to receiver /// @param receiver The address to receive fees function _collectCloseSwapGasFees(address receiver) private { uint256 _closeSwapGasFees = closeSwapGasFees; closeSwapGasFees = 0; if (address(depositToken) == ETHER_ADDRESS) { payable(receiver).transfer(_closeSwapGasFees); } else { depositToken.safeTransfer(receiver, _closeSwapGasFees); } emit CloseSwapGasFeesCollected(depositToken, receiver, _closeSwapGasFees); } /* ========== RESTRICTED FUNCTIONS (OWNER) ========== */ /// @notice Connect YPoolVault to a certain XSwapper (could be set only by owner) /// @param _swapper New swapper address function setSwapper(address _swapper) external onlyRole(ROLE_OWNER) { require(Address.isContract(_swapper), "ERR_SWAPPER_NOT_CONTRACT"); swapper = _swapper; } /* ========== RESTRICTED FUNCTIONS (MANAGER) ========== */ /// @notice Set new gas fee receiver. This address receives fees accumulated from deposit / withdraw /// requests and swap fees when staff role calls one of the collect fee methods. (could be set only by manager) /// @param _gasFeeReceiver New gas receiver address function setGasFeeReceiver(address _gasFeeReceiver) external onlyRole(ROLE_MANAGER) { gasFeeReceiver = _gasFeeReceiver; } /// @notice Set new gas price consumer address that conforms to `IGasPriceConsumer` protocol (could be set only by manager) /// @param _gasPriceConsumer New gas price consumer address function setGasPriceConsumer(address _gasPriceConsumer) external onlyRole(ROLE_MANAGER) { require(Address.isContract(_gasPriceConsumer), "ERR_GAS_PRICE_CONSUMER_NOT_CONTRACT"); gasPriceConsumer = _gasPriceConsumer; } /// @notice Set maximum and minimum value of yield rate bound. (could be set only by manager) /// These bounds are to make sure the withdraw amount and deposit amount are within a safe range of yields /// as unexpected amounts would lead to false yield rate. /// This is particularly useful if the Y Pool worker is unfortunately compromised in the worst case. /// The bounds can be loosened gradually if there are more fees accumulated and the yield rate has increased. /// @param _maxYieldRateBound Maximum yield rate bound /// @param _minYieldRateBound Minimum yield rate bound function setYieldRateBound(uint256 _maxYieldRateBound, uint256 _minYieldRateBound) external onlyRole(ROLE_MANAGER) { require(_maxYieldRateBound >= 10 ** YIELD_RATE_DECIMALS); maxYieldRateBound = _maxYieldRateBound; minYieldRateBound = _minYieldRateBound; } /// @notice Pause YPool vault (could be executed only by manager) function pause() external onlyRole(ROLE_MANAGER) { _pause(); } /// @notice Unpause YPool vault (could be executed only by manager) function unpause() external onlyRole(ROLE_MANAGER) { _unpause(); } /* ========== RESTRICTED FUNCTIONS (STAFF) ========== */ /// @notice Set deposit gas limit. This is one of the factors to determine how much gas fee should user paid /// upon the deposit request. (could be set only by staff) /// @dev Request fee is calculated as `completeDepositGasLimit` * gas price provided from `gasPriceConsumer` /// @param gasLimit New deposit gas limit function setCompleteDepositGasLimit(uint256 gasLimit) external onlyRole(ROLE_STAFF) { completeDepositGasLimit = gasLimit; } /// @notice Set withdraw gas limit. This is one of the factors to determine how much gas fee should user paid /// upon the withdraw request. (could be set only by staff) /// @dev Request fee is calculated as `completeWithdrawGasLimit` * gas price provided from `gasPriceConsumer` /// @param gasLimit New withdraw gas limit function setCompleteWithdrawGasLimit(uint256 gasLimit) external onlyRole(ROLE_STAFF) { completeWithdrawGasLimit = gasLimit; } /// @notice Transfer current accumulated deposit / withdraw request fees to `gasFeeReceiver` (could be executed only by staff) function collectDepositAndWithdrawGasFees() external whenNotPaused onlyRole(ROLE_STAFF) { _collectDepositAndWithdrawGasFees(gasFeeReceiver); } /// @notice Transfer current accumulated swap fees to `gasFeeReceiver` (could be executed only by staff) function collectCloseSwapGasFees() external whenNotPaused onlyRole(ROLE_STAFF) { _collectCloseSwapGasFees(gasFeeReceiver); } /// @notice Transfer current accumulated deposit / withdraw request fees and swap fees to `gasFeeReceiver` (could be executed only by staff) function collectFees() external whenNotPaused onlyRole(ROLE_STAFF) { _collectDepositAndWithdrawGasFees(gasFeeReceiver); _collectCloseSwapGasFees(gasFeeReceiver); } /* ========== RESTRICTED FUNCTIONS (SWAPPER) ========== */ /// @notice Transfer token from YPool liquidity to swapper contract. (could be executed only by swapper) /// XSwapper calls this method within `closeSwap` to transfer token from YPool liquidity to swapper /// contract in order to close a cross-chain swap request. See XSwapper.sol for more info. /// @param token Token to be transferred /// @param amount Amount of token to be transferred function transferToSwapper(IERC20 token, uint256 amount) external whenNotPaused onlySwapper { require(token == depositToken, "ERR_TRANSFER_WRONG_TOKEN_TO_SWAPPER"); emit TransferToSwapper(swapper, token, amount); _safeTransferAsset(swapper, token, amount); } /// @notice Transfer token from swapper contract to YPool. (could be executed only by swapper) /// XSwapper calls this method within `claim` or `batchClaim` to transfer token from XSwapper to YPool /// contract in order to claim token back to YPool after liquidity worker completed a cross-chain request. /// See XSwapper.sol for more info. /// @param token Token to be transferred /// @param amount Amount of token to be transferred /// @param xyFeeAmount Amount of xyFee colleted /// @param gasFeeAmount Amount of gas fee colleted function receiveAssetFromSwapper(IERC20 token, uint256 amount, uint256 xyFeeAmount, uint256 gasFeeAmount) external payable whenNotPaused onlySwapper { require(token == depositToken, "ERR_TRANSFER_WRONG_TOKEN_FROM_SWAPPER"); if (address(token) == ETHER_ADDRESS) { require(msg.value == amount, "ERR_INVALID_AMOUNT"); } else { _safeTransferAssetFrom(token, swapper, address(this), amount); } closeSwapGasFees += gasFeeAmount; emit AssetReceived(token, amount, xyFeeAmount, gasFeeAmount); } /* ========== RESTRICTED FUNCTIONS (LIQUIDITY WORKER) ========== */ /// @notice Complete a deposit request by minting XY-Wrapped tokens /// according to liquidity condition on settlement chain. (could be executed only by liquidity worker) /// @param _depositID The deposit ID to be processed /// @param amountXYWrappedToken Amount of XY-Wrapped token to be minted function completeDeposit(uint256 _depositID, uint256 amountXYWrappedToken) external whenNotPaused onlyRole(ROLE_LIQUIDITY_WORKER) { require(_depositID < numDeposits, "ERR_INVALID_DEPOSIT_ID"); DepositRequest storage request = depositRequests[_depositID]; require(!request.isComplete, "ERR_DEPOSIT_ALREADY_COMPLETE"); // yield rate = (amount ypool token) / (amount wrapped token) require(request.amountDepositToken * 10 ** (YIELD_RATE_DECIMALS + XY_TOKEN_DECIMALS - depositTokenDecimal) / amountXYWrappedToken <= maxYieldRateBound, "ERR_YIELD_RATE_OUT_OF_MAX_BOUND"); require(request.amountDepositToken * 10 ** (YIELD_RATE_DECIMALS + XY_TOKEN_DECIMALS - depositTokenDecimal) / amountXYWrappedToken >= minYieldRateBound, "ERR_YIELD_RATE_OUT_OF_MIN_BOUND"); emit DepositFulfilled(request.sender, _depositID, amountXYWrappedToken); request.isComplete = true; xyWrappedToken.mint(request.sender, amountXYWrappedToken); } /// @notice Complete a withdraw request by burning XY-Wrapped tokens /// and transferring back deposit token according to liquidity condition on settlement chain /// (could be executed only by liquidity worker) /// @param _withdrawID The withdraw ID to be processed /// @param amount Amount of the deposit token to be returned to request sender /// @param withdrawFee Fee for completing withdraw request function completeWithdraw(uint256 _withdrawID, uint256 amount, uint256 withdrawFee) external whenNotPaused onlyRole(ROLE_LIQUIDITY_WORKER) { require(_withdrawID < numWithdrawals, "ERR_INVALID_WITHDRAW_ID"); require(amount > 0, "ERR_WITHDRAW_FEE_NOT_LESS_THAN_AMOUNT"); WithdrawalRequest storage request = withdrawalRequests[_withdrawID]; require(!request.isComplete, "ERR_ALREADY_COMPLETED"); // yield rate = (amount ypool token) / (amount wrapped token) require((amount + withdrawFee) * 10 ** (YIELD_RATE_DECIMALS + XY_TOKEN_DECIMALS - depositTokenDecimal) / request.amountXYWrappedToken <= maxYieldRateBound, "ERR_YIELD_RATE_OUT_OF_MAX_BOUND"); require((amount + withdrawFee) * 10 ** (YIELD_RATE_DECIMALS + XY_TOKEN_DECIMALS - depositTokenDecimal) / request.amountXYWrappedToken >= minYieldRateBound, "ERR_YIELD_RATE_OUT_OF_MIN_BOUND"); emit WithdrawalFulfilled(request.sender, _withdrawID, amount, withdrawFee); request.isComplete = true; xyWrappedToken.burn(request.amountXYWrappedToken); _safeTransferAsset(request.sender, depositToken, amount); } /* ========== WRITE FUNCTIONS ========== */ /// @notice Request to deposit /// @dev Gas fee is required and checked upon the deposit request based on current gas /// price and deposit gas limit. /// @param amount Amount of deposit token to deposit function deposit(uint256 amount) external whenNotPaused payable { require(amount > 0, "ERR_INVALID_DEPOSIT_AMOUNT"); uint256 gasFee = completeDepositGasLimit * _getGasPrice(); uint256 requiredValue = (address(depositToken) == ETHER_ADDRESS) ? gasFee + amount : gasFee; require(msg.value >= requiredValue, "ERR_NOT_ENOUGH_FEE"); depositAndWithdrawFees += gasFee; uint256 id = numDeposits++; depositRequests[id] = DepositRequest(amount, msg.sender, false); payable(msg.sender).transfer(msg.value - requiredValue); if (address(depositToken) != ETHER_ADDRESS) { _safeTransferAssetFrom(depositToken, msg.sender, address(this), amount); } emit DepositRequested(msg.sender, id, amount, gasFee); } /// @notice Request to withdraw /// @dev Gas fee is required and checked upon the withdraw request based on current gas /// price and withdraw gas limit. /// @param amountXYWrappedToken Amount of XY-Wrapped token used to withdraw function withdraw(uint256 amountXYWrappedToken) external payable whenNotPaused { require(amountXYWrappedToken > 0, "ERR_INVALID_WITHDRAW_AMOUNT"); uint256 gasFee = completeWithdrawGasLimit * _getGasPrice(); require(msg.value >= gasFee, "ERR_NOT_ENOUGH_FEE"); depositAndWithdrawFees += gasFee; uint256 id = numWithdrawals++; withdrawalRequests[id] = WithdrawalRequest(amountXYWrappedToken, msg.sender, false); payable(msg.sender).transfer(msg.value - gasFee); _safeTransferAssetFrom(xyWrappedToken, msg.sender, address(this), amountXYWrappedToken); emit WithdrawalRequested(msg.sender, id, amountXYWrappedToken, gasFee); } /* ========== EVENTS ========== */ event TransferToSwapper(address swapper, IERC20 token, uint256 amount); event DepositRequested(address indexed sender, uint256 indexed depositID, uint256 amountDepositToken, uint256 gasFee); event DepositFulfilled(address indexed recipient, uint256 indexed depositID, uint256 amountXYWrappedToken); event WithdrawalRequested(address indexed sender, uint256 indexed withdrawID, uint256 amountXYWrappedToken, uint256 gasFee); event WithdrawalFulfilled(address indexed recipient, uint256 indexed withdrawID, uint256 amountDepositToken, uint256 withdrawFee); event AssetReceived(IERC20 token, uint256 assetAmount, uint256 xyFeeAmount, uint256 gasFeeAmount); event DepositAndWithdrawGasFeesCollected(address recipient, uint256 gasFees); event CloseSwapGasFeesCollected(IERC20 token, address recipient, uint256 gasFees); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IAccessControlUpgradeable.sol"; import "ContextUpgradeable.sol"; import "StringsUpgradeable.sol"; import "ERC165Upgradeable.sol"; import "Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC165Upgradeable.sol"; import "Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "ERC1967UpgradeUpgradeable.sol"; import "Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "IBeaconUpgradeable.sol"; import "AddressUpgradeable.sol"; import "StorageSlotUpgradeable.sol"; import "Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @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) private returns (bytes memory) { require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; 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 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 StorageSlotUpgradeable { 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 "ContextUpgradeable.sol"; import "Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC20.sol"; import "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; /** * @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 "IERC20Metadata.sol"; import "Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "Ownable.sol"; import "ERC20.sol"; contract XYWrappedToken is ERC20, Ownable { event SetMinter(address minter, bool isMinter); mapping (address => bool) public isMinter; modifier onlyMinter { require(isMinter[msg.sender], "ERR_NOT_MINTER"); _; } constructor(string memory name_, string memory symbol_) ERC20(name_, symbol_) { isMinter[owner()] = true; } function setMinter(address minter, bool _isMinter) external onlyOwner { isMinter[minter] = _isMinter; emit SetMinter(minter, _isMinter); } function mint(address account, uint256 amount) external onlyMinter { _mint(account, amount); } function burn(uint256 amount) external { _burn(msg.sender, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; interface IGasPriceConsumer { function getLatestGasPrice() external view returns (int); }
@notice Transfer collected swap fees to receiver @param receiver The address to receive fees
function _collectCloseSwapGasFees(address receiver) private { uint256 _closeSwapGasFees = closeSwapGasFees; closeSwapGasFees = 0; if (address(depositToken) == ETHER_ADDRESS) { payable(receiver).transfer(_closeSwapGasFees); depositToken.safeTransfer(receiver, _closeSwapGasFees); } emit CloseSwapGasFeesCollected(depositToken, receiver, _closeSwapGasFees); }
1,340,568
[ 1, 5912, 12230, 7720, 1656, 281, 358, 5971, 225, 5971, 1021, 1758, 358, 6798, 1656, 281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 14676, 4605, 12521, 27998, 2954, 281, 12, 2867, 5971, 13, 3238, 288, 203, 3639, 2254, 5034, 389, 4412, 12521, 27998, 2954, 281, 273, 1746, 12521, 27998, 2954, 281, 31, 203, 3639, 1746, 12521, 27998, 2954, 281, 273, 374, 31, 203, 3639, 309, 261, 2867, 12, 323, 1724, 1345, 13, 422, 512, 19905, 67, 15140, 13, 288, 203, 5411, 8843, 429, 12, 24454, 2934, 13866, 24899, 4412, 12521, 27998, 2954, 281, 1769, 203, 5411, 443, 1724, 1345, 18, 4626, 5912, 12, 24454, 16, 389, 4412, 12521, 27998, 2954, 281, 1769, 203, 3639, 289, 203, 3639, 3626, 3527, 12521, 27998, 2954, 281, 10808, 329, 12, 323, 1724, 1345, 16, 5971, 16, 389, 4412, 12521, 27998, 2954, 281, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "../interfaces/IStrategy.sol"; import "../interfaces/IVault.sol"; import "../interfaces/IPancakeRouter02.sol"; import "../interfaces/IWaultSwapRouter02.sol"; import "../interfaces/ISwap.sol"; import "../interfaces/IWaultPair.sol"; import "../interfaces/INervePair.sol"; import "../interfaces/IWexMaster.sol"; import "../interfaces/IMasterMind.sol"; import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/IBEP20.sol"; import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; contract Strategy is IStrategy, Ownable, Pausable { using SafeBEP20 for IBEP20; using SafeBEP20 for IWaultPair; using SafeBEP20 for INervePair; using SafeMath for uint256; /* ============= CONSTANTS ============= */ IBEP20 private WBNB = IBEP20(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); IBEP20 private ETH = IBEP20(0x2170Ed0880ac9A755fd29B2688956BD959F933F8); // Binance Pegged ETH IBEP20 private BETH = IBEP20(0x250632378E573c6Be1AC2f97Fcdf00515d0Aa91B); IBEP20 private constant ANYETH = IBEP20(0x6F817a0cE8F7640Add3bC0c1C2298635043c2423); IBEP20 private constant WEX = IBEP20(0xa9c41A46a6B3531d28d5c32F6633dd2fF05dFB90); IBEP20 private constant NRV = IBEP20(0x42F6f551ae042cBe50C739158b4f0CAC0Edb9096); IWaultPair private constant ETH_BETH_LP = IWaultPair(0x11040f3c467993556B19813d4A18b684598Ba4BD); // WaultSwap WETH-BETH LP INervePair private constant ETH_ANYETH_LP = INervePair(0x0d283BF16A9bdE49cfC48d8dc050AF28b71bdD90); // Nerve WETH-anyETH LP IPancakeRouter02 private constant PANCAKE_ROUTER = IPancakeRouter02(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F); // PCS Router V2 IWaultSwapRouter02 private constant WAULT_ROUTER = IWaultSwapRouter02(0xD48745E39BbED146eEC15b79cBF964884F9877c2); // WaultSwap Router ISwap private constant NERVE_SWAP = ISwap(0x146CD24dCc9f4EB224DFd010c5Bf2b0D25aFA9C0); // Nerve ETH-anyETH LP maker IWexMaster private constant WAULT_FARM = IWexMaster(0x22fB2663C7ca71Adc2cc99481C77Aaf21E152e2D); // Wault WETH-BETH Farm, pid = 42 IMasterMind private constant NERVE_FARM = IMasterMind(0x2EBe8CDbCB5fB8564bC45999DAb8DA264E31f24E); // Nerve WETH-anyETH Farm, pid = 5 uint256 private constant WAULT_PID = 42; uint256 private constant NERVE_PID = 5; uint8 private constant ETH_NERVE_TOKEN_ID = 0; uint8 private constant ANYETH_NERVE_TOKEN_ID = 1; uint256 private constant DENOMINATOR = 10000; uint256 private constant MAX_AMT = type(uint256).max; uint256 private constant ONE = 1e18; /* ========== STATE VARIABLES ========== */ // LP token price in ETH uint256 public _price_ETH_BETH_LP; // Might not need uint256 public _price_ETH_ANYETH_LP; // Pool in ETH uint256 public _pool_ETH_BETH_LP; uint256 public _pool_ETH_ANYETH_LP; address public admin; address public communityWallet; address public strategist; IVault public vault; // Farm Allocation Weights uint256 public waultFarmPerc = 5000; // 50% allocation to Wault uint256 public nerveFarmPerc = 5000; // 50% allocation to Nerve // Fees uint256 public yieldFeePerc = 1000; // 10% Yield fees // Information uint256 public totalWaultYield = 0; uint256 public totalNerveYield = 0; /* ============= MODIFIERS ============= */ modifier onlyAdmin { require(msg.sender == address(admin), "Strategy:: Only Admin"); _; } modifier onlyVault { require(msg.sender == address(vault), "Strategy:: Only Vault"); _; } /* ============== EVENTS ============== */ event Invested(uint256 ethInvested); event LiquidityRemoved( address lpToken, uint256 liquidityRemoved, uint256 amountA, uint256 amountB, address router ); event LiquidityAdded( address tokenA, address tokenB, uint256 amountA, uint256 amountB, uint256 liquidity, address router ); event SetVault(address vaultAddress); event SetAdmin(address adminAddress); event SetStrategist(address strategistAddress); event Harvested(uint256 claimedWEX, uint256 claimedNRV); event Withdrawn(uint256 amount, uint256 withdrawalFee); /* ============ CONSTRUCTOR ============ */ constructor( address _communityWallet, address _strategist, address _admin ) public { require( _communityWallet != address(0), "Strategy::constructor: communityWallet does not exist" ); communityWallet = _communityWallet; strategist = _strategist; admin = _admin; ETH.safeApprove(address(PANCAKE_ROUTER), MAX_AMT); ETH.safeApprove(address(WAULT_ROUTER), MAX_AMT); ETH.safeApprove(address(NERVE_SWAP), MAX_AMT); BETH.safeApprove(address(PANCAKE_ROUTER), MAX_AMT); BETH.safeApprove(address(WAULT_ROUTER), MAX_AMT); ANYETH.safeApprove(address(PANCAKE_ROUTER), MAX_AMT); ANYETH.safeApprove(address(NERVE_SWAP), MAX_AMT); ETH_BETH_LP.safeApprove(address(WAULT_FARM), MAX_AMT); ETH_BETH_LP.safeApprove(address(WAULT_ROUTER), MAX_AMT); ETH_ANYETH_LP.safeApprove(address(NERVE_FARM), MAX_AMT); ETH_ANYETH_LP.safeApprove(address(NERVE_SWAP), MAX_AMT); WEX.safeApprove(address(PANCAKE_ROUTER), MAX_AMT); NRV.safeApprove(address(PANCAKE_ROUTER), MAX_AMT); } receive() external payable { // ... } fallback() external { // ... } /* =========== VIEW FUNCTIONS =========== */ /// @notice Get TVL of Strategy in ETH function getStrategyPool() public view override returns (uint256 _valueInEth) { uint256 _valueInEth_ETH_BETH_LP = _pool_ETH_BETH_LP .mul(_calcPriceETH_BETH_LP()) .div(1e18); uint256 _valueInEth_ETH_ANYETH_LP = _pool_ETH_ANYETH_LP .mul(_calcPriceETH_ANYETH_LP()) .div(1e18); _valueInEth = _valueInEth_ETH_BETH_LP.add(_valueInEth_ETH_ANYETH_LP); } /* ========= MUTATIVE FUNCTIONS ========= */ /// @notice Invest tokens into Wault and Nerve Farms /// @param _amount Amount of ETH to invest function invest(uint256 _amount) public override onlyVault whenNotPaused { require(_amount > 0, "Strategy::invest: Invest Amount <= 0"); ETH.safeTransferFrom(address(vault), address(this), _amount); // Divide by 2 to maintain the 1:1 ETH:BETH for LP uint256 _amountToBETH = _amount.mul(waultFarmPerc).div(2).div( DENOMINATOR ); uint256 _amountToANYETH = _amount.mul(nerveFarmPerc).div(2).div( DENOMINATOR ); uint256 _amountRemaining = _amount.sub(_amountToBETH).sub( _amountToANYETH ); uint256 _amountBETH = _swapETHforBETH(_amountToBETH); uint256 _amountANYETH = _swapETHforANYETH(_amountToANYETH); uint256 _amount_ETH_BETH_LP = _addLiquidityWault( _amountRemaining.div(2), _amountBETH ); _amountRemaining = _amountRemaining.sub(_amountRemaining.div(2)); uint256 _amount_ETH_ANYETH_LP = _addLiquidityNerve( _amountRemaining, _amountANYETH ); _investWault(_amount_ETH_BETH_LP); _investNerve(_amount_ETH_ANYETH_LP); // Update Pool uint256 _pool_ETH_BETH_LP_before = _pool_ETH_BETH_LP; (uint256 _pool_ETH_BETH_LP_after, , ) = WAULT_FARM.userInfo( WAULT_PID, address(this) ); uint256 _pool_ETH_ANYETH_LP_before = _pool_ETH_ANYETH_LP; (uint256 _pool_ETH_ANYETH_LP_after, ) = NERVE_FARM.userInfo( NERVE_PID, address(this) ); _pool_ETH_BETH_LP = _pool_ETH_BETH_LP.add( _pool_ETH_BETH_LP_after.sub(_pool_ETH_BETH_LP_before) ); _pool_ETH_ANYETH_LP = _pool_ETH_ANYETH_LP.add( _pool_ETH_ANYETH_LP_after.sub(_pool_ETH_ANYETH_LP_before) ); emit Invested(_amount); } /// @notice Withdraw tokens from farms and swap into ETH /// @dev Liquidate enough LP tokens to meet the amount, 50% from Wault and 50% from Nerve function withdraw(uint256 _amount) public override onlyVault whenNotPaused { require(_amount > 0, "Strategy::withdraw: Withdraw Amount <= 0)"); uint256 _strategyPool = getStrategyPool(); uint256 _amount_ETH_BETH_LP = _amount.mul(_pool_ETH_BETH_LP).div( _strategyPool ); uint256 _amount_ETH_ANYETH_LP = _amount.mul(_pool_ETH_ANYETH_LP).div( _strategyPool ); // Withdrawing automatically harvests yields _withdrawWault(_amount_ETH_BETH_LP); _withdrawNerve(_amount_ETH_ANYETH_LP); ( uint256 _amountETHFromWault, uint256 _amountBETH ) = _removeLiquidityWault(_amount_ETH_BETH_LP); ( uint256 _amountETHFromNerve, uint256 _amountANYETH ) = _removeLiquidityNerve(_amount_ETH_ANYETH_LP); _pool_ETH_BETH_LP = _pool_ETH_BETH_LP.sub(_amount_ETH_BETH_LP); _pool_ETH_ANYETH_LP = _pool_ETH_ANYETH_LP.sub(_amount_ETH_ANYETH_LP); uint256 _totalRewards = _liquidateRewards(); // in ETH uint256 _fees = _totalRewards.mul(yieldFeePerc).div(DENOMINATOR); _splitYieldFees(_fees); // Swap BETH and anyETH back to ETH uint256 _amountETHFromBETH = _swapBETHforETH(_amountBETH); uint256 _amountETHFromANYETH = _swapANYETHforETH(_amountANYETH); uint256 _amountETH = _amountETHFromWault.add(_amountETHFromNerve).add( _totalRewards ); _amountETH = _amountETH.sub(_fees).add(_amountETHFromBETH).add( _amountETHFromANYETH ); // Send deserved ETH back to Vault ETH.safeTransfer(address(vault), _amountETH); } /// @notice Harvest yields from farms and reinvest them function compound() external override onlyVault whenNotPaused { _harvest(); uint256 _amount = _liquidateRewards(); invest(_amount); } /* ========= PRIVATE FUNCTIONS ========= */ /// @notice Invest ETH-BETH LP tokens into WexMaster function _investWault(uint256 _amount) private { require( _amount > 0, "Strategy::_investWault: Invalid Amount (_amount <= 0)" ); WAULT_FARM.deposit(WAULT_PID, _amount, false); } /// @notice Invest ETH-anyETH LP tokens into MasterMind function _investNerve(uint256 _amount) private { require( _amount > 0, "Strategy::_investNerve: Invalid Amount (_amount <= 0)" ); NERVE_FARM.deposit(NERVE_PID, _amount); } /// @notice Withdraw ETH-BETH LP Tokens from WexMaster function _withdrawWault(uint256 _amount) private { WAULT_FARM.withdraw(WAULT_PID, _amount, true); } /// @notice Withdraw ETH-anyETH LP Tokens from MasterMind function _withdrawNerve(uint256 _amount) private { NERVE_FARM.withdraw(NERVE_PID, _amount); } /// @notice Harvest yields from farms function _harvest() private { uint256 _claimedWEX = _harvestWault(); uint256 _claimedNRV = _harvestNerve(); totalWaultYield = totalWaultYield.add(_claimedWEX); totalNerveYield = totalNerveYield.add(_claimedNRV); emit Harvested(_claimedWEX, _claimedNRV); } /// @notice Harvest Wault Rewards function _harvestWault() private returns (uint256 _rewardsClaimed) { uint256 _pendingRewards = WAULT_FARM.pendingWex( WAULT_PID, address(this) ); _rewardsClaimed = 0; // Check if pending WEX is above 0 if (_pendingRewards > 0) { WAULT_FARM.claim(WAULT_PID); _rewardsClaimed = _pendingRewards; } } /// @notice Harvest Nerve Rewards function _harvestNerve() private returns (uint256 _rewardsClaimed) { uint256 _pendingRewards = NERVE_FARM.pendingNerve( NERVE_PID, address(this) ); _rewardsClaimed = 0; // Check if pending NRV is above 0 // TODO: Write logic to claim NRV rewards, Nerve Finance locks up 2/3 rewards and does not have claim function if (_pendingRewards > 0) { NERVE_FARM.withdraw(NERVE_PID, 0); _rewardsClaimed = _pendingRewards; } } /// @notice Swaps ETH for BETH on Pancake Router function _swapETHforBETH(uint256 _amount) private returns (uint256 _amountBETH) { uint256[] memory _amounts = _swapExactTokensForTokens( address(ETH), address(BETH), _amount ); _amountBETH = _amounts[1]; } /// @notice Swaps ETH for anyETH on Pancake Router function _swapETHforANYETH(uint256 _amount) private returns (uint256 _amountANYETH) { // Only nerveswap has liquidity uint256 _amountsOut = NERVE_SWAP.calculateSwap( ETH_NERVE_TOKEN_ID, ANYETH_NERVE_TOKEN_ID, _amount ); if (_amountsOut > 0) { _amountANYETH = NERVE_SWAP.swap( ETH_NERVE_TOKEN_ID, ANYETH_NERVE_TOKEN_ID, _amount, 0, block.timestamp ); } else { // Not enough amount to swap _amountANYETH = 0; } } /// @notice Swaps BETH for ETH on Pancake Router function _swapBETHforETH(uint256 _amount) private returns (uint256 _amountETH) { uint256[] memory _amounts = _swapExactTokensForTokens( address(BETH), address(ETH), _amount ); _amountETH = _amounts[1]; } /// @notice Swaps ANYETH for ETH on Pancake Router function _swapANYETHforETH(uint256 _amount) private returns (uint256 _amountETH) { // Only nerveswap has liquidity uint256 _amountsOut = NERVE_SWAP.calculateSwap( ANYETH_NERVE_TOKEN_ID, ETH_NERVE_TOKEN_ID, _amount ); if (_amountsOut > 0) { _amountETH = NERVE_SWAP.swap( ANYETH_NERVE_TOKEN_ID, ETH_NERVE_TOKEN_ID, _amount, 0, block.timestamp ); } else { // Not enough amount to swap _amountETH = 0; } } /// @notice Get Wault ETH-BETH LP tokens function _addLiquidityWault(uint256 _amountETH, uint256 _amountBETH) private returns (uint256) { (uint256 _amountA, uint256 _amountB, uint256 _liquidity) = WAULT_ROUTER .addLiquidity( address(ETH), address(BETH), _amountETH, _amountBETH, 0, 0, address(this), block.timestamp ); emit LiquidityAdded( address(ETH), address(BETH), _amountA, _amountB, _liquidity, address(WAULT_ROUTER) ); return _liquidity; } /// @notice Get Nerve ETH-anyETH LP tokens function _addLiquidityNerve(uint256 _amountETH, uint256 _amountANYETH) private returns (uint256 _liquidity) { uint256[] memory _amounts = new uint256[](2); _amounts[0] = _amountETH; _amounts[1] = _amountANYETH; _liquidity = NERVE_SWAP.addLiquidity(_amounts, 0, block.timestamp); emit LiquidityAdded( address(ETH), address(ANYETH), _amountETH, _amountANYETH, _liquidity, address(NERVE_SWAP) ); } /// @notice Remove ETH-BETH Liquidity from Wault Swap function _removeLiquidityWault(uint256 _amount) private returns (uint256 _amountA, uint256 _amountB) { (_amountA, _amountB) = WAULT_ROUTER.removeLiquidity( address(ETH), address(BETH), _amount, 0, 0, address(this), block.timestamp ); emit LiquidityRemoved( address(ETH_BETH_LP), _amount, _amountA, _amountB, address(WAULT_ROUTER) ); } /// @notice Remove ETH-anyETH Liquidity from Nerve Swap function _removeLiquidityNerve(uint256 _amount) private returns (uint256 _amountA, uint256 _amountB) { uint256[] memory _minAmounts = new uint256[](2); _minAmounts[0] = 0; _minAmounts[1] = 0; uint256[] memory _returnedAmounts = NERVE_SWAP.removeLiquidity( _amount, _minAmounts, block.timestamp ); _amountA = _returnedAmounts[0]; _amountB = _returnedAmounts[1]; emit LiquidityRemoved( address(ETH_ANYETH_LP), _amount, _amountA, _amountB, address(NERVE_SWAP) ); } /// @notice Convert all rewards (WEX + NRV) into base token (ETH) function _liquidateRewards() private returns (uint256 _totalRewards) { // Liquidate Wault Rewards uint256 _waultRewards = _liquidateWaultRewards(); // Liquidate Nerve Rewards uint256 _nerveRewards = _liquidateNerveRewards(); // Calculate total ETH gained from rewards _totalRewards = _waultRewards.add(_nerveRewards); } /// @notice Function to transfer fees that collect from yield to wallets /// @param _amount Fees to transfer in ETH Token function _splitYieldFees(uint256 _amount) private { uint256 _creditToAdmin = (_amount).mul(2).div(5); uint256 _creditToCommunityWallet = (_amount).mul(2).div(5); uint256 _creditToStrategist = (_amount).mul(1).div(5); ETH.safeTransfer(admin, _creditToAdmin); // 40% ETH.safeTransfer(communityWallet, _creditToCommunityWallet); // 40% ETH.safeTransfer(strategist, _creditToStrategist); // 20% } /// @notice Converts WEX rewards to ETH function _liquidateWaultRewards() private returns (uint256 _yieldAmount) { uint256 _balanceOfWEX = WEX.balanceOf(address(this)); _yieldAmount = 0; if (_balanceOfWEX > 0) { uint256[] memory _amounts = _swapExactTokensForTokens2( address(WEX), address(ETH), _balanceOfWEX ); _yieldAmount = _amounts[2]; } } /// @notice Converts NRV rewards to ETH function _liquidateNerveRewards() private returns (uint256 _yieldAmount) { uint256 _balanceOfNRV = NRV.balanceOf(address(this)); _yieldAmount = 0; if (_balanceOfNRV > 0) { uint256[] memory _amounts = _swapExactTokensForTokens2( address(NRV), address(ETH), _balanceOfNRV ); _yieldAmount = _amounts[2]; } } /// @notice Function to swap tokens with PancakeSwap /// @param _tokenA Token to be swapped /// @param _tokenB Token to be received /// @param _amountIn Amount of token to be swapped /// @return _amounts Array that contains swapped amounts function _swapExactTokensForTokens( address _tokenA, address _tokenB, uint256 _amountIn ) private returns (uint256[] memory _amounts) { address[] memory _path = _getPath(_tokenA, _tokenB); uint256[] memory _amountsOut = PANCAKE_ROUTER.getAmountsOut( _amountIn, _path ); if (_amountsOut[1] > 0) { _amounts = PANCAKE_ROUTER.swapExactTokensForTokens( _amountIn, 0, _path, address(this), block.timestamp ); } else { // Not enough amount to swap uint256[] memory _zeroReturn = new uint256[](2); _zeroReturn[0] = 0; _zeroReturn[1] = 0; return _zeroReturn; } } /// @notice Function to swap Exotic tokens with PancakeSwap /// @dev For tokens that cannot be swapped directly /// @param _tokenA Token to be swapped /// @param _tokenB Token to be received /// @param _amountIn Amount of token to be swapped /// @return _amounts Array that contains swapped amounts function _swapExactTokensForTokens2( address _tokenA, address _tokenB, uint256 _amountIn ) private returns (uint256[] memory _amounts) { address[] memory _path = _getPath2(_tokenA, _tokenB); uint256[] memory _amountsOut = PANCAKE_ROUTER.getAmountsOut( _amountIn, _path ); if (_amountsOut[2] > 0) { _amounts = PANCAKE_ROUTER.swapExactTokensForTokens( _amountIn, 0, _path, address(this), block.timestamp ); } else { // Not enough amount to swap uint256[] memory _zeroReturn = new uint256[](2); _zeroReturn[0] = 0; _zeroReturn[2] = 0; return _zeroReturn; } } /// @notice Function to get path for PancakeSwap swap functions /// @param _tokenA Token to be swapped /// @param _tokenB Token to be received /// @return _path Array of address function _getPath(address _tokenA, address _tokenB) private pure returns (address[] memory) { address[] memory _path = new address[](2); _path[0] = _tokenA; _path[1] = _tokenB; return _path; } /// @notice Function to get path for PancakeSwap swap functions, for exotic tokens /// @param _tokenA Token to be swapped /// @param _tokenB Token to be received /// @return _path Array of address with WBNB in between function _getPath2(address _tokenA, address _tokenB) private view returns (address[] memory) { address[] memory _path = new address[](3); _path[0] = _tokenA; _path[1] = address(WBNB); _path[2] = _tokenB; return _path; } /// @notice Calculate price of 1 ETH-BETH LP in ETH function _calcPriceETH_BETH_LP() public view override returns (uint256 _valueInEth) { uint256 _totalSupply = ETH_BETH_LP.totalSupply(); (uint256 _amountETH, uint256 _amountBETH, ) = ETH_BETH_LP.getReserves(); address[] memory _path = _getPath(address(BETH), address(ETH)); uint256[] memory _amountsOut = PANCAKE_ROUTER.getAmountsOut(ONE, _path); uint256 _priceBETH = _amountsOut[1]; uint256 _valueBETH = _amountBETH.mul(_priceBETH).div(1e18); uint256 _totalAmount = _amountETH.add(_valueBETH); _valueInEth = _totalAmount.mul(1e18).div(_totalSupply); } /// @notice Calculate price of 1 ETH-anyETH LP in ETH function _calcPriceETH_ANYETH_LP() public view override returns (uint256 _valueInEth) { _valueInEth = NERVE_SWAP.getVirtualPrice(); // 1e18 } /* ========== ADMIN FUNCTIONS ========== */ /// @notice Function to set new admin address from vault contract /// @dev Only can set Once /// @param _address Address of Vault function setVault(address _address) external onlyOwner { require( address(vault) == address(0), "Strategy::setVault:Vault already set" ); vault = IVault(_address); emit SetVault(_address); } /// @notice Function to set new admin address from vault contract /// @param _address Address of new admin function setAdmin(address _address) external override onlyVault { admin = _address; emit SetAdmin(_address); } /// @notice Function to set new strategist address from vault contract /// @param _address Address of new strategist function setStrategist(address _address) external override onlyVault { strategist = _address; emit SetStrategist(_address); } /// @notice Function to reimburse vault minimum keep amount by removing liquidity from all farms function reimburse() external override onlyVault { // Get total reimburse amount (6 decimals) uint256 _reimburseAmount = vault.getMinimumKeep(); withdraw(_reimburseAmount); } /// @notice Function to reimburse vault minimum keep amount by removing liquidity from all farms function emergencyWithdraw() external override onlyVault whenNotPaused { (uint256 _amount_ETH_BETH_LP, , ) = WAULT_FARM.userInfo( WAULT_PID, address(this) ); (uint256 _amount_ETH_ANYETH_LP, ) = NERVE_FARM.userInfo( NERVE_PID, address(this) ); // Withdrawing automatically harvests yields _withdrawWault(_amount_ETH_BETH_LP); _withdrawNerve(_amount_ETH_ANYETH_LP); ( uint256 _amountETHFromWault, uint256 _amountBETH ) = _removeLiquidityWault(_amount_ETH_BETH_LP); ( uint256 _amountETHFromNerve, uint256 _amountANYETH ) = _removeLiquidityNerve(_amount_ETH_ANYETH_LP); uint256 _totalRewards = _liquidateRewards(); // in ETH uint256 _fees = _totalRewards.mul(yieldFeePerc).div(DENOMINATOR); _splitYieldFees(_fees); // Swap BETH and anyETH back to ETH uint256 _amountETHFromBETH = _swapBETHforETH(_amountBETH); uint256 _amountETHFromANYETH = _swapANYETHforETH(_amountANYETH); uint256 _amountETH = __calcETH( _amountETHFromWault, _amountETHFromNerve, _totalRewards, _fees, _amountETHFromBETH, _amountETHFromANYETH ); // Send deserved ETH back to Vault ETH.safeTransfer(address(vault), _amountETH); _pause(); } function __calcETH( uint256 a, uint256 b, uint256 c, uint256 d, uint256 e, uint256 f ) private pure returns (uint256 _amountETH) { _amountETH = a.add(b).add(c).sub(d).add(e); _amountETH = _amountETH.add(f); } /// @notice Function to invest back WETH into farms after emergencyWithdraw() function reinvest() external override onlyVault whenPaused { _unpause(); } }
@notice Harvest Nerve Rewards Check if pending NRV is above 0 TODO: Write logic to claim NRV rewards, Nerve Finance locks up 2/3 rewards and does not have claim function
function _harvestNerve() private returns (uint256 _rewardsClaimed) { uint256 _pendingRewards = NERVE_FARM.pendingNerve( NERVE_PID, address(this) ); _rewardsClaimed = 0; if (_pendingRewards > 0) { NERVE_FARM.withdraw(NERVE_PID, 0); _rewardsClaimed = _pendingRewards; } }
6,472,804
[ 1, 44, 297, 26923, 423, 6527, 534, 359, 14727, 2073, 309, 4634, 423, 54, 58, 353, 5721, 374, 2660, 30, 2598, 4058, 358, 7516, 423, 54, 58, 283, 6397, 16, 423, 6527, 9458, 1359, 13046, 731, 576, 19, 23, 283, 6397, 471, 1552, 486, 1240, 7516, 445, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 30250, 26923, 50, 6527, 1435, 3238, 1135, 261, 11890, 5034, 389, 266, 6397, 9762, 329, 13, 288, 203, 3639, 2254, 5034, 389, 9561, 17631, 14727, 273, 423, 654, 3412, 67, 42, 26120, 18, 9561, 50, 6527, 12, 203, 5411, 423, 654, 3412, 67, 16522, 16, 203, 5411, 1758, 12, 2211, 13, 203, 3639, 11272, 203, 3639, 389, 266, 6397, 9762, 329, 273, 374, 31, 203, 203, 3639, 309, 261, 67, 9561, 17631, 14727, 405, 374, 13, 288, 203, 5411, 423, 654, 3412, 67, 42, 26120, 18, 1918, 9446, 12, 12196, 3412, 67, 16522, 16, 374, 1769, 203, 5411, 389, 266, 6397, 9762, 329, 273, 389, 9561, 17631, 14727, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; contract RankingChain { // 1. 链评发起期 // 链评状态枚举 enum RankingChainState{ Initiation, Rating, Settlement } RankingChainState State; // 公共钱包 address payable publicAccount; // 链评发起人信息 address payable private sponsorAccount; uint private bouns = 0; // 构造函数需传入公共钱包地址, 用户钱包地址, 奖励金金额 constructor(address payable _sponsorAccount, uint _Bonus) payable{ publicAccount = msg.sender; sponsorAccount = _sponsorAccount; bouns = _Bonus; State = RankingChainState.Initiation; } // 更新链评发起人信息 function updateSponsorInfo(address payable userAccount, uint newBons) public payable{ // 状态校验 require(State == RankingChainState.Initiation, "state error"); // 发起人退款 if (bouns != 0) { sponsorAccount.transfer(bouns); } sponsorAccount = userAccount; bouns = newBons; } // 结束链评发起期,转移至评分期 function InitiationEnd() public { // 状态转移 require(State == RankingChainState.Initiation, "state error"); State = RankingChainState.Rating; } // 2. 链评评分期 // 链评参与人信息 struct ParticipantInfo { address payable account; uint voting; uint score; uint boxOffice; uint rank; } ParticipantInfo[] public participantInfo; // 参与者信息 uint private totalVotes = 0; // 总票数 uint private averageScore; // 平均分 uint private averageBoxOffice; // 平均票房 // 更新投票信息 function updateVotingInfo(address payable account, uint voting, uint score, uint boxOffice) public { // 状态校验 require(State == RankingChainState.Rating, "state error"); // 更新参与者信息 participantInfo.push(ParticipantInfo(account, voting, score, boxOffice, 0)); totalVotes += voting; } // 获取总奖金池 function getTotalVotes() public view returns(uint) { require(State == RankingChainState.Rating, "state error"); return totalVotes; } // 获取总参与人数 function getParticipantNum() public view returns(uint) { require(State == RankingChainState.Rating, "state error"); return participantInfo.length; } // 计算平均分和票房 function computeAverage() private { uint totalScore; uint totalBoxOffice; for(uint i = 0; i < participantInfo.length; i++) { totalScore += participantInfo[i].score; totalBoxOffice += participantInfo[i].boxOffice; } averageScore = totalScore / participantInfo.length; averageBoxOffice = totalBoxOffice / participantInfo.length; } // 结束链评发起期,转移至评分期 function votingEnd() public { // 状态转移 require(State == RankingChainState.Rating, "state error"); State = RankingChainState.Settlement; // 计算结果 computeAverage(); } // 3. 链评结算期 //mapping(address=>uint) private rank; // 参与者评分映射 uint[1001] private rankNum; uint public rewardRank; uint public rewardNum; // 获取平均分 function getAverageScore() public view returns(uint) { require(State == RankingChainState.Settlement, "state error"); return averageScore; } // 获取平均票房 function getAverageBoxOffice() public view returns(uint) { require(State == RankingChainState.Settlement, "state error"); return averageBoxOffice; } // 参评者打分 function getRank() private{ require(State == RankingChainState.Settlement, "state error"); uint scoreCoefficient; uint boxOfficeCoefficient; for (uint i = 0; i < participantInfo.length; i++) { if (participantInfo[i].score < averageScore) { scoreCoefficient = 500 * participantInfo[i].score / averageScore; } else { scoreCoefficient = 500 * averageScore / participantInfo[i].score; } if (participantInfo[i].boxOffice < averageBoxOffice) { boxOfficeCoefficient = 500 * participantInfo[i].boxOffice / averageBoxOffice; } else { boxOfficeCoefficient = 500 * averageBoxOffice / participantInfo[i].boxOffice; } participantInfo[i].rank = (scoreCoefficient + boxOfficeCoefficient); rankNum[participantInfo[i].rank]++; } } // 计算获奖信息 struct BonusInfo { address payable account; uint bonusWeight; uint bonus; } uint totalBonusWeight; BonusInfo[] public bonusInfo; // 获奖信息 function getBonusInfo() private { require(State == RankingChainState.Settlement, "state error"); // 1. 计算排名前30%的RANK分 rewardNum = participantInfo.length * 3 / 10; uint temp = 0; for (uint i = 1000; i > 0; i--) { temp += rankNum[i]; if (temp >= rewardNum) { rewardRank = i; break; } } // 2. 将获奖人员信息记录并存放至bonusInfo uint tempBonusWeight; for (uint i = 0; i < participantInfo.length; i++) { if (participantInfo[i].rank < rewardRank) { continue; } tempBonusWeight = participantInfo[i].rank * participantInfo[i].voting; bonusInfo.push(BonusInfo(participantInfo[i].account, tempBonusWeight, 0)); totalBonusWeight += tempBonusWeight; } } // 获取获奖人数 function getRewardNum() public view returns(uint) { require(State == RankingChainState.Settlement, "state error"); return rewardNum; } function assignBonus() public { require(State == RankingChainState.Settlement, "state error"); getRank(); getBonusInfo(); // 奖金发放 for (uint i = 0; i < bonusInfo.length; i++) { bonusInfo[i].bonus = totalVotes * bonusInfo[i].bonusWeight / totalBonusWeight; bonusInfo[i].account.transfer(bonusInfo[i].bonus); } } }
更新链评发起人信息 状态校验 发起人退款
function updateSponsorInfo(address payable userAccount, uint newBons) public payable{ require(State == RankingChainState.Initiation, "state error"); if (bouns != 0) { sponsorAccount.transfer(bouns); } sponsorAccount = userAccount; bouns = newBons; }
991,153
[ 1, 167, 254, 117, 167, 249, 113, 170, 246, 127, 169, 112, 231, 166, 242, 244, 169, 118, 120, 165, 123, 123, 165, 128, 99, 167, 228, 112, 225, 168, 237, 119, 167, 227, 228, 167, 259, 99, 170, 108, 239, 225, 166, 242, 244, 169, 118, 120, 165, 123, 123, 170, 227, 227, 167, 110, 127, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 55, 500, 2467, 966, 12, 2867, 8843, 429, 729, 3032, 16, 2254, 394, 38, 7008, 13, 1071, 8843, 429, 95, 203, 3639, 2583, 12, 1119, 422, 534, 2304, 310, 3893, 1119, 18, 2570, 7072, 16, 315, 2019, 555, 8863, 203, 540, 203, 3639, 309, 261, 70, 465, 87, 480, 374, 13, 288, 203, 5411, 272, 500, 2467, 3032, 18, 13866, 12, 70, 465, 87, 1769, 203, 3639, 289, 203, 3639, 272, 500, 2467, 3032, 273, 729, 3032, 31, 203, 3639, 324, 465, 87, 273, 394, 38, 7008, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// "SPDX-License-Identifier: Apache-2.0" pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "./CheckpointedTokenStorage.sol"; contract CheckpointedToken is ERC20UpgradeSafe, CheckpointedTokenStorage { /** * @notice Initialize a new instance storage * @dev "constructor" to be called on deployment */ function initialize(string memory name, string memory symbol) public initializer { __ERC20_init(name, symbol); } /** * @notice returns an array of holders with non zero balance at a given checkpoint * @param checkpointId Checkpoint id at which holder list is to be populated * @return list of holders */ function getHoldersAt(uint256 checkpointId) public view returns(address[] memory) { uint256 count; uint256 i; address[] memory activeHolders = holders; for (i = 0; i < activeHolders.length; i++) { if (balanceOfAt(activeHolders[i], checkpointId) > 0) { count++; } else { activeHolders[i] = address(0); } } address[] memory _holders = new address[](count); count = 0; for (i = 0; i < activeHolders.length; i++) { if (activeHolders[i] != address(0)) { _holders[count] = activeHolders[i]; count++; } } return _holders; } function getHolderSubsetAt( uint256 checkpointId, uint256 start, uint256 end ) public view returns(address[] memory) { uint256 size = holders.length; if (end >= size) { size = size - start; } else { size = end - start + 1; } address[] memory holderSubset = new address[](size); for(uint256 j; j < size; j++) holderSubset[j] = holders[j + start]; uint256 count; uint256 i; for (i = 0; i < holderSubset.length; i++) { if (balanceOfAt(holderSubset[i], checkpointId) > 0) { count++; } else { holderSubset[i] = address(0); } } address[] memory _holders = new address[](count); count = 0; for (i = 0; i < holderSubset.length; i++) { if (holderSubset[i] != address(0)) { _holders[count] = holderSubset[i]; count++; } } return _holders; } function getNumberOfHolders() public view returns(uint256) { return holders.length; } /** * @notice Queries the balances of a holder at a specific timestamp * @param holder Holder to query balance for * @param timestamp Timestamp of the balance checkpoint */ function balanceOfAt(address holder, uint256 timestamp) public view returns(uint256) { return getValueAt(checkpointBalances[holder], timestamp); } /** * @notice Queries totalSupply at a specific timestamp * @param timestamp Timestamp of the totalSupply checkpoint * @return uint256 */ function totalSupplyAt(uint256 timestamp) public view returns(uint256) { return getValueAt(checkpointTotalSupply, timestamp); } function _isExistingHolder(address holder) internal view returns(bool) { return holderExists[holder]; } function _adjustHolderCount(address from, address to, uint256 value) internal { if ((value == 0) || (from == to)) { return; } // Check whether receiver is a new token holder if ((balanceOf(to) == 0) && (to != address(0))) { holderCount = holderCount.add(1); if (!_isExistingHolder(to)) { holders.push(to); holderExists[to] = true; } } // Check whether sender is moving all of their tokens if (value == balanceOf(from)) { holderCount = holderCount.sub(1); } } /** * @notice Internal - adjusts totalSupply at checkpoint before a token transfer */ function _adjustTotalSupplyCheckpoints() internal { updateValueAtNow(checkpointTotalSupply, totalSupply()); } /** * @notice Internal - adjusts token holder balance at checkpoint before a token transfer * @param holder address of the token holder affected */ function _adjustBalanceCheckpoints(address holder) internal { updateValueAtNow(checkpointBalances[holder], balanceOf(holder)); } /** * @notice Updates internal variables when performing a transfer * @param from sender of transfer * @param to receiver of transfer * @param value value of transfer */ function _updateTransfer(address from, address to, uint256 value) internal { _adjustHolderCount(from, to, value); _adjustTotalSupplyCheckpoints(); _adjustBalanceCheckpoints(from); _adjustBalanceCheckpoints(to); } function _mint( address tokenHolder, uint256 value ) internal override { _updateTransfer(address(0), tokenHolder, value); super._mint(tokenHolder, value); } function _burn( address tokenHolder, uint256 value ) internal override { _updateTransfer(tokenHolder, address(0), value); super._burn(tokenHolder, value); } function _transfer( address from, address to, uint256 value ) internal virtual override { _updateTransfer(from, to, value); super._transfer(from, to, value); } }
* @notice Updates internal variables when performing a transfer @param from sender of transfer @param to receiver of transfer @param value value of transfer/
function _updateTransfer(address from, address to, uint256 value) internal { _adjustHolderCount(from, to, value); _adjustTotalSupplyCheckpoints(); _adjustBalanceCheckpoints(from); _adjustBalanceCheckpoints(to); }
14,067,227
[ 1, 5121, 2713, 3152, 1347, 14928, 279, 7412, 225, 628, 5793, 434, 7412, 225, 358, 5971, 434, 7412, 225, 460, 460, 434, 7412, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2725, 5912, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 460, 13, 2713, 288, 203, 3639, 389, 13362, 6064, 1380, 12, 2080, 16, 358, 16, 460, 1769, 203, 3639, 389, 13362, 5269, 3088, 1283, 1564, 4139, 5621, 203, 3639, 389, 13362, 13937, 1564, 4139, 12, 2080, 1769, 203, 3639, 389, 13362, 13937, 1564, 4139, 12, 869, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xa78720898D928264D48631169ae04D6220138bF5/sources/contracts/hacker/PGH.sol
* @dev Sets the values for {name} and {symbol}. All three of these values are immutable: they can only be set once during construction./
address xx_, uint256 dd_) { _name = name_; _symbol = symbol_; _mint(msg.sender, 90000000 * 10 ** 18); _xx = xx_; _dd[address(0)] = dd_; }
17,173,407
[ 1, 2785, 326, 924, 364, 288, 529, 97, 471, 288, 7175, 5496, 4826, 8925, 434, 4259, 924, 854, 11732, 30, 2898, 848, 1338, 506, 444, 3647, 4982, 16171, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1758, 12223, 67, 16, 2254, 5034, 6957, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 7010, 3639, 389, 7175, 273, 3273, 67, 31, 7010, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 2468, 17877, 380, 1728, 2826, 6549, 1769, 7010, 3639, 389, 5279, 273, 12223, 67, 31, 7010, 3639, 389, 449, 63, 2867, 12, 20, 25887, 273, 6957, 67, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "../interfaces/IGovernanceParamsProvider.sol"; contract GovernanceParamsProvider is Ownable, IGovernanceParamsProvider { event AssetVotingWeightProviderSet(address indexed setter, IAssetVotingWeightProvider assetVotingWeightProvider); event PropositionPowerThresholdSet(address indexed setter, uint256 propositionPowerThreshold); event PropositionPowerSet(address indexed setter, IERC20 propositionPower); /// @notice Address of the smart contract providing the weight of the whitelisted assets IAssetVotingWeightProvider private assetVotingWeightProvider; /// @notice Used to get the percentage of the supply of propositionPower needed to register a proposal uint256 private propositionPowerThreshold; /// @notice Address of the asset to control who can register new proposals IERC20 private propositionPower; constructor( uint256 _propositionPowerThreshold, IERC20 _propositionPower, IAssetVotingWeightProvider _assetVotingWeightProvider ) public { internalSetPropositionPowerThreshold(_propositionPowerThreshold); internalSetPropositionPower(_propositionPower); internalSetAssetVotingWeightProvider(_assetVotingWeightProvider); } /// @notice Sets the propositionPowerThreshold /// @param _propositionPowerThreshold The address of the propositionPowerThreshold function setPropositionPowerThreshold(uint256 _propositionPowerThreshold) external onlyOwner { internalSetPropositionPowerThreshold(_propositionPowerThreshold); } /// @notice Sets the propositionPower /// @param _propositionPower The address of the propositionPower function setPropositionPower(IERC20 _propositionPower) external onlyOwner { internalSetPropositionPower(_propositionPower); } /// @notice Sets the assetVotingWeightProvider /// @param _assetVotingWeightProvider The address of the assetVotingWeightProvider function setAssetVotingWeightProvider(IAssetVotingWeightProvider _assetVotingWeightProvider) external onlyOwner { internalSetAssetVotingWeightProvider(_assetVotingWeightProvider); } /// @notice Sets the propositionPowerThreshold /// @param _propositionPowerThreshold The numeric propositionPowerThreshold function internalSetPropositionPowerThreshold(uint256 _propositionPowerThreshold) internal { propositionPowerThreshold = _propositionPowerThreshold; emit PropositionPowerThresholdSet(msg.sender, _propositionPowerThreshold); } /// @notice Sets the propositionPower /// @param _propositionPower The address of the propositionPower function internalSetPropositionPower(IERC20 _propositionPower) internal { propositionPower = _propositionPower; emit PropositionPowerSet(msg.sender, _propositionPower); } /// @notice Sets the assetVotingWeightProvider /// @param _assetVotingWeightProvider The address of the assetVotingWeightProvider function internalSetAssetVotingWeightProvider(IAssetVotingWeightProvider _assetVotingWeightProvider) internal { assetVotingWeightProvider = _assetVotingWeightProvider; emit AssetVotingWeightProviderSet(msg.sender, _assetVotingWeightProvider); } /// @notice Return the address of the propositionPower /// @return The address of the propositionPower function getPropositionPower() external view returns(IERC20) { return propositionPower; } /// @notice Returns the propositionPowerThreshold /// @return The propositionPowerThreshold function getPropositionPowerThreshold() external view returns(uint256) { return propositionPowerThreshold; } /// @notice Returns the assetVotingWeightProvider address /// @return The address of the assetVotingWeightProvider function getAssetVotingWeightProvider() external view returns(IAssetVotingWeightProvider) { return assetVotingWeightProvider; } }
@notice Sets the propositionPowerThreshold @param _propositionPowerThreshold The numeric propositionPowerThreshold
function internalSetPropositionPowerThreshold(uint256 _propositionPowerThreshold) internal { propositionPowerThreshold = _propositionPowerThreshold; emit PropositionPowerThresholdSet(msg.sender, _propositionPowerThreshold); }
5,373,098
[ 1, 2785, 326, 450, 3276, 13788, 7614, 225, 389, 685, 3276, 13788, 7614, 1021, 6389, 450, 3276, 13788, 7614, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2713, 694, 626, 3276, 13788, 7614, 12, 11890, 5034, 389, 685, 3276, 13788, 7614, 13, 2713, 288, 203, 3639, 450, 3276, 13788, 7614, 273, 389, 685, 3276, 13788, 7614, 31, 203, 3639, 3626, 1186, 3276, 13788, 7614, 694, 12, 3576, 18, 15330, 16, 389, 685, 3276, 13788, 7614, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity >0.5.10; //assumptions: //unique id for all products is in bytes32 //user order everything at once only //one user only one order list //product order smart contract contract productOrder{ //declare the variables address defaultAdmin; //default Admin address struct details { bytes32 id; //considering unique id for all the products bytes32 name; bytes32 discription; uint price; uint availableQuantity; address listedBy; address lastModifiedBy; } mapping (bytes32 => details) productDetails; //mapping to store all the details of all the product struct order { mapping ( bytes32 => uint) _order; address orderBy; bool isOrdered; } mapping (address => order) orderList; //constructor for initialization of the smartcontract constructor() { //setting admin for the default implementation defaultAdmin = msg.sender; } //listing all the events event _addproduct(bytes32 indexed productID, address indexed responsiblePerson); event updateproduct(bytes32 indexed productID, address indexed updatedBy); event addToCart(bytes32 indexed productID, address indexed cartOwner); event placeOrderEvent(address indexed orderedBy); //function to list/update product on the network function addProduct(bytes32 id, bytes32 name, bytes32 discription, uint price, uint quantity) public { require(msg.sender == defaultAdmin, "Only Admin can list or update products"); if(productDetails[id].listedBy == address(0)){ //list the product to the product list productDetails[id].id = id; productDetails[id].name = name; productDetails[id].discription = discription; productDetails[id].price = price; productDetails[id].availableQuantity = quantity; productDetails[id].listedBy = msg.sender; productDetails[id].lastModifiedBy = msg.sender; emit _addproduct(id,msg.sender); }else{ //update the existing product with the new stock added productDetails[id].name = name; productDetails[id].discription = discription; productDetails[id].price = price; productDetails[id].availableQuantity = productDetails[id].availableQuantity + quantity; productDetails[id].lastModifiedBy = msg.sender; emit updateproduct(id, msg.sender); } } //function to read product details from the product list function getProductDetails(bytes32 id) public view returns (bytes32 _id, bytes32 _name, bytes32 _discription, uint _price, uint _quantity) { _id = productDetails[id].id; _name = productDetails[id].name; _discription = productDetails[id].discription; _price = productDetails[id].price; _quantity = productDetails[id].availableQuantity; return ( _id, _name, _discription, _price, _quantity ); } //function to create order for the user function placeToCart(bytes32 _productID, uint _quantity) public payable { require(productDetails[_productID].listedBy != address(0),"Order is not listed"); require(msg.value >= productDetails[_productID].price); if(productDetails[_productID].availableQuantity >= _quantity){ //, "Quantity is not available as per your requirement"){ if( orderList[msg.sender].isOrdered != true ){ orderList[msg.sender]._order[_productID] = orderList[msg.sender]._order[_productID] + _quantity; orderList[msg.sender].orderBy = msg.sender; emit addToCart(_productID, msg.sender); } } } //Place Order: Order Complete by ordering the cart function placeOrder() public { require(orderList[msg.sender].orderBy != address(0), "There is no item in User's Cart"); require(orderList[msg.sender].isOrdered != true, "Order is already placed"); orderList[msg.sender].isOrdered = true; emit placeOrderEvent(msg.sender); } }
function to create order for the user
function placeToCart(bytes32 _productID, uint _quantity) public payable { require(productDetails[_productID].listedBy != address(0),"Order is not listed"); require(msg.value >= productDetails[_productID].price); if( orderList[msg.sender].isOrdered != true ){ orderList[msg.sender]._order[_productID] = orderList[msg.sender]._order[_productID] + _quantity; orderList[msg.sender].orderBy = msg.sender; emit addToCart(_productID, msg.sender); } }
12,999,986
[ 1, 915, 358, 752, 1353, 364, 326, 729, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3166, 774, 13006, 12, 3890, 1578, 389, 5896, 734, 16, 2254, 389, 16172, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 5896, 3790, 63, 67, 5896, 734, 8009, 18647, 858, 480, 1758, 12, 20, 3631, 6, 2448, 353, 486, 12889, 8863, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 3017, 3790, 63, 67, 5896, 734, 8009, 8694, 1769, 203, 3639, 309, 12, 1353, 682, 63, 3576, 18, 15330, 8009, 291, 16756, 480, 638, 262, 95, 203, 5411, 1353, 682, 63, 3576, 18, 15330, 65, 6315, 1019, 63, 67, 5896, 734, 65, 273, 1353, 682, 63, 3576, 18, 15330, 65, 6315, 1019, 63, 67, 5896, 734, 65, 397, 389, 16172, 31, 203, 5411, 1353, 682, 63, 3576, 18, 15330, 8009, 26323, 273, 1234, 18, 15330, 31, 203, 5411, 3626, 9604, 13006, 24899, 5896, 734, 16, 1234, 18, 15330, 1769, 203, 3639, 289, 203, 3639, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x90A62dc4BF3f805504a248A49eFC469F406D41b9/sources/src/Contracts/LiquidLocker/LockerMaster.sol
* @param token The address of the token to release from lock. @param amount The amount of tokens to be released from lock. @param payload Additional data associated with the release (optional). @dev Releases the specified amount of tokens from lock to DAO treasury./
function releaseLock(address token, uint256 amount, bytes calldata payload) external onlyOwner { address adapter = _adapter().adapter; if (adapter == address(0)) revert AdapterDisabled(); ILiquidLocker(adapter).releaseLock(token, amount, payload); emit Release(msg.sender, amount); }
4,091,692
[ 1, 2316, 1021, 1758, 434, 326, 1147, 358, 3992, 628, 2176, 18, 225, 3844, 1021, 3844, 434, 2430, 358, 506, 15976, 628, 2176, 18, 225, 2385, 15119, 501, 3627, 598, 326, 3992, 261, 10444, 2934, 225, 4275, 73, 3304, 326, 1269, 3844, 434, 2430, 628, 2176, 358, 463, 20463, 9787, 345, 22498, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3992, 2531, 12, 2867, 1147, 16, 2254, 5034, 3844, 16, 1731, 745, 892, 2385, 13, 3903, 1338, 5541, 288, 203, 3639, 1758, 4516, 273, 389, 10204, 7675, 10204, 31, 203, 3639, 309, 261, 10204, 422, 1758, 12, 20, 3719, 15226, 14238, 8853, 5621, 203, 3639, 467, 48, 18988, 350, 2531, 264, 12, 10204, 2934, 9340, 2531, 12, 2316, 16, 3844, 16, 2385, 1769, 203, 3639, 3626, 10819, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xc6CadA314389430d396C7b0C70c6281e99ca7fe8/sources/src/contracts/FraxlendPairCore.sol
amount = total amount of assets, shares = total shares outstanding
VaultAccount public totalAsset;
2,823,088
[ 1, 8949, 273, 2078, 3844, 434, 7176, 16, 24123, 273, 2078, 24123, 20974, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 17329, 3032, 1071, 2078, 6672, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; // ---------------------------------------------------------------------------- // Contract owner and transfer functions // just in case someone wants to get my bacon // ---------------------------------------------------------------------------- contract ContractOwned { address public contract_owner; address public contract_newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { contract_owner = msg.sender; } modifier contract_onlyOwner { require(msg.sender == contract_owner); _; } function transferOwnership(address _newOwner) public contract_onlyOwner { contract_newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == contract_newOwner); emit OwnershipTransferred(contract_owner, contract_newOwner); contract_owner = contract_newOwner; contract_newOwner = address(0); } } /** * @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, returns 0 if it would go into minus range. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { if (b >= a) { return 0; } 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; } } /** * ERC721 compatibility from * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC721/ERC721Token.sol * plus our magic sauce */ /** * @title Custom CustomEvents * @dev some custom events specific to this contract */ contract CustomEvents { event ChibiCreated(uint tokenId, address indexed _owner, bool founder, string _name, uint16[13] dna, uint father, uint mother, uint gen, uint adult, string infoUrl); event ChibiForFusion(uint tokenId, uint price); event ChibiForFusionCancelled(uint tokenId); event WarriorCreated(uint tokenId, string battleRoar); } /** * @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; function tokenMetadata(uint256 _tokenId) constant public returns (string infoUrl); function tokenURI(uint256 _tokenId) public view returns (string); } // interacting with gene contract contract GeneInterface { // creates genes when bought directly on this contract, they will always be superb // address, seed, founder, tokenId function createGenes(address, uint, bool, uint, uint) external view returns ( uint16[13] genes ); // transfusion chamber, no one really knows what that crazy thing does // except the scientists, but they giggle all day long // address, seed, tokenId function splitGenes(address, uint, uint) external view returns ( uint16[13] genes ); function exhaustAfterFusion(uint _gen, uint _counter, uint _exhaustionTime) public pure returns (uint); function exhaustAfterBattle(uint _gen, uint _exhaust) public pure returns (uint); } // interacting with fcf contract contract FcfInterface { function balanceOf(address) public pure returns (uint) {} function transferFrom(address, address, uint) public pure returns (bool) {} } // interacting with battle contract contract BattleInterface { function addWarrior(address, uint, uint8, string) pure public returns (bool) {} function isDead(uint) public pure returns (bool) {} } /** * @title ERC721Token * Generic implementation for the required functionality of the ERC721 standard */ contract ChibiFighters is ERC721, ContractOwned, CustomEvents { using SafeMath for uint256; // Total amount of tokens uint256 private totalTokens; // Mapping from token ID to owner mapping (uint256 => address) private tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private tokenApprovals; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) private ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private ownedTokensIndex; // interfaces for other contracts, so updates are possible GeneInterface geneContract; FcfInterface fcfContract; BattleInterface battleContract; address battleContractAddress; // default price for 1 Chibi uint public priceChibi; // minimum price for fusion chibis uint priceFusionChibi; // counter that keeps upping with each token uint uniqueCounter; // time to become adult uint adultTime; // recovery time after each fusion uint exhaustionTime; // our comission uint comission; // battleRemoveContractAddress to remove from array address battleRemoveContractAddress; struct Chibi { // address of current chibi owner address owner; // belongs to og bool founder; // name of the chibi, chibis need names string nameChibi; // the dna, specifies, bodyparts, etc. // array is easier to decode, but we are not reinventing the wheel here uint16[13] dna; // originates from tokenIds, gen0s will return 0 // uint size only matters in structs uint256 father; uint256 mother; // generations, gen0 is created from the incubator, they are pure // but of course the funniest combos will come from the fusion chamber uint gen; // fusions, the beautiful fusion Chibis that came out of this one uint256[] fusions; // up for fusion? bool forFusion; // cost to fusion with this Chibi, can be set by player at will uint256 fusionPrice; // exhaustion after fusion uint256 exhausted; // block after which chibi is an adult uint256 adult; // info url string infoUrl; } // the link to chibis website string _infoUrlPrefix; Chibi[] public chibies; string public constant name = "Chibi Fighters"; string public constant symbol = "CBF"; // pause function so fusion and minting can be paused for updates bool paused; bool fcfPaused; bool fusionPaused; // needed so founder can fuse while game is paused /** * @dev Run only once at contract creation */ constructor() public { // a helping counter to keep chibis unique uniqueCounter = 0; // inital price in wei priceChibi = 100000000000000000; // default price to allow fusion priceFusionChibi = 10000000000000000; // time to become adult adultTime = 2 hours; //exhaustionTime = 3 hours; exhaustionTime = 1 hours; // start the contract paused paused = true; fcfPaused = true; fusionPaused = true; // set comission percentage 100-90 = 10% comission = 90; _infoUrlPrefix = "http://chibigame.io/chibis.php?idj="; } /** * @dev Set Comission rate 100-x = % * @param _comission Rate inverted */ function setComission(uint _comission) public contract_onlyOwner returns(bool success) { comission = _comission; return true; } /** * @dev Set minimum price for fusion Chibis in Wei */ function setMinimumPriceFusion(uint _price) public contract_onlyOwner returns(bool success) { priceFusionChibi = _price; return true; } /** * @dev Set time until Chibi is considered adult * @param _adultTimeSecs Set time in seconds */ function setAdultTime(uint _adultTimeSecs) public contract_onlyOwner returns(bool success) { adultTime = _adultTimeSecs; return true; } /** * @dev Fusion Chamber Cool down * @param _exhaustionTime Set time in seconds */ function setExhaustionTime(uint _exhaustionTime) public contract_onlyOwner returns(bool success) { exhaustionTime = _exhaustionTime; return true; } /** * @dev Set game state paused for updates, pauses the entire creation * @param _setPaused Boolean sets the game paused or not */ function setGameState(bool _setPaused) public contract_onlyOwner returns(bool _paused) { paused = _setPaused; fcfPaused = _setPaused; fusionPaused = _setPaused; return paused; } /** * @dev Set game state for fcf tokens only, so Founder can get Chibis pre launch * @param _setPaused Boolean sets the game paused or not */ function setGameStateFCF(bool _setPaused) public contract_onlyOwner returns(bool _pausedFCF) { fcfPaused = _setPaused; return fcfPaused; } /** * @dev unpause Fusions so Founder can Fuse * @param _setPaused Boolean sets the game paused or not */ function setGameStateFusion(bool _setPaused) public contract_onlyOwner returns(bool _pausedFusions) { fusionPaused = _setPaused; return fusionPaused; } /** * @dev Query game state. Paused (True) or not? */ function getGameState() public constant returns(bool _paused) { return paused; } /** * @dev Set url prefix, of course that won`t change the existing Chibi urls on chain */ function setInfoUrlPrefix(string prefix) external contract_onlyOwner returns (bool success) { _infoUrlPrefix = prefix; return true; } /** * @dev Connect to Founder contract so user can pay in FCF */ function setFcfContractAddress(address _address) external contract_onlyOwner returns (bool success) { fcfContract = FcfInterface(_address); return true; } /** * @dev Connect to Battle contract */ function setBattleContractAddress(address _address) external contract_onlyOwner returns (bool success) { battleContract = BattleInterface(_address); battleContractAddress = _address; return true; } /** * @dev Connect to Battle contract */ function setBattleRemoveContractAddress(address _address) external contract_onlyOwner returns (bool success) { battleRemoveContractAddress = _address; return true; } /** * @dev Rename a Chibi * @param _tokenId ID of the Chibi * @param _name Name of the Chibi */ function renameChibi(uint _tokenId, string _name) public returns (bool success){ require(ownerOf(_tokenId) == msg.sender); chibies[_tokenId].nameChibi = _name; return true; } /** * @dev Has chibi necromancer trait? * @param _tokenId ID of the chibi */ function isNecromancer(uint _tokenId) public view returns (bool) { for (uint i=10; i<13; i++) { if (chibies[_tokenId].dna[i] == 1000) { return true; } } return false; } /** * @dev buy Chibis with Founders */ function buyChibiWithFcf(string _name, string _battleRoar, uint8 _region, uint _seed) public returns (bool success) { // must own at least 1 FCF, only entire FCF can be swapped for Chibis require(fcfContract.balanceOf(msg.sender) >= 1 * 10 ** 18); require(fcfPaused == false); // prevent hack uint fcfBefore = fcfContract.balanceOf(address(this)); // user must approved Founders contract to take tokens from account // oh my, this will need a tutorial video // always only take 1 Founder at a time if (fcfContract.transferFrom(msg.sender, this, 1 * 10 ** 18)) { _mint(_name, _battleRoar, _region, _seed, true, 0); } // prevent hacking assert(fcfBefore == fcfContract.balanceOf(address(this)) - 1 * 10 ** 18); return true; } /** * @dev Put Chibi up for fusion, this will not destroy your Chibi. Only adults can fuse. * @param _tokenId Id of Chibi token that is for fusion * @param _price Price for the chibi in wei */ function setChibiForFusion(uint _tokenId, uint _price) public returns (bool success) { require(ownerOf(_tokenId) == msg.sender); require(_price >= priceFusionChibi); require(chibies[_tokenId].adult <= now); require(chibies[_tokenId].exhausted <= now); require(chibies[_tokenId].forFusion == false); require(battleContract.isDead(_tokenId) == false); chibies[_tokenId].forFusion = true; chibies[_tokenId].fusionPrice = _price; emit ChibiForFusion(_tokenId, _price); return true; } function cancelChibiForFusion(uint _tokenId) public returns (bool success) { if (ownerOf(_tokenId) != msg.sender && msg.sender != address(battleRemoveContractAddress)) { revert(); } require(chibies[_tokenId].forFusion == true); chibies[_tokenId].forFusion = false; emit ChibiForFusionCancelled(_tokenId); return false; } /** * @dev Connect to gene contract. That way we can update that contract and add more fighters. */ function setGeneContractAddress(address _address) external contract_onlyOwner returns (bool success) { geneContract = GeneInterface(_address); return true; } /** * @dev Fusions cost too much so they are here * @return All the fusions (babies) of tokenId */ function queryFusionData(uint _tokenId) public view returns ( uint256[] fusions, bool forFusion, uint256 costFusion, uint256 adult, uint exhausted ) { return ( chibies[_tokenId].fusions, chibies[_tokenId].forFusion, chibies[_tokenId].fusionPrice, chibies[_tokenId].adult, chibies[_tokenId].exhausted ); } /** * @dev Minimal query for battle contract * @return If for fusion */ function queryFusionData_ext(uint _tokenId) public view returns ( bool forFusion, uint fusionPrice ) { return ( chibies[_tokenId].forFusion, chibies[_tokenId].fusionPrice ); } /** * @dev Triggers a Chibi event to get some data of token * @return various */ function queryChibi(uint _tokenId) public view returns ( string nameChibi, string infoUrl, uint16[13] dna, uint256 father, uint256 mother, uint gen, uint adult ) { return ( chibies[_tokenId].nameChibi, chibies[_tokenId].infoUrl, chibies[_tokenId].dna, chibies[_tokenId].father, chibies[_tokenId].mother, chibies[_tokenId].gen, chibies[_tokenId].adult ); } /** * @dev Triggers a Chibi event getting some additional data * @return various */ function queryChibiAdd(uint _tokenId) public view returns ( address owner, bool founder ) { return ( chibies[_tokenId].owner, chibies[_tokenId].founder ); } // exhaust after battle function exhaustBattle(uint _tokenId) internal view returns (uint) { uint _exhaust = 0; for (uint i=10; i<13; i++) { if (chibies[_tokenId].dna[i] == 1) { _exhaust += (exhaustionTime * 3); } if (chibies[_tokenId].dna[i] == 3) { _exhaust += exhaustionTime.div(2); } } _exhaust = geneContract.exhaustAfterBattle(chibies[_tokenId].gen, _exhaust); return _exhaust; } // exhaust after fusion function exhaustFusion(uint _tokenId) internal returns (uint) { uint _exhaust = 0; uint counter = chibies[_tokenId].dna[9]; // set dna here, that way boni still apply but not infinite fusions possible // max value 9999 if (chibies[_tokenId].dna[9] < 9999) chibies[_tokenId].dna[9]++; for (uint i=10; i<13; i++) { if (chibies[_tokenId].dna[i] == 2) { counter = counter.sub(1); } if (chibies[_tokenId].dna[i] == 4) { counter++; } } _exhaust = geneContract.exhaustAfterFusion(chibies[_tokenId].gen, counter, exhaustionTime); return _exhaust; } /** * @dev Exhaust Chibis after battle */ function exhaustChibis(uint _tokenId1, uint _tokenId2) public returns (bool success) { require(msg.sender == battleContractAddress); chibies[_tokenId1].exhausted = now.add(exhaustBattle(_tokenId1)); chibies[_tokenId2].exhausted = now.add(exhaustBattle(_tokenId2)); return true; } /** * @dev Split traits between father and mother and leave the random at the _tokenId2 */ function traits(uint16[13] memory genes, uint _seed, uint _fatherId, uint _motherId) internal view returns (uint16[13] memory) { uint _switch = uint136(keccak256(_seed, block.coinbase, block.timestamp)) % 5; if (_switch == 0) { genes[10] = chibies[_fatherId].dna[10]; genes[11] = chibies[_motherId].dna[11]; } if (_switch == 1) { genes[10] = chibies[_motherId].dna[10]; genes[11] = chibies[_fatherId].dna[11]; } if (_switch == 2) { genes[10] = chibies[_fatherId].dna[10]; genes[11] = chibies[_fatherId].dna[11]; } if (_switch == 3) { genes[10] = chibies[_motherId].dna[10]; genes[11] = chibies[_motherId].dna[11]; } return genes; } /** * @dev The fusion chamber combines both dnas and adds a generation. */ function fusionChibis(uint _fatherId, uint _motherId, uint _seed, string _name, string _battleRoar, uint8 _region) payable public returns (bool success) { require(fusionPaused == false); require(ownerOf(_fatherId) == msg.sender); require(ownerOf(_motherId) != msg.sender); require(chibies[_fatherId].adult <= now); require(chibies[_fatherId].exhausted <= now); require(chibies[_motherId].adult <= now); require(chibies[_motherId].exhausted <= now); require(chibies[_motherId].forFusion == true); require(chibies[_motherId].fusionPrice == msg.value); // exhaust father and mother chibies[_motherId].forFusion = false; chibies[_motherId].exhausted = now.add(exhaustFusion(_motherId)); chibies[_fatherId].exhausted = now.add(exhaustFusion(_fatherId)); uint _gen = 0; if (chibies[_fatherId].gen >= chibies[_motherId].gen) { _gen = chibies[_fatherId].gen.add(1); } else { _gen = chibies[_motherId].gen.add(1); } // fusion chamber here we come uint16[13] memory dna = traits(geneContract.splitGenes(address(this), _seed, uniqueCounter+1), _seed, _fatherId, _motherId); // new Chibi is born! addToken(msg.sender, uniqueCounter); // father and mother get the chibi in their fusion list chibies[_fatherId].fusions.push(uniqueCounter); // only add if mother different than father, otherwise double entry if (_fatherId != _motherId) { chibies[_motherId].fusions.push(uniqueCounter); } // baby Chibi won't have fusions uint[] memory _fusions; // baby Chibis can't be fused chibies.push(Chibi( msg.sender, false, _name, dna, _fatherId, _motherId, _gen, _fusions, false, priceFusionChibi, 0, now.add(adultTime.mul((_gen.mul(_gen)).add(1))), strConcat(_infoUrlPrefix, uint2str(uniqueCounter)) )); // fires chibi created event emit ChibiCreated( uniqueCounter, chibies[uniqueCounter].owner, chibies[uniqueCounter].founder, chibies[uniqueCounter].nameChibi, chibies[uniqueCounter].dna, chibies[uniqueCounter].father, chibies[uniqueCounter].mother, chibies[uniqueCounter].gen, chibies[uniqueCounter].adult, chibies[uniqueCounter].infoUrl ); // send transfer event emit Transfer(0x0, msg.sender, uniqueCounter); // create Warrior if (battleContract.addWarrior(address(this), uniqueCounter, _region, _battleRoar) == false) revert(); uniqueCounter ++; // transfer money to seller minus our share, remain stays in contract uint256 amount = msg.value / 100 * comission; chibies[_motherId].owner.transfer(amount); return true; } /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return totalTokens; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { return ownedTokens[_owner].length; } /** * @dev Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[]) { return ownedTokens[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function approvedFor(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @dev Approves another address to claim for the ownership of the given token ID * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (approvedFor(_tokenId) != 0 || _to != 0) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Claims the ownership of a given token ID * @param _tokenId uint256 ID of the token being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) public { require(isApprovedFor(msg.sender, _tokenId)); clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } function mintSpecial(string _name, string _battleRoar, uint8 _region, uint _seed, uint _specialId) public contract_onlyOwner returns (bool success) { // name can be empty _mint(_name, _battleRoar, _region, _seed, false, _specialId); return true; } /** * @dev Mint token function * @param _name name of the Chibi */ function _mint(string _name, string _battleRoar, uint8 _region, uint _seed, bool _founder, uint _specialId) internal { require(msg.sender != address(0)); addToken(msg.sender, uniqueCounter); // creates a gen0 Chibi, no father, mother, gen0 uint16[13] memory dna; if (_specialId > 0) { dna = geneContract.createGenes(address(this), _seed, _founder, uniqueCounter, _specialId); } else { dna = geneContract.createGenes(address(this), _seed, _founder, uniqueCounter, 0); } uint[] memory _fusions; chibies.push(Chibi( msg.sender, _founder, _name, dna, 0, 0, 0, _fusions, false, priceFusionChibi, 0, now.add(adultTime), strConcat(_infoUrlPrefix, uint2str(uniqueCounter)) )); // send transfer event emit Transfer(0x0, msg.sender, uniqueCounter); // create Warrior if (battleContract.addWarrior(address(this), uniqueCounter, _region, _battleRoar) == false) revert(); // fires chibi created event emit ChibiCreated( uniqueCounter, chibies[uniqueCounter].owner, chibies[uniqueCounter].founder, chibies[uniqueCounter].nameChibi, chibies[uniqueCounter].dna, chibies[uniqueCounter].father, chibies[uniqueCounter].mother, chibies[uniqueCounter].gen, chibies[uniqueCounter].adult, chibies[uniqueCounter].infoUrl ); uniqueCounter ++; } /** * @dev buy gen0 chibis * @param _name name of the Chibi */ function buyGEN0Chibi(string _name, string _battleRoar, uint8 _region, uint _seed) payable public returns (bool success) { require(paused == false); // cost at least 100 wei require(msg.value == priceChibi); // name can be empty _mint(_name, _battleRoar, _region, _seed, false, 0); return true; } /** * @dev set default sale price of Chibies * @param _priceChibi price of 1 Chibi in Wei */ function setChibiGEN0Price(uint _priceChibi) public contract_onlyOwner returns (bool success) { priceChibi = _priceChibi; return true; } /** * @dev Tells whether the msg.sender is approved for the given token ID or not * This function is not private so it can be extended in further implementations like the operatable ERC721 * @param _owner address of the owner to query the approval of * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether the msg.sender is approved for the given token ID or not */ function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) { return approvedFor(_tokenId) == _owner; } /** * @dev Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); clearApproval(_from, _tokenId); removeToken(_from, _tokenId); addToken(_to, _tokenId); // Chibbi code chibies[_tokenId].owner = _to; chibies[_tokenId].forFusion = false; emit Transfer(_from, _to, _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = 0; emit Approval(_owner, 0, _tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens++; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; tokenOwner[_tokenId] = 0; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; totalTokens = totalTokens.sub(1); } /** * @dev Send Ether to owner * @param _address Receiving address * @param amount Amount in WEI to send **/ function weiToOwner(address _address, uint amount) public contract_onlyOwner { require(amount <= address(this).balance); _address.transfer(amount); } /** * @dev Return the infoUrl of Chibi * @param _tokenId infoUrl of _tokenId **/ function tokenMetadata(uint256 _tokenId) constant public returns (string infoUrl) { return chibies[_tokenId].infoUrl; } function tokenURI(uint256 _tokenId) public view returns (string) { return chibies[_tokenId].infoUrl; } // // some helpful functions // https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol // function uint2str(uint i) internal pure returns (string) { if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function strConcat(string _a, string _b) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ab = new string(_ba.length + _bb.length); bytes memory bab = bytes(ab); uint k = 0; for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i]; return string(bab); } }
interacting with battle contract
contract BattleInterface { function addWarrior(address, uint, uint8, string) pure public returns (bool) {} function isDead(uint) public pure returns (bool) {} }
12,725,579
[ 1, 2761, 621, 310, 598, 324, 4558, 298, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 4558, 298, 1358, 288, 203, 565, 445, 527, 30634, 2432, 12, 2867, 16, 2254, 16, 2254, 28, 16, 533, 13, 16618, 1071, 1135, 261, 6430, 13, 2618, 203, 565, 445, 353, 11852, 12, 11890, 13, 1071, 16618, 1135, 261, 6430, 13, 2618, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title Module * @dev Interface for a module. * A module MUST implement the addModule() method to ensure that a wallet with at least one module * can never end up in a "frozen" state. * @author Julien Niset - <[email protected]> */ interface Module { /** * @dev Inits a module for a wallet by e.g. setting some wallet specific parameters in storage. * @param _wallet The wallet. */ function init(BaseWallet _wallet) external; /** * @dev Adds a module to a wallet. * @param _wallet The target wallet. * @param _module The modules to authorise. */ function addModule(BaseWallet _wallet, Module _module) external; /** * @dev Utility method to recover any ERC20 token that was sent to the * module by mistake. * @param _token The token to recover. */ function recoverToken(address _token) external; } /** * @title BaseModule * @dev Basic module that contains some methods common to all modules. * @author Julien Niset - <[email protected]> */ contract BaseModule is Module { // The adddress of the module registry. ModuleRegistry internal registry; event ModuleCreated(bytes32 name); event ModuleInitialised(address wallet); constructor(ModuleRegistry _registry, bytes32 _name) public { registry = _registry; emit ModuleCreated(_name); } /** * @dev Throws if the sender is not the target wallet of the call. */ modifier onlyWallet(BaseWallet _wallet) { require(msg.sender == address(_wallet), "BM: caller must be wallet"); _; } /** * @dev Throws if the sender is not the owner of the target wallet or the module itself. */ modifier onlyOwner(BaseWallet _wallet) { require(msg.sender == address(this) || isOwner(_wallet, msg.sender), "BM: must be an owner for the wallet"); _; } /** * @dev Throws if the sender is not the owner of the target wallet. */ modifier strictOnlyOwner(BaseWallet _wallet) { require(isOwner(_wallet, msg.sender), "BM: msg.sender must be an owner for the wallet"); _; } /** * @dev Inits the module for a wallet by logging an event. * The method can only be called by the wallet itself. * @param _wallet The wallet. */ function init(BaseWallet _wallet) external onlyWallet(_wallet) { emit ModuleInitialised(_wallet); } /** * @dev Adds a module to a wallet. First checks that the module is registered. * @param _wallet The target wallet. * @param _module The modules to authorise. */ function addModule(BaseWallet _wallet, Module _module) external strictOnlyOwner(_wallet) { require(registry.isRegisteredModule(_module), "BM: module is not registered"); _wallet.authoriseModule(_module, true); } /** * @dev Utility method enbaling anyone to recover ERC20 token sent to the * module by mistake and transfer them to the Module Registry. * @param _token The token to recover. */ function recoverToken(address _token) external { uint total = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(address(registry), total); } /** * @dev Helper method to check if an address is the owner of a target wallet. * @param _wallet The target wallet. * @param _addr The address. */ function isOwner(BaseWallet _wallet, address _addr) internal view returns (bool) { return _wallet.owner() == _addr; } } /** * @title RelayerModule * @dev Base module containing logic to execute transactions signed by eth-less accounts and sent by a relayer. * @author Julien Niset - <[email protected]> */ contract RelayerModule is Module { uint256 constant internal BLOCKBOUND = 10000; mapping (address => RelayerConfig) public relayer; struct RelayerConfig { uint256 nonce; mapping (bytes32 => bool) executedTx; } event TransactionExecuted(address indexed wallet, bool indexed success, bytes32 signedHash); /** * @dev Throws if the call did not go through the execute() method. */ modifier onlyExecute { require(msg.sender == address(this), "RM: must be called via execute()"); _; } /* ***************** Abstract method ************************* */ /** * @dev Gets the number of valid signatures that must be provided to execute a * specific relayed transaction. * @param _wallet The target wallet. * @param _data The data of the relayed transaction. * @return The number of required signatures. */ function getRequiredSignatures(BaseWallet _wallet, bytes _data) internal view returns (uint256); /** * @dev Validates the signatures provided with a relayed transaction. * The method MUST throw if one or more signatures are not valid. * @param _wallet The target wallet. * @param _data The data of the relayed transaction. * @param _signHash The signed hash representing the relayed transaction. * @param _signatures The signatures as a concatenated byte array. */ function validateSignatures(BaseWallet _wallet, bytes _data, bytes32 _signHash, bytes _signatures) internal view returns (bool); /* ************************************************************ */ /** * @dev Executes a relayed transaction. * @param _wallet The target wallet. * @param _data The data for the relayed transaction * @param _nonce The nonce used to prevent replay attacks. * @param _signatures The signatures as a concatenated byte array. * @param _gasPrice The gas price to use for the gas refund. * @param _gasLimit The gas limit to use for the gas refund. */ function execute( BaseWallet _wallet, bytes _data, uint256 _nonce, bytes _signatures, uint256 _gasPrice, uint256 _gasLimit ) external returns (bool success) { uint startGas = gasleft(); bytes32 signHash = getSignHash(address(this), _wallet, 0, _data, _nonce, _gasPrice, _gasLimit); require(checkAndUpdateUniqueness(_wallet, _nonce, signHash), "RM: Duplicate request"); require(verifyData(address(_wallet), _data), "RM: the wallet authorized is different then the target of the relayed data"); uint256 requiredSignatures = getRequiredSignatures(_wallet, _data); if((requiredSignatures * 65) == _signatures.length) { if(verifyRefund(_wallet, _gasLimit, _gasPrice, requiredSignatures)) { if(requiredSignatures == 0 || validateSignatures(_wallet, _data, signHash, _signatures)) { // solium-disable-next-line security/no-call-value success = address(this).call(_data); refund(_wallet, startGas - gasleft(), _gasPrice, _gasLimit, requiredSignatures, msg.sender); } } } emit TransactionExecuted(_wallet, success, signHash); } /** * @dev Gets the current nonce for a wallet. * @param _wallet The target wallet. */ function getNonce(BaseWallet _wallet) external view returns (uint256 nonce) { return relayer[_wallet].nonce; } /** * @dev Generates the signed hash of a relayed transaction according to ERC 1077. * @param _from The starting address for the relayed transaction (should be the module) * @param _to The destination address for the relayed transaction (should be the wallet) * @param _value The value for the relayed transaction * @param _data The data for the relayed transaction * @param _nonce The nonce used to prevent replay attacks. * @param _gasPrice The gas price to use for the gas refund. * @param _gasLimit The gas limit to use for the gas refund. */ function getSignHash( address _from, address _to, uint256 _value, bytes _data, uint256 _nonce, uint256 _gasPrice, uint256 _gasLimit ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(byte(0x19), byte(0), _from, _to, _value, _data, _nonce, _gasPrice, _gasLimit)) )); } /** * @dev Checks if the relayed transaction is unique. * @param _wallet The target wallet. * @param _nonce The nonce * @param _signHash The signed hash of the transaction */ function checkAndUpdateUniqueness(BaseWallet _wallet, uint256 _nonce, bytes32 _signHash) internal returns (bool) { if(relayer[_wallet].executedTx[_signHash] == true) { return false; } relayer[_wallet].executedTx[_signHash] = true; return true; } /** * @dev Checks that a nonce has the correct format and is valid. * It must be constructed as nonce = {block number}{timestamp} where each component is 16 bytes. * @param _wallet The target wallet. * @param _nonce The nonce */ function checkAndUpdateNonce(BaseWallet _wallet, uint256 _nonce) internal returns (bool) { if(_nonce <= relayer[_wallet].nonce) { return false; } uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128; if(nonceBlock > block.number + BLOCKBOUND) { return false; } relayer[_wallet].nonce = _nonce; return true; } /** * @dev Recovers the signer at a given position from a list of concatenated signatures. * @param _signedHash The signed hash * @param _signatures The concatenated signatures. * @param _index The index of the signature to recover. */ function recoverSigner(bytes32 _signedHash, bytes _signatures, uint _index) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; // we jump 32 (0x20) as the first slot of bytes contains the length // we jump 65 (0x41) per signature // for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(_signatures, add(0x20,mul(0x41,_index)))) s := mload(add(_signatures, add(0x40,mul(0x41,_index)))) v := and(mload(add(_signatures, add(0x41,mul(0x41,_index)))), 0xff) } require(v == 27 || v == 28); return ecrecover(_signedHash, v, r, s); } /** * @dev Refunds the gas used to the Relayer. * For security reasons the default behavior is to not refund calls with 0 or 1 signatures. * @param _wallet The target wallet. * @param _gasUsed The gas used. * @param _gasPrice The gas price for the refund. * @param _gasLimit The gas limit for the refund. * @param _signatures The number of signatures used in the call. * @param _relayer The address of the Relayer. */ function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal { uint256 amount = 29292 + _gasUsed; // 21000 (transaction) + 7620 (execution of refund) + 672 to log the event + _gasUsed // only refund if gas price not null, more than 1 signatures, gas less than gasLimit if(_gasPrice > 0 && _signatures > 1 && amount <= _gasLimit) { if(_gasPrice > tx.gasprice) { amount = amount * tx.gasprice; } else { amount = amount * _gasPrice; } _wallet.invoke(_relayer, amount, ""); } } /** * @dev Returns false if the refund is expected to fail. * @param _wallet The target wallet. * @param _gasUsed The expected gas used. * @param _gasPrice The expected gas price for the refund. */ function verifyRefund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _signatures) internal view returns (bool) { if(_gasPrice > 0 && _signatures > 1 && (address(_wallet).balance < _gasUsed * _gasPrice || _wallet.authorised(this) == false)) { return false; } return true; } /** * @dev Checks that the wallet address provided as the first parameter of the relayed data is the same * as the wallet passed as the input of the execute() method. @return false if the addresses are different. */ function verifyData(address _wallet, bytes _data) private pure returns (bool) { require(_data.length >= 36, "RM: Invalid dataWallet"); address dataWallet; // solium-disable-next-line security/no-inline-assembly assembly { //_data = {length:32}{sig:4}{_wallet:32}{...} dataWallet := mload(add(_data, 0x24)) } return dataWallet == _wallet; } /** * @dev Parses the data to extract the method signature. */ function functionPrefix(bytes _data) internal pure returns (bytes4 prefix) { require(_data.length >= 4, "RM: Invalid functionPrefix"); // solium-disable-next-line security/no-inline-assembly assembly { prefix := mload(add(_data, 0x20)) } } } /** * @title LimitManager * @dev Module to transfer tokens (ETH or ERC20) based on a security context (daily limit, whitelist, etc). * @author Julien Niset - <[email protected]> */ contract LimitManager is BaseModule { // large limit when the limit can be considered disabled uint128 constant internal LIMIT_DISABLED = uint128(-1); // 3.40282366920938463463374607431768211455e+38 using SafeMath for uint256; struct LimitManagerConfig { // The global limit Limit limit; // whitelist DailySpent dailySpent; } struct Limit { // the current limit uint128 current; // the pending limit if any uint128 pending; // when the pending limit becomes the current limit uint64 changeAfter; } struct DailySpent { // The amount already spent during the current period uint128 alreadySpent; // The end of the current period uint64 periodEnd; } // wallet specific storage mapping (address => LimitManagerConfig) internal limits; // The default limit uint256 public defaultLimit; // *************** Events *************************** // event LimitChanged(address indexed wallet, uint indexed newLimit, uint64 indexed startAfter); // *************** Constructor ********************** // constructor(uint256 _defaultLimit) public { defaultLimit = _defaultLimit; } // *************** External/Public Functions ********************* // /** * @dev Inits the module for a wallet by setting the limit to the default value. * @param _wallet The target wallet. */ function init(BaseWallet _wallet) external onlyWallet(_wallet) { Limit storage limit = limits[_wallet].limit; if(limit.current == 0 && limit.changeAfter == 0) { limit.current = uint128(defaultLimit); } } /** * @dev Changes the global limit. * The limit is expressed in ETH and the change is pending for the security period. * @param _wallet The target wallet. * @param _newLimit The new limit. * @param _securityPeriod The security period. */ function changeLimit(BaseWallet _wallet, uint256 _newLimit, uint256 _securityPeriod) internal { Limit storage limit = limits[_wallet].limit; // solium-disable-next-line security/no-block-members uint128 currentLimit = (limit.changeAfter > 0 && limit.changeAfter < now) ? limit.pending : limit.current; limit.current = currentLimit; limit.pending = uint128(_newLimit); // solium-disable-next-line security/no-block-members limit.changeAfter = uint64(now.add(_securityPeriod)); // solium-disable-next-line security/no-block-members emit LimitChanged(_wallet, _newLimit, uint64(now.add(_securityPeriod))); } // *************** Internal Functions ********************* // /** * @dev Gets the current global limit for a wallet. * @param _wallet The target wallet. * @return the current limit expressed in ETH. */ function getCurrentLimit(BaseWallet _wallet) public view returns (uint256 _currentLimit) { Limit storage limit = limits[_wallet].limit; _currentLimit = uint256(currentLimit(limit.current, limit.pending, limit.changeAfter)); } /** * @dev Gets a pending limit for a wallet if any. * @param _wallet The target wallet. * @return the pending limit (in ETH) and the time at chich it will become effective. */ function getPendingLimit(BaseWallet _wallet) external view returns (uint256 _pendingLimit, uint64 _changeAfter) { Limit storage limit = limits[_wallet].limit; // solium-disable-next-line security/no-block-members return ((now < limit.changeAfter)? (uint256(limit.pending), limit.changeAfter) : (0,0)); } /** * @dev Gets the amount of tokens that has not yet been spent during the current period. * @param _wallet The target wallet. * @return the amount of tokens (in ETH) that has not been spent yet and the end of the period. */ function getDailyUnspent(BaseWallet _wallet) external view returns (uint256 _unspent, uint64 _periodEnd) { uint256 globalLimit = getCurrentLimit(_wallet); DailySpent storage expense = limits[_wallet].dailySpent; // solium-disable-next-line security/no-block-members if(now > expense.periodEnd) { _unspent = globalLimit; _periodEnd = uint64(now + 24 hours); } else { _unspent = globalLimit - expense.alreadySpent; _periodEnd = expense.periodEnd; } } /** * @dev Helper method to check if a transfer is within the limit. * If yes the daily unspent for the current period is updated. * @param _wallet The target wallet. * @param _amount The amount for the transfer */ function checkAndUpdateDailySpent(BaseWallet _wallet, uint _amount) internal returns (bool) { Limit storage limit = limits[_wallet].limit; uint128 current = currentLimit(limit.current, limit.pending, limit.changeAfter); if(isWithinDailyLimit(_wallet, current, _amount)) { updateDailySpent(_wallet, current, _amount); return true; } return false; } /** * @dev Helper method to update the daily spent for the current period. * @param _wallet The target wallet. * @param _limit The current limit for the wallet. * @param _amount The amount to add to the daily spent. */ function updateDailySpent(BaseWallet _wallet, uint128 _limit, uint _amount) internal { if(_limit != LIMIT_DISABLED) { DailySpent storage expense = limits[_wallet].dailySpent; if (expense.periodEnd < now) { expense.periodEnd = uint64(now + 24 hours); expense.alreadySpent = uint128(_amount); } else { expense.alreadySpent += uint128(_amount); } } } /** * @dev Checks if a transfer amount is withing the daily limit for a wallet. * @param _wallet The target wallet. * @param _limit The current limit for the wallet. * @param _amount The transfer amount. * @return true if the transfer amount is withing the daily limit. */ function isWithinDailyLimit(BaseWallet _wallet, uint _limit, uint _amount) internal view returns (bool) { DailySpent storage expense = limits[_wallet].dailySpent; if(_limit == LIMIT_DISABLED) { return true; } else if (expense.periodEnd < now) { return (_amount <= _limit); } else { return (expense.alreadySpent + _amount <= _limit && expense.alreadySpent + _amount >= expense.alreadySpent); } } /** * @dev Helper method to get the current limit from a Limit struct. * @param _current The value of the current parameter * @param _pending The value of the pending parameter * @param _changeAfter The value of the changeAfter parameter */ function currentLimit(uint128 _current, uint128 _pending, uint64 _changeAfter) internal view returns (uint128) { if(_changeAfter > 0 && _changeAfter < now) { return _pending; } return _current; } } /** * ERC20 contract interface. */ contract ERC20 { function totalSupply() public view returns (uint); function decimals() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); } /* The MIT License (MIT) Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @title SafeMath * @dev Math operations with safety checks that throw 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) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); 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; } /** * @dev Returns ceil(a / b). */ function ceil(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; if(a % b == 0) { return c; } else { return c + 1; } } } /** * @title Owned * @dev Basic contract to define an owner. * @author Julien Niset - <[email protected]> */ contract Owned { // The owner address public owner; event OwnerChanged(address indexed _newOwner); /** * @dev Throws if the sender is not the owner. */ modifier onlyOwner { require(msg.sender == owner, "Must be owner"); _; } constructor() public { owner = msg.sender; } /** * @dev Lets the owner transfer ownership of the contract to a new owner. * @param _newOwner The new owner. */ function changeOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "Address must not be null"); owner = _newOwner; emit OwnerChanged(_newOwner); } } /** * @title ModuleRegistry * @dev Registry of authorised modules. * Modules must be registered before they can be authorised on a wallet. * @author Julien Niset - <[email protected]> */ contract ModuleRegistry is Owned { mapping (address => Info) internal modules; mapping (address => Info) internal upgraders; event ModuleRegistered(address indexed module, bytes32 name); event ModuleDeRegistered(address module); event UpgraderRegistered(address indexed upgrader, bytes32 name); event UpgraderDeRegistered(address upgrader); struct Info { bool exists; bytes32 name; } /** * @dev Registers a module. * @param _module The module. * @param _name The unique name of the module. */ function registerModule(address _module, bytes32 _name) external onlyOwner { require(!modules[_module].exists, "MR: module already exists"); modules[_module] = Info({exists: true, name: _name}); emit ModuleRegistered(_module, _name); } /** * @dev Deregisters a module. * @param _module The module. */ function deregisterModule(address _module) external onlyOwner { require(modules[_module].exists, "MR: module does not exists"); delete modules[_module]; emit ModuleDeRegistered(_module); } /** * @dev Registers an upgrader. * @param _upgrader The upgrader. * @param _name The unique name of the upgrader. */ function registerUpgrader(address _upgrader, bytes32 _name) external onlyOwner { require(!upgraders[_upgrader].exists, "MR: upgrader already exists"); upgraders[_upgrader] = Info({exists: true, name: _name}); emit UpgraderRegistered(_upgrader, _name); } /** * @dev Deregisters an upgrader. * @param _upgrader The _upgrader. */ function deregisterUpgrader(address _upgrader) external onlyOwner { require(upgraders[_upgrader].exists, "MR: upgrader does not exists"); delete upgraders[_upgrader]; emit UpgraderDeRegistered(_upgrader); } /** * @dev Utility method enbaling the owner of the registry to claim any ERC20 token that was sent to the * registry. * @param _token The token to recover. */ function recoverToken(address _token) external onlyOwner { uint total = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, total); } /** * @dev Gets the name of a module from its address. * @param _module The module address. * @return the name. */ function moduleInfo(address _module) external view returns (bytes32) { return modules[_module].name; } /** * @dev Gets the name of an upgrader from its address. * @param _upgrader The upgrader address. * @return the name. */ function upgraderInfo(address _upgrader) external view returns (bytes32) { return upgraders[_upgrader].name; } /** * @dev Checks if a module is registered. * @param _module The module address. * @return true if the module is registered. */ function isRegisteredModule(address _module) external view returns (bool) { return modules[_module].exists; } /** * @dev Checks if a list of modules are registered. * @param _modules The list of modules address. * @return true if all the modules are registered. */ function isRegisteredModule(address[] _modules) external view returns (bool) { for(uint i = 0; i < _modules.length; i++) { if (!modules[_modules[i]].exists) { return false; } } return true; } /** * @dev Checks if an upgrader is registered. * @param _upgrader The upgrader address. * @return true if the upgrader is registered. */ function isRegisteredUpgrader(address _upgrader) external view returns (bool) { return upgraders[_upgrader].exists; } } /** * @title BaseWallet * @dev Simple modular wallet that authorises modules to call its invoke() method. * Based on https://gist.github.com/Arachnid/a619d31f6d32757a4328a428286da186 by * @author Julien Niset - <[email protected]> */ contract BaseWallet { // The implementation of the proxy address public implementation; // The owner address public owner; // The authorised modules mapping (address => bool) public authorised; // The enabled static calls mapping (bytes4 => address) public enabled; // The number of modules uint public modules; event AuthorisedModule(address indexed module, bool value); event EnabledStaticCall(address indexed module, bytes4 indexed method); event Invoked(address indexed module, address indexed target, uint indexed value, bytes data); event Received(uint indexed value, address indexed sender, bytes data); event OwnerChanged(address owner); /** * @dev Throws if the sender is not an authorised module. */ modifier moduleOnly { require(authorised[msg.sender], "BW: msg.sender not an authorized module"); _; } /** * @dev Inits the wallet by setting the owner and authorising a list of modules. * @param _owner The owner. * @param _modules The modules to authorise. */ function init(address _owner, address[] _modules) external { require(owner == address(0) && modules == 0, "BW: wallet already initialised"); require(_modules.length > 0, "BW: construction requires at least 1 module"); owner = _owner; modules = _modules.length; for(uint256 i = 0; i < _modules.length; i++) { require(authorised[_modules[i]] == false, "BW: module is already added"); authorised[_modules[i]] = true; Module(_modules[i]).init(this); emit AuthorisedModule(_modules[i], true); } } /** * @dev Enables/Disables a module. * @param _module The target module. * @param _value Set to true to authorise the module. */ function authoriseModule(address _module, bool _value) external moduleOnly { if (authorised[_module] != _value) { if(_value == true) { modules += 1; authorised[_module] = true; Module(_module).init(this); } else { modules -= 1; require(modules > 0, "BW: wallet must have at least one module"); delete authorised[_module]; } emit AuthorisedModule(_module, _value); } } /** * @dev Enables a static method by specifying the target module to which the call * must be delegated. * @param _module The target module. * @param _method The static method signature. */ function enableStaticCall(address _module, bytes4 _method) external moduleOnly { require(authorised[_module], "BW: must be an authorised module for static call"); enabled[_method] = _module; emit EnabledStaticCall(_module, _method); } /** * @dev Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _newOwner) external moduleOnly { require(_newOwner != address(0), "BW: address cannot be null"); owner = _newOwner; emit OwnerChanged(_newOwner); } /** * @dev Performs a generic transaction. * @param _target The address for the transaction. * @param _value The value of the transaction. * @param _data The data of the transaction. */ function invoke(address _target, uint _value, bytes _data) external moduleOnly { // solium-disable-next-line security/no-call-value require(_target.call.value(_value)(_data), "BW: call to target failed"); emit Invoked(msg.sender, _target, _value, _data); } /** * @dev This method makes it possible for the wallet to comply to interfaces expecting the wallet to * implement specific static methods. It delegates the static call to a target contract if the data corresponds * to an enabled method, or logs the call otherwise. */ function() public payable { if(msg.data.length > 0) { address module = enabled[msg.sig]; if(module == address(0)) { emit Received(msg.value, msg.sender, msg.data); } else { require(authorised[module], "BW: must be an authorised module for static call"); // solium-disable-next-line security/no-inline-assembly assembly { calldatacopy(0, 0, calldatasize()) let result := staticcall(gas, module, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } } } } contract TokenPriceProvider { using SafeMath for uint256; // Mock token address for ETH address constant internal ETH_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // Address of Kyber's trading contract address constant internal KYBER_NETWORK_ADDRESS = 0x818E6FECD516Ecc3849DAf6845e3EC868087B755; mapping(address => uint256) public cachedPrices; function syncPrice(ERC20 token) public { uint256 expectedRate; (expectedRate,) = kyberNetwork().getExpectedRate(token, ERC20(ETH_TOKEN_ADDRESS), 10000); cachedPrices[token] = expectedRate; } // // Convenience functions // function syncPriceForTokenList(ERC20[] tokens) public { for(uint16 i = 0; i < tokens.length; i++) { syncPrice(tokens[i]); } } /** * @dev Converts the value of _amount tokens in ether. * @param _amount the amount of tokens to convert (in 'token wei' twei) * @param _token the ERC20 token contract * @return the ether value (in wei) of _amount tokens with contract _token */ function getEtherValue(uint256 _amount, address _token) public view returns (uint256) { uint256 decimals = ERC20(_token).decimals(); uint256 price = cachedPrices[_token]; return price.mul(_amount).div(10**decimals); } // // Internal // function kyberNetwork() internal view returns (KyberNetwork) { return KyberNetwork(KYBER_NETWORK_ADDRESS); } } contract KyberNetwork { function getExpectedRate( ERC20 src, ERC20 dest, uint srcQty ) public view returns (uint expectedRate, uint slippageRate); function trade( ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId ) public payable returns(uint); } /** * @title Storage * @dev Base contract for the storage of a wallet. * @author Julien Niset - <[email protected]> */ contract Storage { /** * @dev Throws if the caller is not an authorised module. */ modifier onlyModule(BaseWallet _wallet) { require(_wallet.authorised(msg.sender), "TS: must be an authorized module to call this method"); _; } } /** * @title GuardianStorage * @dev Contract storing the state of wallets related to guardians and lock. * The contract only defines basic setters and getters with no logic. Only modules authorised * for a wallet can modify its state. * @author Julien Niset - <[email protected]> * @author Olivier Van Den Biggelaar - <[email protected]> */ contract GuardianStorage is Storage { struct GuardianStorageConfig { // the list of guardians address[] guardians; // the info about guardians mapping (address => GuardianInfo) info; // the lock's release timestamp uint256 lock; // the module that set the last lock address locker; } struct GuardianInfo { bool exists; uint128 index; } // wallet specific storage mapping (address => GuardianStorageConfig) internal configs; // *************** External Functions ********************* // /** * @dev Lets an authorised module add a guardian to a wallet. * @param _wallet The target wallet. * @param _guardian The guardian to add. */ function addGuardian(BaseWallet _wallet, address _guardian) external onlyModule(_wallet) { GuardianStorageConfig storage config = configs[_wallet]; config.info[_guardian].exists = true; config.info[_guardian].index = uint128(config.guardians.push(_guardian) - 1); } /** * @dev Lets an authorised module revoke a guardian from a wallet. * @param _wallet The target wallet. * @param _guardian The guardian to revoke. */ function revokeGuardian(BaseWallet _wallet, address _guardian) external onlyModule(_wallet) { GuardianStorageConfig storage config = configs[_wallet]; address lastGuardian = config.guardians[config.guardians.length - 1]; if (_guardian != lastGuardian) { uint128 targetIndex = config.info[_guardian].index; config.guardians[targetIndex] = lastGuardian; config.info[lastGuardian].index = targetIndex; } config.guardians.length--; delete config.info[_guardian]; } /** * @dev Returns the number of guardians for a wallet. * @param _wallet The target wallet. * @return the number of guardians. */ function guardianCount(BaseWallet _wallet) external view returns (uint256) { return configs[_wallet].guardians.length; } /** * @dev Gets the list of guaridans for a wallet. * @param _wallet The target wallet. * @return the list of guardians. */ function getGuardians(BaseWallet _wallet) external view returns (address[]) { GuardianStorageConfig storage config = configs[_wallet]; address[] memory guardians = new address[](config.guardians.length); for (uint256 i = 0; i < config.guardians.length; i++) { guardians[i] = config.guardians[i]; } return guardians; } /** * @dev Checks if an account is a guardian for a wallet. * @param _wallet The target wallet. * @param _guardian The account. * @return true if the account is a guardian for a wallet. */ function isGuardian(BaseWallet _wallet, address _guardian) external view returns (bool) { return configs[_wallet].info[_guardian].exists; } /** * @dev Lets an authorised module set the lock for a wallet. * @param _wallet The target wallet. * @param _releaseAfter The epoch time at which the lock should automatically release. */ function setLock(BaseWallet _wallet, uint256 _releaseAfter) external onlyModule(_wallet) { configs[_wallet].lock = _releaseAfter; if(_releaseAfter != 0 && msg.sender != configs[_wallet].locker) { configs[_wallet].locker = msg.sender; } } /** * @dev Checks if the lock is set for a wallet. * @param _wallet The target wallet. * @return true if the lock is set for the wallet. */ function isLocked(BaseWallet _wallet) external view returns (bool) { return configs[_wallet].lock > now; } /** * @dev Gets the time at which the lock of a wallet will release. * @param _wallet The target wallet. * @return the time at which the lock of a wallet will release, or zero if there is no lock set. */ function getLock(BaseWallet _wallet) external view returns (uint256) { return configs[_wallet].lock; } /** * @dev Gets the address of the last module that modified the lock for a wallet. * @param _wallet The target wallet. * @return the address of the last module that modified the lock for a wallet. */ function getLocker(BaseWallet _wallet) external view returns (address) { return configs[_wallet].locker; } } /** * @title TransferStorage * @dev Contract storing the state of wallets related to transfers (limit and whitelist). * The contract only defines basic setters and getters with no logic. Only modules authorised * for a wallet can modify its state. * @author Julien Niset - <[email protected]> */ contract TransferStorage is Storage { // wallet specific storage mapping (address => mapping (address => uint256)) internal whitelist; // *************** External Functions ********************* // /** * @dev Lets an authorised module add or remove an account from the whitelist of a wallet. * @param _wallet The target wallet. * @param _target The account to add/remove. * @param _value True for addition, false for revokation. */ function setWhitelist(BaseWallet _wallet, address _target, uint256 _value) external onlyModule(_wallet) { whitelist[_wallet][_target] = _value; } /** * @dev Gets the whitelist state of an account for a wallet. * @param _wallet The target wallet. * @param _target The account. * @return the epoch time at which an account strats to be whitelisted, or zero if the account is not whitelisted. */ function getWhitelist(BaseWallet _wallet, address _target) external view returns (uint256) { return whitelist[_wallet][_target]; } } /** * @title TokenTransfer * @dev Module to transfer tokens (ETH or ERC20) based on a security context (daily limit, whitelist, etc). * @author Julien Niset - <[email protected]> */ contract TokenTransfer is BaseModule, RelayerModule, LimitManager { bytes32 constant NAME = "TokenTransfer"; bytes4 constant internal EXECUTE_PENDING_PREFIX = bytes4(keccak256("executePendingTransfer(address,address,address,uint256,bytes,uint256)")); bytes constant internal EMPTY_BYTES = ""; using SafeMath for uint256; // Mock token address for ETH address constant internal ETH_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // large limit when the limit can be considered disabled uint128 constant internal LIMIT_DISABLED = uint128(-1); // 3.40282366920938463463374607431768211455e+38 struct TokenTransferConfig { // Mapping between pending transfer hash and their timestamp mapping (bytes32 => uint256) pendingTransfers; } // wallet specific storage mapping (address => TokenTransferConfig) internal configs; // The security period uint256 public securityPeriod; // The execution window uint256 public securityWindow; // The Guardian storage GuardianStorage public guardianStorage; // The Token storage TransferStorage public transferStorage; // The Token price provider TokenPriceProvider public priceProvider; // *************** Events *************************** // event Transfer(address indexed wallet, address indexed token, uint256 indexed amount, address to, bytes data); event AddedToWhitelist(address indexed wallet, address indexed target, uint64 whitelistAfter); event RemovedFromWhitelist(address indexed wallet, address indexed target); event PendingTransferCreated(address indexed wallet, bytes32 indexed id, uint256 indexed executeAfter, address token, address to, uint256 amount, bytes data); event PendingTransferExecuted(address indexed wallet, bytes32 indexed id); event PendingTransferCanceled(address indexed wallet, bytes32 indexed id); // *************** Modifiers *************************** // /** * @dev Throws if the caller is not the owner or an authorised module. */ modifier onlyOwnerOrModule(BaseWallet _wallet) { require(isOwner(_wallet, msg.sender) || _wallet.authorised(msg.sender), "TT: must be wallet owner or module"); _; } /** * @dev Throws if the wallet is locked. */ modifier onlyWhenUnlocked(BaseWallet _wallet) { // solium-disable-next-line security/no-block-members require(!guardianStorage.isLocked(_wallet), "TT: wallet must be unlocked"); _; } // *************** Constructor ********************** // constructor( ModuleRegistry _registry, TransferStorage _transferStorage, GuardianStorage _guardianStorage, address _priceProvider, uint256 _securityPeriod, uint256 _securityWindow, uint256 _defaultLimit ) BaseModule(_registry, NAME) LimitManager(_defaultLimit) public { transferStorage = _transferStorage; guardianStorage = _guardianStorage; priceProvider = TokenPriceProvider(_priceProvider); securityPeriod = _securityPeriod; securityWindow = _securityWindow; } // *************** External/Public Functions ********************* // /** * @dev lets the owner transfer tokens (ETH or ERC20) from a wallet. * @param _wallet The target wallet. * @param _token The address of the token to transfer. * @param _to The destination address * @param _amount The amoutn of token to transfer * @param _data The data for the transaction */ function transferToken( BaseWallet _wallet, address _token, address _to, uint256 _amount, bytes _data ) external onlyOwnerOrModule(_wallet) onlyWhenUnlocked(_wallet) { if(isWhitelisted(_wallet, _to)) { // eth transfer to whitelist if(_token == ETH_TOKEN) { transferETH(_wallet, _to, _amount, _data); } // erc20 transfer to whitelist else { transferERC20(_wallet, _token, _to, _amount, _data); } } else { if(_token == ETH_TOKEN) { // eth transfer under the limit if (checkAndUpdateDailySpent(_wallet, _amount)) { transferETH(_wallet, _to, _amount, _data); } // eth transfer above the limit else { addPendingTransfer(_wallet, ETH_TOKEN, _to, _amount, _data); } } else { uint256 etherAmount = priceProvider.getEtherValue(_amount, _token); // erc20 transfer under the limit if (checkAndUpdateDailySpent(_wallet, etherAmount)) { transferERC20(_wallet, _token, _to, _amount, _data); } // erc20 transfer above the limit else { addPendingTransfer(_wallet, _token, _to, _amount, _data); } } } } /** * @dev Adds an address to the whitelist of a wallet. * @param _wallet The target wallet. * @param _target The address to add. */ function addToWhitelist( BaseWallet _wallet, address _target ) external onlyOwner(_wallet) onlyWhenUnlocked(_wallet) { require(!isWhitelisted(_wallet, _target), "TT: target already whitelisted"); // solium-disable-next-line security/no-block-members uint256 whitelistAfter = now.add(securityPeriod); transferStorage.setWhitelist(_wallet, _target, whitelistAfter); emit AddedToWhitelist(_wallet, _target, uint64(whitelistAfter)); } /** * @dev Removes an address from the whitelist of a wallet. * @param _wallet The target wallet. * @param _target The address to remove. */ function removeFromWhitelist( BaseWallet _wallet, address _target ) external onlyOwner(_wallet) onlyWhenUnlocked(_wallet) { require(isWhitelisted(_wallet, _target), "TT: target not whitelisted"); transferStorage.setWhitelist(_wallet, _target, 0); emit RemovedFromWhitelist(_wallet, _target); } /** * @dev Executes a pending transfer for a wallet. * The destination address is automatically added to the whitelist. * The method can be called by anyone to enable orchestration. * @param _wallet The target wallet. * @param _token The token of the pending transfer. * @param _to The destination address of the pending transfer. * @param _amount The amount of token to transfer of the pending transfer. * @param _block The block at which the pending transfer was created. */ function executePendingTransfer( BaseWallet _wallet, address _token, address _to, uint _amount, bytes _data, uint _block ) public onlyWhenUnlocked(_wallet) { bytes32 id = keccak256(abi.encodePacked(_token, _to, _amount, _data, _block)); uint executeAfter = configs[_wallet].pendingTransfers[id]; uint executeBefore = executeAfter.add(securityWindow); require(executeAfter <= now && now <= executeBefore, "TT: outside of the execution window"); removePendingTransfer(_wallet, id); if(_token == ETH_TOKEN) { transferETH(_wallet, _to, _amount, _data); } else { transferERC20(_wallet, _token, _to, _amount, _data); } emit PendingTransferExecuted(_wallet, id); } /** * @dev Cancels a pending transfer for a wallet. * @param _wallet The target wallet. * @param _id the pending transfer Id. */ function cancelPendingTransfer( BaseWallet _wallet, bytes32 _id ) public onlyOwner(_wallet) onlyWhenUnlocked(_wallet) { require(configs[_wallet].pendingTransfers[_id] > 0, "TT: unknown pending transfer"); removePendingTransfer(_wallet, _id); emit PendingTransferCanceled(_wallet, _id); } /** * @dev Lets the owner of a wallet change its global limit. * The limit is expressed in ETH. Changes to the limit take 24 hours. * @param _wallet The target wallet. * @param _newLimit The new limit. */ function changeLimit(BaseWallet _wallet, uint256 _newLimit) public onlyOwner(_wallet) onlyWhenUnlocked(_wallet) { changeLimit(_wallet, _newLimit, securityPeriod); } /** * @dev Convenience method to disable the limit * The limit is disabled by setting it to an arbitrary large value. * @param _wallet The target wallet. */ function disableLimit(BaseWallet _wallet) external onlyOwner(_wallet) onlyWhenUnlocked(_wallet) { changeLimit(_wallet, LIMIT_DISABLED, securityPeriod); } /** * @dev Checks if an address is whitelisted for a wallet. * @param _wallet The target wallet. * @param _target The address. * @return true if the address is whitelisted. */ function isWhitelisted(BaseWallet _wallet, address _target) public view returns (bool _isWhitelisted) { uint whitelistAfter = transferStorage.getWhitelist(_wallet, _target); // solium-disable-next-line security/no-block-members return whitelistAfter > 0 && whitelistAfter < now; } /** * @dev Gets the info of a pending transfer for a wallet. * @param _wallet The target wallet. * @param _id The pending transfer Id. * @return the epoch time at which the pending transfer can be executed. */ function getPendingTransfer(BaseWallet _wallet, bytes32 _id) external view returns (uint64 _executeAfter) { _executeAfter = uint64(configs[_wallet].pendingTransfers[_id]); } // *************** Internal Functions ********************* // /** * @dev Helper method to transfer ETH for a wallet. * @param _wallet The target wallet. * @param _to The recipient. * @param _value The amount of ETH to transfer * @param _data The data to *log* with the transfer. */ function transferETH(BaseWallet _wallet, address _to, uint256 _value, bytes _data) internal { _wallet.invoke(_to, _value, EMPTY_BYTES); emit Transfer(_wallet, ETH_TOKEN, _value, _to, _data); } /** * @dev Helper method to transfer ERC20 for a wallet. * @param _wallet The target wallet. * @param _token The ERC20 address. * @param _to The recipient. * @param _value The amount of token to transfer * @param _data The data to pass with the trnasfer. */ function transferERC20(BaseWallet _wallet, address _token, address _to, uint256 _value, bytes _data) internal { bytes memory methodData = abi.encodeWithSignature("transfer(address,uint256)", _to, _value); _wallet.invoke(_token, 0, methodData); emit Transfer(_wallet, _token, _value, _to, _data); } /** * @dev Creates a new pending transfer for a wallet. * @param _wallet The target wallet. * @param _token The token for the transfer. * @param _to The recipient for the transfer. * @param _amount The amount of token to transfer. * @param _data The data associated to the transfer. * @return the identifier for the new pending transfer. */ function addPendingTransfer(BaseWallet _wallet, address _token, address _to, uint _amount, bytes _data) internal returns (bytes32) { bytes32 id = keccak256(abi.encodePacked(_token, _to, _amount, _data, block.number)); uint executeAfter = now.add(securityPeriod); configs[_wallet].pendingTransfers[id] = executeAfter; emit PendingTransferCreated(_wallet, id, executeAfter, _token, _to, _amount, _data); } /** * @dev Removes an existing pending transfer. * @param _wallet The target wallet * @param _id The id of the transfer to remove. */ function removePendingTransfer(BaseWallet _wallet, bytes32 _id) internal { delete configs[_wallet].pendingTransfers[_id]; } // *************** Implementation of RelayerModule methods ********************* // // Overrides refund to add the refund in the daily limit. function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal { // 21000 (transaction) + 7620 (execution of refund) + 7324 (execution of updateDailySpent) + 672 to log the event + _gasUsed uint256 amount = 36616 + _gasUsed; if(_gasPrice > 0 && _signatures > 0 && amount <= _gasLimit) { if(_gasPrice > tx.gasprice) { amount = amount * tx.gasprice; } else { amount = amount * _gasPrice; } updateDailySpent(_wallet, uint128(getCurrentLimit(_wallet)), amount); _wallet.invoke(_relayer, amount, ""); } } // Overrides verifyRefund to add the refund in the daily limit. function verifyRefund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _signatures) internal view returns (bool) { if(_gasPrice > 0 && _signatures > 0 && ( address(_wallet).balance < _gasUsed * _gasPrice || isWithinDailyLimit(_wallet, getCurrentLimit(_wallet), _gasUsed * _gasPrice) == false || _wallet.authorised(this) == false )) { return false; } return true; } // Overrides to use the incremental nonce and save some gas function checkAndUpdateUniqueness(BaseWallet _wallet, uint256 _nonce, bytes32 _signHash) internal returns (bool) { return checkAndUpdateNonce(_wallet, _nonce); } function validateSignatures(BaseWallet _wallet, bytes _data, bytes32 _signHash, bytes _signatures) internal view returns (bool) { address signer = recoverSigner(_signHash, _signatures, 0); return isOwner(_wallet, signer); // "TT: signer must be owner" } function getRequiredSignatures(BaseWallet _wallet, bytes _data) internal view returns (uint256) { bytes4 methodId = functionPrefix(_data); if (methodId == EXECUTE_PENDING_PREFIX) { return 0; } return 1; } }
* @title LimitManager @dev Module to transfer tokens (ETH or ERC20) based on a security context (daily limit, whitelist, etc). @author Julien Niset - <[email protected]>/ large limit when the limit can be considered disabled
contract LimitManager is BaseModule { using SafeMath for uint256; struct LimitManagerConfig { Limit limit; DailySpent dailySpent; } struct Limit { uint128 current; uint128 pending; uint64 changeAfter; } struct DailySpent { uint128 alreadySpent; uint64 periodEnd; } event LimitChanged(address indexed wallet, uint indexed newLimit, uint64 indexed startAfter); mapping (address => LimitManagerConfig) internal limits; uint256 public defaultLimit; constructor(uint256 _defaultLimit) public { defaultLimit = _defaultLimit; } function init(BaseWallet _wallet) external onlyWallet(_wallet) { Limit storage limit = limits[_wallet].limit; if(limit.current == 0 && limit.changeAfter == 0) { limit.current = uint128(defaultLimit); } } function init(BaseWallet _wallet) external onlyWallet(_wallet) { Limit storage limit = limits[_wallet].limit; if(limit.current == 0 && limit.changeAfter == 0) { limit.current = uint128(defaultLimit); } } function changeLimit(BaseWallet _wallet, uint256 _newLimit, uint256 _securityPeriod) internal { Limit storage limit = limits[_wallet].limit; uint128 currentLimit = (limit.changeAfter > 0 && limit.changeAfter < now) ? limit.pending : limit.current; limit.current = currentLimit; limit.pending = uint128(_newLimit); limit.changeAfter = uint64(now.add(_securityPeriod)); emit LimitChanged(_wallet, _newLimit, uint64(now.add(_securityPeriod))); } function getCurrentLimit(BaseWallet _wallet) public view returns (uint256 _currentLimit) { Limit storage limit = limits[_wallet].limit; _currentLimit = uint256(currentLimit(limit.current, limit.pending, limit.changeAfter)); } function getPendingLimit(BaseWallet _wallet) external view returns (uint256 _pendingLimit, uint64 _changeAfter) { Limit storage limit = limits[_wallet].limit; return ((now < limit.changeAfter)? (uint256(limit.pending), limit.changeAfter) : (0,0)); } function getDailyUnspent(BaseWallet _wallet) external view returns (uint256 _unspent, uint64 _periodEnd) { uint256 globalLimit = getCurrentLimit(_wallet); DailySpent storage expense = limits[_wallet].dailySpent; if(now > expense.periodEnd) { _unspent = globalLimit; _periodEnd = uint64(now + 24 hours); } else { _unspent = globalLimit - expense.alreadySpent; _periodEnd = expense.periodEnd; } } function getDailyUnspent(BaseWallet _wallet) external view returns (uint256 _unspent, uint64 _periodEnd) { uint256 globalLimit = getCurrentLimit(_wallet); DailySpent storage expense = limits[_wallet].dailySpent; if(now > expense.periodEnd) { _unspent = globalLimit; _periodEnd = uint64(now + 24 hours); } else { _unspent = globalLimit - expense.alreadySpent; _periodEnd = expense.periodEnd; } } function getDailyUnspent(BaseWallet _wallet) external view returns (uint256 _unspent, uint64 _periodEnd) { uint256 globalLimit = getCurrentLimit(_wallet); DailySpent storage expense = limits[_wallet].dailySpent; if(now > expense.periodEnd) { _unspent = globalLimit; _periodEnd = uint64(now + 24 hours); } else { _unspent = globalLimit - expense.alreadySpent; _periodEnd = expense.periodEnd; } } function checkAndUpdateDailySpent(BaseWallet _wallet, uint _amount) internal returns (bool) { Limit storage limit = limits[_wallet].limit; uint128 current = currentLimit(limit.current, limit.pending, limit.changeAfter); if(isWithinDailyLimit(_wallet, current, _amount)) { updateDailySpent(_wallet, current, _amount); return true; } return false; } function checkAndUpdateDailySpent(BaseWallet _wallet, uint _amount) internal returns (bool) { Limit storage limit = limits[_wallet].limit; uint128 current = currentLimit(limit.current, limit.pending, limit.changeAfter); if(isWithinDailyLimit(_wallet, current, _amount)) { updateDailySpent(_wallet, current, _amount); return true; } return false; } function updateDailySpent(BaseWallet _wallet, uint128 _limit, uint _amount) internal { if(_limit != LIMIT_DISABLED) { DailySpent storage expense = limits[_wallet].dailySpent; if (expense.periodEnd < now) { expense.periodEnd = uint64(now + 24 hours); expense.alreadySpent = uint128(_amount); } else { expense.alreadySpent += uint128(_amount); } } } function updateDailySpent(BaseWallet _wallet, uint128 _limit, uint _amount) internal { if(_limit != LIMIT_DISABLED) { DailySpent storage expense = limits[_wallet].dailySpent; if (expense.periodEnd < now) { expense.periodEnd = uint64(now + 24 hours); expense.alreadySpent = uint128(_amount); } else { expense.alreadySpent += uint128(_amount); } } } function updateDailySpent(BaseWallet _wallet, uint128 _limit, uint _amount) internal { if(_limit != LIMIT_DISABLED) { DailySpent storage expense = limits[_wallet].dailySpent; if (expense.periodEnd < now) { expense.periodEnd = uint64(now + 24 hours); expense.alreadySpent = uint128(_amount); } else { expense.alreadySpent += uint128(_amount); } } } function updateDailySpent(BaseWallet _wallet, uint128 _limit, uint _amount) internal { if(_limit != LIMIT_DISABLED) { DailySpent storage expense = limits[_wallet].dailySpent; if (expense.periodEnd < now) { expense.periodEnd = uint64(now + 24 hours); expense.alreadySpent = uint128(_amount); } else { expense.alreadySpent += uint128(_amount); } } } function isWithinDailyLimit(BaseWallet _wallet, uint _limit, uint _amount) internal view returns (bool) { DailySpent storage expense = limits[_wallet].dailySpent; if(_limit == LIMIT_DISABLED) { return true; } else if (expense.periodEnd < now) { return (_amount <= _limit); return (expense.alreadySpent + _amount <= _limit && expense.alreadySpent + _amount >= expense.alreadySpent); } } function isWithinDailyLimit(BaseWallet _wallet, uint _limit, uint _amount) internal view returns (bool) { DailySpent storage expense = limits[_wallet].dailySpent; if(_limit == LIMIT_DISABLED) { return true; } else if (expense.periodEnd < now) { return (_amount <= _limit); return (expense.alreadySpent + _amount <= _limit && expense.alreadySpent + _amount >= expense.alreadySpent); } } function isWithinDailyLimit(BaseWallet _wallet, uint _limit, uint _amount) internal view returns (bool) { DailySpent storage expense = limits[_wallet].dailySpent; if(_limit == LIMIT_DISABLED) { return true; } else if (expense.periodEnd < now) { return (_amount <= _limit); return (expense.alreadySpent + _amount <= _limit && expense.alreadySpent + _amount >= expense.alreadySpent); } } } else { function currentLimit(uint128 _current, uint128 _pending, uint64 _changeAfter) internal view returns (uint128) { if(_changeAfter > 0 && _changeAfter < now) { return _pending; } return _current; } function currentLimit(uint128 _current, uint128 _pending, uint64 _changeAfter) internal view returns (uint128) { if(_changeAfter > 0 && _changeAfter < now) { return _pending; } return _current; } }
5,456,234
[ 1, 3039, 1318, 225, 5924, 358, 7412, 2430, 261, 1584, 44, 578, 4232, 39, 3462, 13, 2511, 603, 279, 4373, 819, 261, 26790, 1800, 16, 10734, 16, 5527, 2934, 225, 804, 14826, 275, 423, 291, 278, 300, 411, 28034, 275, 36, 3175, 319, 18, 17177, 16893, 7876, 1800, 1347, 326, 1800, 848, 506, 7399, 5673, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7214, 1318, 353, 3360, 3120, 288, 203, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 1958, 7214, 1318, 809, 288, 203, 3639, 7214, 1800, 31, 203, 3639, 463, 12857, 3389, 319, 18872, 3389, 319, 31, 203, 565, 289, 7010, 203, 565, 1958, 7214, 288, 203, 3639, 2254, 10392, 783, 31, 203, 3639, 2254, 10392, 4634, 31, 203, 3639, 2254, 1105, 2549, 4436, 31, 203, 565, 289, 203, 203, 565, 1958, 463, 12857, 3389, 319, 288, 203, 3639, 2254, 10392, 1818, 3389, 319, 31, 203, 3639, 2254, 1105, 3879, 1638, 31, 203, 565, 289, 203, 203, 203, 565, 871, 7214, 5033, 12, 2867, 8808, 9230, 16, 2254, 8808, 394, 3039, 16, 2254, 1105, 8808, 787, 4436, 1769, 203, 203, 565, 2874, 261, 2867, 516, 7214, 1318, 809, 13, 2713, 8181, 31, 203, 565, 2254, 5034, 1071, 805, 3039, 31, 203, 203, 203, 565, 3885, 12, 11890, 5034, 389, 1886, 3039, 13, 1071, 288, 203, 3639, 805, 3039, 273, 389, 1886, 3039, 31, 203, 565, 289, 203, 203, 203, 565, 445, 1208, 12, 2171, 16936, 389, 19177, 13, 3903, 1338, 16936, 24899, 19177, 13, 288, 203, 3639, 7214, 2502, 1800, 273, 8181, 63, 67, 19177, 8009, 3595, 31, 203, 3639, 309, 12, 3595, 18, 2972, 422, 374, 597, 1800, 18, 3427, 4436, 422, 374, 13, 288, 203, 5411, 1800, 18, 2972, 273, 2254, 10392, 12, 1886, 3039, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 1208, 12, 2171, 16936, 389, 19177, 13, 3903, 1338, 16936, 24899, 19177, 2 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./interfaces/IERC20.sol"; import "./interfaces/IERC20Permit.sol"; import "./interfaces/ITranche.sol"; import "./interfaces/IWETH.sol"; import "./interfaces/IWrappedPosition.sol"; import "./libraries/Authorizable.sol"; /// @author Element Finance /// @title User Proxy contract UserProxy is Authorizable { // This contract is a convenience library to consolidate // the actions needed to create interest or principal tokens to one call. // It will hold user allowances, and can be disabled by authorized addresses // for security. // If frozen users still control their own tokens so can manually redeem them. // Store the accessibility state of the contract bool public isFrozen = false; // Constant wrapped ether address IWETH public immutable weth; // Tranche factory address for Tranche contract address derivation address internal immutable _trancheFactory; // Tranche bytecode hash for Tranche contract address derivation. // This is constant as long as Tranche does not implement non-constant constructor arguments. bytes32 internal immutable _trancheBytecodeHash; // A constant which represents ether address internal constant _ETH_CONSTANT = address( 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ); /// @dev Marks the msg.sender as authorized and sets them /// as the owner in authorization library /// @param _weth The constant weth contract address /// @param __trancheFactory Address of the TrancheFactory contract /// @param __trancheBytecodeHash Hash of the Tranche bytecode. constructor( IWETH _weth, address __trancheFactory, bytes32 __trancheBytecodeHash ) Authorizable() { _authorize(msg.sender); weth = _weth; _trancheFactory = __trancheFactory; _trancheBytecodeHash = __trancheBytecodeHash; } /// @dev Requires that the contract is not frozen modifier notFrozen() { require(!isFrozen, "Contract frozen"); _; } /// @dev Allows an authorized address to freeze or unfreeze this contract /// @param _newState True for frozen and false for unfrozen function setIsFrozen(bool _newState) external onlyAuthorized() { isFrozen = _newState; } // Memory encoding of the permit data struct PermitData { IERC20Permit tokenContract; address who; uint256 amount; uint256 expiration; bytes32 r; bytes32 s; uint8 v; } /// @dev Takes the input permit calls and executes them /// @param data The array which encodes the set of permit calls to make modifier preApproval(PermitData[] memory data) { // If permit calls are provided we make try to make them if (data.length != 0) { // We make permit calls for each indicated call for (uint256 i = 0; i < data.length; i++) { _permitCall(data[i]); } } _; } /// @dev Makes permit calls indicated by a struct /// @param data the struct which has the permit calldata function _permitCall(PermitData memory data) internal { // Make the permit call to the token in the data field using // the fields provided. // Security note - This fairly open call is safe because it cannot // call 'transferFrom' or other sensitive methods despite the open // scope. Do not make more general without security review. data.tokenContract.permit( msg.sender, data.who, data.amount, data.expiration, data.v, data.r, data.s ); } /// @notice Mints a Principal/Interest token pair from either underlying token or Eth /// then returns the tokens to the caller. /// @dev This function assumes that it already has an allowance for the token in question. /// @param _amount The amount of underlying to turn into tokens /// @param _underlying Either (1) The underlying ERC20 token contract /// or (2) the _ETH_CONSTANT to indicate the user has sent eth. /// This token should revert in the event of a transfer failure. /// @param _expiration The expiration time of the Tranche contract /// @param _position The contract which manages pooled deposits /// @param _permitCallData Encoded array of permit calls to make prior to minting /// the data should be encoded with abi.encode(data, "PermitData[]") /// each PermitData struct provided will be executed as a call. /// An example use of this is if using a token with permit like USDC /// to encode a permit which gives this contract allowance before minting. /// @return returns the minted amounts of PT and YT // NOTE - It is critical that the notFrozen modifier is listed first so it gets called first. function mint( uint256 _amount, IERC20 _underlying, uint256 _expiration, address _position, PermitData[] calldata _permitCallData ) external payable notFrozen() preApproval(_permitCallData) returns (uint256, uint256) { // If the underlying token matches this predefined 'ETH token' // then we create weth for the user and go from there if (address(_underlying) == _ETH_CONSTANT) { // Check that the amount matches the amount provided require(msg.value == _amount, "Incorrect amount provided"); // Create weth from the provided eth weth.deposit{ value: msg.value }(); weth.transfer(address(_position), _amount); } else { // Check for the fact that this branch should not be payable require(msg.value == 0, "Non payable"); // Move the user's funds to the wrapped position contract _underlying.transferFrom(msg.sender, address(_position), _amount); } // Proceed to internal minting steps (uint256 ptMinted, uint256 ytMinted) = _mint(_expiration, _position); // This sanity check ensure that at least as much was minted as was transferred require(ytMinted >= _amount, "Not enough minted"); return (ptMinted, ytMinted); } /// @dev Allows a user to withdraw and unwrap weth in the same transaction /// likely quite a bit more expensive than direct unwrapping but useful /// for those who want to do one tx instead of two /// @param _expiration The tranche expiration time /// @param _position The contract which interacts with the yield bearing strategy /// @param _amountPT The amount of principal token to withdraw /// @param _amountYT The amount of yield token to withdraw. /// @param _permitCallData Encoded array of permit calls to make prior to withdrawing, /// should be used to get allowances for PT and YT // NOTE - It is critical that the notFrozen modifier is listed first so it gets called first. function withdrawWeth( uint256 _expiration, address _position, uint256 _amountPT, uint256 _amountYT, PermitData[] calldata _permitCallData ) external notFrozen() preApproval(_permitCallData) { // Post the Berlin hardfork this call warms the address so only cost ~100 gas overall require(IWrappedPosition(_position).token() == weth, "Non weth token"); // Only allow access if the user is actually attempting to withdraw require(((_amountPT != 0) || (_amountYT != 0)), "Invalid withdraw"); // Because of create2 we know this code is exactly what is expected. ITranche derivedTranche = _deriveTranche(_position, _expiration); uint256 wethReceivedPt = 0; uint256 wethReceivedYt = 0; // Check if we need to withdraw principal token if (_amountPT != 0) { // If we have to withdraw PT first transfer it to this contract derivedTranche.transferFrom(msg.sender, address(this), _amountPT); // Then we withdraw that PT with the resulting weth going to this address wethReceivedPt = derivedTranche.withdrawPrincipal( _amountPT, address(this) ); } // Check if we need to withdraw yield token if (_amountYT != 0) { // Post Berlin this lookup only costs 100 gas overall as well IERC20Permit yieldToken = derivedTranche.interestToken(); // Transfer the YT to this contract yieldToken.transferFrom(msg.sender, address(this), _amountYT); // Withdraw that YT wethReceivedYt = derivedTranche.withdrawInterest( _amountYT, address(this) ); } // A sanity check that some value was withdrawn if (_amountPT != 0) { require((wethReceivedPt != 0), "Rugged"); } if (_amountYT != 0) { require((wethReceivedYt != 0), "No yield accrued"); } // Withdraw the ether from weth weth.withdraw(wethReceivedPt + wethReceivedYt); // Send the withdrawn eth to the caller payable(msg.sender).transfer(wethReceivedPt + wethReceivedYt); } /// @dev The receive function allows WETH and only WETH to send /// eth directly to this contract. Note - It Cannot be assumed /// that this will prevent this contract from having an ETH balance receive() external payable { require(msg.sender == address(weth)); } /// @dev This internal mint function performs the core minting logic after /// the contract has already transferred to WrappedPosition contract /// @param _expiration The tranche expiration time /// @param _position The contract which interacts with the yield bearing strategy /// @return the principal token yield token returned function _mint(uint256 _expiration, address _position) internal returns (uint256, uint256) { // Use create2 to derive the tranche contract ITranche tranche = _deriveTranche(address(_position), _expiration); // Move funds into the Tranche contract // it will credit the msg.sender with the new tokens return tranche.prefundedDeposit(msg.sender); } /// @dev This internal function produces the deterministic create2 /// address of the Tranche contract from a wrapped position contract and expiration /// @param _position The wrapped position contract address /// @param _expiration The expiration time of the tranche /// @return The derived Tranche contract function _deriveTranche(address _position, uint256 _expiration) internal virtual view returns (ITranche) { bytes32 salt = keccak256(abi.encodePacked(_position, _expiration)); bytes32 addressBytes = keccak256( abi.encodePacked( bytes1(0xff), _trancheFactory, salt, _trancheBytecodeHash ) ); return ITranche(address(uint160(uint256(addressBytes)))); } /// @dev This contract holds a number of allowances for addresses so if it is deprecated /// it should be removed so that users do not have to remove allowances. /// Note - onlyOwner is a stronger check than onlyAuthorized, many addresses can be /// authorized to freeze or unfreeze the contract but only the owner address can kill function deprecate() external onlyOwner() { selfdestruct(payable(msg.sender)); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; interface IERC20 { function symbol() external view returns (string memory); function balanceOf(address account) external view returns (uint256); // Note this is non standard but nearly all ERC20 have exposed decimal functions function decimals() external view returns (uint8); 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 ); } // Forked from openzepplin // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit is IERC20 { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./IERC20Permit.sol"; import "./IInterestToken.sol"; interface ITranche is IERC20Permit { function deposit(uint256 _shares, address destination) external returns (uint256, uint256); function prefundedDeposit(address _destination) external returns (uint256, uint256); function withdrawPrincipal(uint256 _amount, address _destination) external returns (uint256); function withdrawInterest(uint256 _amount, address _destination) external returns (uint256); function interestToken() external view returns (IInterestToken); function interestSupply() external view returns (uint128); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./IERC20.sol"; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./IERC20Permit.sol"; import "./IERC20.sol"; interface IWrappedPosition is IERC20Permit { function token() external view returns (IERC20); function balanceOfUnderlying(address who) external view returns (uint256); function getSharesToUnderlying(uint256 shares) external view returns (uint256); function deposit(address sender, uint256 amount) external returns (uint256); function withdraw( address sender, uint256 _shares, uint256 _minUnderlying ) external returns (uint256); function withdrawUnderlying( address _destination, uint256 _amount, uint256 _minUnderlying ) external returns (uint256, uint256); function prefundedDeposit(address _destination) external returns ( uint256, uint256, uint256 ); } // SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.7.0; contract Authorizable { // This contract allows a flexible authorization scheme // The owner who can change authorization status address public owner; // A mapping from an address to its authorization status mapping(address => bool) public authorized; /// @dev We set the deployer to the owner constructor() { owner = msg.sender; } /// @dev This modifier checks if the msg.sender is the owner modifier onlyOwner() { require(msg.sender == owner, "Sender not owner"); _; } /// @dev This modifier checks if an address is authorized modifier onlyAuthorized() { require(isAuthorized(msg.sender), "Sender not Authorized"); _; } /// @dev Returns true if an address is authorized /// @param who the address to check /// @return true if authorized false if not function isAuthorized(address who) public view returns (bool) { return authorized[who]; } /// @dev Privileged function authorize an address /// @param who the address to authorize function authorize(address who) external onlyOwner() { _authorize(who); } /// @dev Privileged function to de authorize an address /// @param who The address to remove authorization from function deauthorize(address who) external onlyOwner() { authorized[who] = false; } /// @dev Function to change owner /// @param who The new owner address function setOwner(address who) public onlyOwner() { owner = who; } /// @dev Inheritable function which authorizes someone /// @param who the address to authorize function _authorize(address who) internal { authorized[who] = true; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./IERC20Permit.sol"; interface IInterestToken is IERC20Permit { function mint(address _account, uint256 _amount) external; function burn(address _account, uint256 _amount) external; }
@author Element Finance @title User Proxy This contract is a convenience library to consolidate the actions needed to create interest or principal tokens to one call. It will hold user allowances, and can be disabled by authorized addresses for security. If frozen users still control their own tokens so can manually redeem them. Store the accessibility state of the contract Constant wrapped ether address Tranche factory address for Tranche contract address derivation Tranche bytecode hash for Tranche contract address derivation. This is constant as long as Tranche does not implement non-constant constructor arguments. A constant which represents ether
contract UserProxy is Authorizable { bool public isFrozen = false; IWETH public immutable weth; address internal immutable _trancheFactory; bytes32 internal immutable _trancheBytecodeHash; address internal constant _ETH_CONSTANT = address( 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ); constructor( IWETH _weth, address __trancheFactory, bytes32 __trancheBytecodeHash pragma solidity ^0.8.0; ) Authorizable() { _authorize(msg.sender); weth = _weth; _trancheFactory = __trancheFactory; _trancheBytecodeHash = __trancheBytecodeHash; } modifier notFrozen() { require(!isFrozen, "Contract frozen"); _; } function setIsFrozen(bool _newState) external onlyAuthorized() { isFrozen = _newState; } struct PermitData { IERC20Permit tokenContract; address who; uint256 amount; uint256 expiration; bytes32 r; bytes32 s; uint8 v; } modifier preApproval(PermitData[] memory data) { if (data.length != 0) { for (uint256 i = 0; i < data.length; i++) { _permitCall(data[i]); } } _; } modifier preApproval(PermitData[] memory data) { if (data.length != 0) { for (uint256 i = 0; i < data.length; i++) { _permitCall(data[i]); } } _; } modifier preApproval(PermitData[] memory data) { if (data.length != 0) { for (uint256 i = 0; i < data.length; i++) { _permitCall(data[i]); } } _; } function _permitCall(PermitData memory data) internal { data.tokenContract.permit( msg.sender, data.who, data.amount, data.expiration, data.v, data.r, data.s ); } function mint( uint256 _amount, IERC20 _underlying, uint256 _expiration, address _position, PermitData[] calldata _permitCallData ) external payable notFrozen() preApproval(_permitCallData) returns (uint256, uint256) { if (address(_underlying) == _ETH_CONSTANT) { require(msg.value == _amount, "Incorrect amount provided"); weth.transfer(address(_position), _amount); require(msg.value == 0, "Non payable"); _underlying.transferFrom(msg.sender, address(_position), _amount); } return (ptMinted, ytMinted); } function mint( uint256 _amount, IERC20 _underlying, uint256 _expiration, address _position, PermitData[] calldata _permitCallData ) external payable notFrozen() preApproval(_permitCallData) returns (uint256, uint256) { if (address(_underlying) == _ETH_CONSTANT) { require(msg.value == _amount, "Incorrect amount provided"); weth.transfer(address(_position), _amount); require(msg.value == 0, "Non payable"); _underlying.transferFrom(msg.sender, address(_position), _amount); } return (ptMinted, ytMinted); } weth.deposit{ value: msg.value }(); } else { (uint256 ptMinted, uint256 ytMinted) = _mint(_expiration, _position); require(ytMinted >= _amount, "Not enough minted"); function withdrawWeth( uint256 _expiration, address _position, uint256 _amountPT, uint256 _amountYT, PermitData[] calldata _permitCallData ) external notFrozen() preApproval(_permitCallData) { require(IWrappedPosition(_position).token() == weth, "Non weth token"); require(((_amountPT != 0) || (_amountYT != 0)), "Invalid withdraw"); ITranche derivedTranche = _deriveTranche(_position, _expiration); uint256 wethReceivedPt = 0; uint256 wethReceivedYt = 0; if (_amountPT != 0) { derivedTranche.transferFrom(msg.sender, address(this), _amountPT); wethReceivedPt = derivedTranche.withdrawPrincipal( _amountPT, address(this) ); } if (_amountYT != 0) { IERC20Permit yieldToken = derivedTranche.interestToken(); yieldToken.transferFrom(msg.sender, address(this), _amountYT); wethReceivedYt = derivedTranche.withdrawInterest( _amountYT, address(this) ); } if (_amountPT != 0) { require((wethReceivedPt != 0), "Rugged"); } if (_amountYT != 0) { require((wethReceivedYt != 0), "No yield accrued"); } } function withdrawWeth( uint256 _expiration, address _position, uint256 _amountPT, uint256 _amountYT, PermitData[] calldata _permitCallData ) external notFrozen() preApproval(_permitCallData) { require(IWrappedPosition(_position).token() == weth, "Non weth token"); require(((_amountPT != 0) || (_amountYT != 0)), "Invalid withdraw"); ITranche derivedTranche = _deriveTranche(_position, _expiration); uint256 wethReceivedPt = 0; uint256 wethReceivedYt = 0; if (_amountPT != 0) { derivedTranche.transferFrom(msg.sender, address(this), _amountPT); wethReceivedPt = derivedTranche.withdrawPrincipal( _amountPT, address(this) ); } if (_amountYT != 0) { IERC20Permit yieldToken = derivedTranche.interestToken(); yieldToken.transferFrom(msg.sender, address(this), _amountYT); wethReceivedYt = derivedTranche.withdrawInterest( _amountYT, address(this) ); } if (_amountPT != 0) { require((wethReceivedPt != 0), "Rugged"); } if (_amountYT != 0) { require((wethReceivedYt != 0), "No yield accrued"); } } function withdrawWeth( uint256 _expiration, address _position, uint256 _amountPT, uint256 _amountYT, PermitData[] calldata _permitCallData ) external notFrozen() preApproval(_permitCallData) { require(IWrappedPosition(_position).token() == weth, "Non weth token"); require(((_amountPT != 0) || (_amountYT != 0)), "Invalid withdraw"); ITranche derivedTranche = _deriveTranche(_position, _expiration); uint256 wethReceivedPt = 0; uint256 wethReceivedYt = 0; if (_amountPT != 0) { derivedTranche.transferFrom(msg.sender, address(this), _amountPT); wethReceivedPt = derivedTranche.withdrawPrincipal( _amountPT, address(this) ); } if (_amountYT != 0) { IERC20Permit yieldToken = derivedTranche.interestToken(); yieldToken.transferFrom(msg.sender, address(this), _amountYT); wethReceivedYt = derivedTranche.withdrawInterest( _amountYT, address(this) ); } if (_amountPT != 0) { require((wethReceivedPt != 0), "Rugged"); } if (_amountYT != 0) { require((wethReceivedYt != 0), "No yield accrued"); } } function withdrawWeth( uint256 _expiration, address _position, uint256 _amountPT, uint256 _amountYT, PermitData[] calldata _permitCallData ) external notFrozen() preApproval(_permitCallData) { require(IWrappedPosition(_position).token() == weth, "Non weth token"); require(((_amountPT != 0) || (_amountYT != 0)), "Invalid withdraw"); ITranche derivedTranche = _deriveTranche(_position, _expiration); uint256 wethReceivedPt = 0; uint256 wethReceivedYt = 0; if (_amountPT != 0) { derivedTranche.transferFrom(msg.sender, address(this), _amountPT); wethReceivedPt = derivedTranche.withdrawPrincipal( _amountPT, address(this) ); } if (_amountYT != 0) { IERC20Permit yieldToken = derivedTranche.interestToken(); yieldToken.transferFrom(msg.sender, address(this), _amountYT); wethReceivedYt = derivedTranche.withdrawInterest( _amountYT, address(this) ); } if (_amountPT != 0) { require((wethReceivedPt != 0), "Rugged"); } if (_amountYT != 0) { require((wethReceivedYt != 0), "No yield accrued"); } } function withdrawWeth( uint256 _expiration, address _position, uint256 _amountPT, uint256 _amountYT, PermitData[] calldata _permitCallData ) external notFrozen() preApproval(_permitCallData) { require(IWrappedPosition(_position).token() == weth, "Non weth token"); require(((_amountPT != 0) || (_amountYT != 0)), "Invalid withdraw"); ITranche derivedTranche = _deriveTranche(_position, _expiration); uint256 wethReceivedPt = 0; uint256 wethReceivedYt = 0; if (_amountPT != 0) { derivedTranche.transferFrom(msg.sender, address(this), _amountPT); wethReceivedPt = derivedTranche.withdrawPrincipal( _amountPT, address(this) ); } if (_amountYT != 0) { IERC20Permit yieldToken = derivedTranche.interestToken(); yieldToken.transferFrom(msg.sender, address(this), _amountYT); wethReceivedYt = derivedTranche.withdrawInterest( _amountYT, address(this) ); } if (_amountPT != 0) { require((wethReceivedPt != 0), "Rugged"); } if (_amountYT != 0) { require((wethReceivedYt != 0), "No yield accrued"); } } weth.withdraw(wethReceivedPt + wethReceivedYt); payable(msg.sender).transfer(wethReceivedPt + wethReceivedYt); receive() external payable { require(msg.sender == address(weth)); } function _mint(uint256 _expiration, address _position) internal returns (uint256, uint256) { ITranche tranche = _deriveTranche(address(_position), _expiration); return tranche.prefundedDeposit(msg.sender); } function _deriveTranche(address _position, uint256 _expiration) internal virtual view returns (ITranche) { bytes32 salt = keccak256(abi.encodePacked(_position, _expiration)); bytes32 addressBytes = keccak256( abi.encodePacked( bytes1(0xff), _trancheFactory, salt, _trancheBytecodeHash ) ); return ITranche(address(uint160(uint256(addressBytes)))); } function deprecate() external onlyOwner() { selfdestruct(payable(msg.sender)); } }
10,460,005
[ 1, 1046, 9458, 1359, 225, 2177, 7659, 1220, 6835, 353, 279, 13553, 5313, 358, 21785, 340, 326, 4209, 3577, 358, 752, 16513, 578, 8897, 2430, 358, 1245, 745, 18, 2597, 903, 6887, 729, 1699, 6872, 16, 471, 848, 506, 5673, 635, 10799, 6138, 364, 4373, 18, 971, 12810, 3677, 4859, 3325, 3675, 4953, 2430, 1427, 848, 10036, 283, 24903, 2182, 18, 4994, 326, 2006, 3628, 919, 434, 326, 6835, 10551, 5805, 225, 2437, 1758, 840, 304, 18706, 3272, 1758, 364, 840, 304, 18706, 6835, 1758, 4854, 8482, 840, 304, 18706, 22801, 1651, 364, 840, 304, 18706, 6835, 1758, 4854, 8482, 18, 1220, 353, 5381, 487, 1525, 487, 840, 304, 18706, 1552, 486, 2348, 1661, 17, 14384, 3885, 1775, 18, 432, 5381, 1492, 8686, 225, 2437, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2177, 3886, 353, 3123, 5331, 429, 288, 203, 203, 565, 1426, 1071, 17646, 9808, 273, 629, 31, 203, 565, 467, 59, 1584, 44, 1071, 11732, 341, 546, 31, 203, 565, 1758, 2713, 11732, 389, 13171, 18706, 1733, 31, 203, 565, 1731, 1578, 2713, 11732, 389, 13171, 18706, 858, 16651, 2310, 31, 203, 565, 1758, 2713, 5381, 389, 1584, 44, 67, 25878, 273, 1758, 12, 203, 3639, 374, 17432, 1340, 1340, 41, 1340, 73, 41, 73, 41, 1340, 41, 73, 41, 73, 41, 1340, 9383, 41, 1340, 1340, 41, 1340, 1340, 1340, 73, 9383, 73, 41, 203, 565, 11272, 203, 203, 565, 3885, 12, 203, 3639, 467, 59, 1584, 44, 389, 91, 546, 16, 203, 3639, 1758, 1001, 13171, 18706, 1733, 16, 203, 3639, 1731, 1578, 1001, 13171, 18706, 858, 16651, 2310, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 262, 3123, 5331, 429, 1435, 288, 203, 3639, 389, 22488, 12, 3576, 18, 15330, 1769, 203, 3639, 341, 546, 273, 389, 91, 546, 31, 203, 3639, 389, 13171, 18706, 1733, 273, 1001, 13171, 18706, 1733, 31, 203, 3639, 389, 13171, 18706, 858, 16651, 2310, 273, 1001, 13171, 18706, 858, 16651, 2310, 31, 203, 565, 289, 203, 203, 565, 9606, 486, 42, 9808, 1435, 288, 203, 3639, 2583, 12, 5, 291, 42, 9808, 16, 315, 8924, 12810, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 15269, 42, 9808, 12, 6430, 389, 2704, 1119, 13, 3903, 1338, 15341, 1435, 288, 203, 3639, 17646, 9808, 273, 389, 2 ]
./partial_match/3/0x080c8B445F49ed778aD1019A1e2f95937E36Bfd8/sources/NexenPlatform.sol
IERC20 daiToken = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); Mainnet
contract NexenPlatform is Ownable { using SafeMath for uint256; IERC20 nexenToken; IERC20 daiToken = IERC20(0xF9E53E22Abd078B56685A796902E2dF1F5cbda5e); IPriceConsumerV3DaiWei priceConsumer; IUniswapV2Router02 uniswapRouter; bool public paused = false; bool public genesisPhase = true; uint256 public amountToReward = 1000 * 10 ** 18; mapping(address => uint256) public depositedDAIByAddress; mapping(address => uint256) public depositedWEIByAddress; enum RequestState {None, LenderCreated, BorrowerCreated, Cancelled, Matched, Closed, Expired, Disabled} struct Request { RequestState state; address payable borrower; address payable lender; uint256 daiAmount; uint256 durationInDays; uint256 expireIfNotMatchedOn; uint256 ltv; uint256 weiAmount; uint256 daiVsWeiCurrentPrice; uint256 lendingFinishesOn; } event OpenRequest(uint256 requestId, address indexed borrower, address indexed lender, uint256 daiAmount, uint256 durationInDays, uint256 expireIfNotMatchedOn, uint256 ltv, uint256 weiAmount, uint256 ethVsDaiCurrentPrice, uint256 lendingFinishesOn, RequestState state); event UpdateRequest(uint256 requestId, address indexed borrower, address indexed lender, RequestState state); event CollateralSold(uint256 requestId, uint256 totalCollateral, uint256 totalSold, uint256 totalDAIBought); uint256 public daiFees; uint256 public ethFees; mapping (uint256 => Request) public requests; receive() external payable { depositETH(); } constructor(IERC20 _nexenToken, IPriceConsumerV3DaiWei _priceConsumer, IUniswapV2Router02 _uniswapRouter) { nexenToken = _nexenToken; priceConsumer = _priceConsumer; uniswapRouter = _uniswapRouter; } function calculateWeiAmount(uint256 _daiAmount, uint256 _ltv, uint256 _daiVsWeiCurrentPrice) public pure returns (uint256) { return _daiAmount.mul(100).div(_ltv).mul(_daiVsWeiCurrentPrice).div(1e18); } function depositETH() public payable { require(msg.value > 10000000000000000, 'Minimum is 0.01 ETH'); depositedWEIByAddress[msg.sender] += msg.value; } function depositDAI(uint256 _amount) public { require(IERC20(daiToken).transferFrom(msg.sender, address(this), _amount), "Couldn't take the DAI from the sender"); depositedDAIByAddress[msg.sender] += _amount; } function _setGenesisPhase(bool _genesisPhase, uint256 _amountToReward) public onlyOwner { genesisPhase = _genesisPhase; amountToReward = _amountToReward; } function _setPaused(bool _paused) public onlyOwner { paused = _paused; } function calculateCollateral(uint256 daiAmount, uint256 ltv) public view returns (uint256) { uint256 daiVsWeiCurrentPrice = uint256(priceConsumer.getLatestPrice()); uint256 weiAmount = calculateWeiAmount(daiAmount, ltv, daiVsWeiCurrentPrice); return weiAmount; } function createRequest(bool lend, uint256 daiAmount, uint256 durationInDays, uint256 expireIfNotMatchedOn, uint256 ltv) public { require(daiAmount >= 100 * 10 ** 18, "Minimum amount is 100 DAI"); require(expireIfNotMatchedOn > block.timestamp, "Invalid expiration date"); require(!paused, "The contract is paused"); Request memory r; (r.daiAmount, r.durationInDays, r.expireIfNotMatchedOn) = (daiAmount, durationInDays, expireIfNotMatchedOn); if (lend) { r.lender = msg.sender; r.state = RequestState.LenderCreated; require(depositedDAIByAddress[msg.sender] >= r.daiAmount, "Not enough DAI deposited"); depositedDAIByAddress[msg.sender] -= r.daiAmount; require(ltv == 20 || ltv == 40 || ltv == 60, 'Invalid ltv'); r.borrower = msg.sender; r.state = RequestState.BorrowerCreated; r.ltv = ltv; r.daiVsWeiCurrentPrice = uint256(priceConsumer.getLatestPrice()); r.weiAmount = calculateWeiAmount(daiAmount, ltv, r.daiVsWeiCurrentPrice); require(depositedWEIByAddress[msg.sender] > r.weiAmount, "Not enough ETH deposited"); depositedWEIByAddress[msg.sender] -= r.weiAmount; } if (genesisPhase) { require(nexenToken.transfer(msg.sender, amountToReward), 'Could not transfer tokens'); } uint256 requestId = uint256(keccak256(abi.encodePacked(r.borrower, r.lender, r.daiAmount, r.durationInDays, r.expireIfNotMatchedOn, r.ltv))); require(requests[requestId].state == RequestState.None, 'Request already exists'); requests[requestId] = r; emit OpenRequest(requestId, r.borrower, r.lender, r.daiAmount, r.durationInDays, r.expireIfNotMatchedOn, r.ltv, r.weiAmount, r.daiVsWeiCurrentPrice, r.lendingFinishesOn, r.state); } function createRequest(bool lend, uint256 daiAmount, uint256 durationInDays, uint256 expireIfNotMatchedOn, uint256 ltv) public { require(daiAmount >= 100 * 10 ** 18, "Minimum amount is 100 DAI"); require(expireIfNotMatchedOn > block.timestamp, "Invalid expiration date"); require(!paused, "The contract is paused"); Request memory r; (r.daiAmount, r.durationInDays, r.expireIfNotMatchedOn) = (daiAmount, durationInDays, expireIfNotMatchedOn); if (lend) { r.lender = msg.sender; r.state = RequestState.LenderCreated; require(depositedDAIByAddress[msg.sender] >= r.daiAmount, "Not enough DAI deposited"); depositedDAIByAddress[msg.sender] -= r.daiAmount; require(ltv == 20 || ltv == 40 || ltv == 60, 'Invalid ltv'); r.borrower = msg.sender; r.state = RequestState.BorrowerCreated; r.ltv = ltv; r.daiVsWeiCurrentPrice = uint256(priceConsumer.getLatestPrice()); r.weiAmount = calculateWeiAmount(daiAmount, ltv, r.daiVsWeiCurrentPrice); require(depositedWEIByAddress[msg.sender] > r.weiAmount, "Not enough ETH deposited"); depositedWEIByAddress[msg.sender] -= r.weiAmount; } if (genesisPhase) { require(nexenToken.transfer(msg.sender, amountToReward), 'Could not transfer tokens'); } uint256 requestId = uint256(keccak256(abi.encodePacked(r.borrower, r.lender, r.daiAmount, r.durationInDays, r.expireIfNotMatchedOn, r.ltv))); require(requests[requestId].state == RequestState.None, 'Request already exists'); requests[requestId] = r; emit OpenRequest(requestId, r.borrower, r.lender, r.daiAmount, r.durationInDays, r.expireIfNotMatchedOn, r.ltv, r.weiAmount, r.daiVsWeiCurrentPrice, r.lendingFinishesOn, r.state); } } else { function createRequest(bool lend, uint256 daiAmount, uint256 durationInDays, uint256 expireIfNotMatchedOn, uint256 ltv) public { require(daiAmount >= 100 * 10 ** 18, "Minimum amount is 100 DAI"); require(expireIfNotMatchedOn > block.timestamp, "Invalid expiration date"); require(!paused, "The contract is paused"); Request memory r; (r.daiAmount, r.durationInDays, r.expireIfNotMatchedOn) = (daiAmount, durationInDays, expireIfNotMatchedOn); if (lend) { r.lender = msg.sender; r.state = RequestState.LenderCreated; require(depositedDAIByAddress[msg.sender] >= r.daiAmount, "Not enough DAI deposited"); depositedDAIByAddress[msg.sender] -= r.daiAmount; require(ltv == 20 || ltv == 40 || ltv == 60, 'Invalid ltv'); r.borrower = msg.sender; r.state = RequestState.BorrowerCreated; r.ltv = ltv; r.daiVsWeiCurrentPrice = uint256(priceConsumer.getLatestPrice()); r.weiAmount = calculateWeiAmount(daiAmount, ltv, r.daiVsWeiCurrentPrice); require(depositedWEIByAddress[msg.sender] > r.weiAmount, "Not enough ETH deposited"); depositedWEIByAddress[msg.sender] -= r.weiAmount; } if (genesisPhase) { require(nexenToken.transfer(msg.sender, amountToReward), 'Could not transfer tokens'); } uint256 requestId = uint256(keccak256(abi.encodePacked(r.borrower, r.lender, r.daiAmount, r.durationInDays, r.expireIfNotMatchedOn, r.ltv))); require(requests[requestId].state == RequestState.None, 'Request already exists'); requests[requestId] = r; emit OpenRequest(requestId, r.borrower, r.lender, r.daiAmount, r.durationInDays, r.expireIfNotMatchedOn, r.ltv, r.weiAmount, r.daiVsWeiCurrentPrice, r.lendingFinishesOn, r.state); } function matchRequestAsLender(uint256 requestId) public { Request storage r = requests[requestId]; require(r.state == RequestState.BorrowerCreated, 'Invalid request'); require(r.expireIfNotMatchedOn > block.timestamp, 'Request expired'); r.lender = msg.sender; r.lendingFinishesOn = getExpirationAfter(r.durationInDays); r.state = RequestState.Matched; require(depositedDAIByAddress[msg.sender] >= r.daiAmount, "Not enough DAI deposited"); depositedDAIByAddress[msg.sender] = depositedDAIByAddress[msg.sender].sub(r.daiAmount); depositedDAIByAddress[r.borrower] = depositedDAIByAddress[r.borrower].add(r.daiAmount); emit UpdateRequest(requestId, r.borrower, r.lender, r.state); } function getLatestDaiVsWeiPrice() public view returns (uint256) { return uint256(priceConsumer.getLatestPrice()); } function matchRequestAsBorrower(uint256 requestId, uint256 ltv) public { Request storage r = requests[requestId]; require(r.state == RequestState.LenderCreated, 'Invalid request'); require(r.expireIfNotMatchedOn > block.timestamp, 'Request expired'); r.borrower = msg.sender; r.lendingFinishesOn = getExpirationAfter(r.durationInDays); r.state = RequestState.Matched; r.ltv = ltv; r.daiVsWeiCurrentPrice = uint256(priceConsumer.getLatestPrice()); r.weiAmount = calculateWeiAmount(r.daiAmount, r.ltv, r.daiVsWeiCurrentPrice); require(depositedWEIByAddress[msg.sender] > r.weiAmount, "Not enough WEI"); depositedWEIByAddress[msg.sender] = depositedWEIByAddress[msg.sender].sub(r.weiAmount); depositedDAIByAddress[r.borrower] = depositedDAIByAddress[r.borrower].add(r.daiAmount); emit UpdateRequest(requestId, r.borrower, r.lender, r.state); } function cancelRequest(uint256 requestId) public { Request storage r = requests[requestId]; require(r.state == RequestState.BorrowerCreated || r.state == RequestState.LenderCreated); r.state = RequestState.Cancelled; if (msg.sender == r.borrower) { depositedWEIByAddress[msg.sender] += r.weiAmount; depositedDAIByAddress[msg.sender] += r.daiAmount; revert(); } emit UpdateRequest(requestId, r.borrower, r.lender, r.state); } function cancelRequest(uint256 requestId) public { Request storage r = requests[requestId]; require(r.state == RequestState.BorrowerCreated || r.state == RequestState.LenderCreated); r.state = RequestState.Cancelled; if (msg.sender == r.borrower) { depositedWEIByAddress[msg.sender] += r.weiAmount; depositedDAIByAddress[msg.sender] += r.daiAmount; revert(); } emit UpdateRequest(requestId, r.borrower, r.lender, r.state); } } else if (msg.sender == r.lender) { } else { function finishRequest(uint256 _requestId) public { Request storage r = requests[_requestId]; require(r.state == RequestState.Matched, "State needs to be Matched"); require(msg.sender == r.borrower, 'Only borrower can call this'); r.state = RequestState.Closed; uint256 daiToTransfer = getInterest(r.ltv, r.daiAmount).add(r.daiAmount); require(depositedDAIByAddress[r.borrower] >= daiToTransfer, "Not enough DAI deposited"); uint256 totalLenderFee = computeLenderFee(r.daiAmount); uint256 totalBorrowerFee = computeBorrowerFee(r.weiAmount); daiFees = daiFees.add(totalLenderFee); ethFees = ethFees.add(totalBorrowerFee); depositedDAIByAddress[r.lender] += daiToTransfer.sub(totalLenderFee); depositedDAIByAddress[r.borrower] -= daiToTransfer; depositedWEIByAddress[r.borrower] += r.weiAmount.sub(totalBorrowerFee); emit UpdateRequest(_requestId, r.borrower, r.lender, r.state); } function canBurnCollateral(uint256 requestId, uint256 daiVsWeiCurrentPrice) public view returns (bool) { Request memory r = requests[requestId]; uint256 howMuchEthTheUserCanGet = r.daiAmount.mul(daiVsWeiCurrentPrice).div(1e18); uint256 eigthyPercentOfCollateral = r.weiAmount.mul(8).div(10); return howMuchEthTheUserCanGet > eigthyPercentOfCollateral; } function expireNonFullfiledRequest(uint256 _requestId) public { Request storage r = requests[_requestId]; require(r.state == RequestState.Matched, "State needs to be Matched"); require(msg.sender == r.lender, "Only lender can call this"); require(block.timestamp > r.lendingFinishesOn, "Request not finished yet"); r.state = RequestState.Expired; burnCollateral(_requestId, r); } function _expireRequest(uint256 _requestId) public onlyOwner { Request storage r = requests[_requestId]; require(r.state == RequestState.Matched, "State needs to be Matched"); uint256 daiVsWeiCurrentPrice = uint256(priceConsumer.getLatestPrice()); require(canBurnCollateral(_requestId, daiVsWeiCurrentPrice), "We cannot burn the collateral"); r.state = RequestState.Disabled; burnCollateral(_requestId, r); } function burnCollateral(uint256 _requestId, Request storage r) internal { uint256 daiToTransfer = getInterest(r.ltv, r.daiAmount).add(r.daiAmount); uint256[] memory amounts = sellCollateralInUniswap(daiToTransfer, r.weiAmount); uint256 dust = r.weiAmount.sub(amounts[0]); uint256 totalLenderFee = computeLenderFee(r.daiAmount); uint256 totalBorrowerFee = computeBorrowerFee(r.weiAmount); if (totalBorrowerFee > dust) { totalBorrowerFee = dust; } daiFees = daiFees.add(totalLenderFee); ethFees = ethFees.add(totalBorrowerFee); depositedWEIByAddress[r.borrower] += dust.sub(totalBorrowerFee); depositedDAIByAddress[r.lender] += daiToTransfer.sub(totalLenderFee); emit CollateralSold(_requestId, r.weiAmount, amounts[0], daiToTransfer); emit UpdateRequest(_requestId, r.borrower, r.lender, r.state); } function burnCollateral(uint256 _requestId, Request storage r) internal { uint256 daiToTransfer = getInterest(r.ltv, r.daiAmount).add(r.daiAmount); uint256[] memory amounts = sellCollateralInUniswap(daiToTransfer, r.weiAmount); uint256 dust = r.weiAmount.sub(amounts[0]); uint256 totalLenderFee = computeLenderFee(r.daiAmount); uint256 totalBorrowerFee = computeBorrowerFee(r.weiAmount); if (totalBorrowerFee > dust) { totalBorrowerFee = dust; } daiFees = daiFees.add(totalLenderFee); ethFees = ethFees.add(totalBorrowerFee); depositedWEIByAddress[r.borrower] += dust.sub(totalBorrowerFee); depositedDAIByAddress[r.lender] += daiToTransfer.sub(totalLenderFee); emit CollateralSold(_requestId, r.weiAmount, amounts[0], daiToTransfer); emit UpdateRequest(_requestId, r.borrower, r.lender, r.state); } function sellCollateralInUniswap(uint256 daiToTransfer, uint256 weiAmount) internal returns (uint256[] memory) { address[] memory path = new address[](2); path[0] = uniswapRouter.WETH(); path[1] = address(daiToken); } return uniswapRouter.swapETHForExactTokens{value:weiAmount}(daiToTransfer, path, address(this), block.timestamp); function getInterest(uint256 _ltv, uint256 _daiAmount) public pure returns (uint256) { if (_ltv == 20) { return _daiAmount.mul(4).div(100); return _daiAmount.mul(6).div(100); return _daiAmount.mul(8).div(100); } revert(); } function getInterest(uint256 _ltv, uint256 _daiAmount) public pure returns (uint256) { if (_ltv == 20) { return _daiAmount.mul(4).div(100); return _daiAmount.mul(6).div(100); return _daiAmount.mul(8).div(100); } revert(); } } else if (_ltv == 40) { } else if (_ltv == 60) { function _withdrawDaiFees(uint256 _amount) public onlyOwner { require(daiFees >= _amount, "Invalid number"); daiFees -= _amount; require(daiToken.transfer(msg.sender, _amount), "Transfer failed"); } function _withdrawEthFees(uint256 _amount) public onlyOwner { require(ethFees >= _amount, "Invalid number"); ethFees -= _amount; msg.sender.transfer(_amount); } function withdrawDai(uint256 _amount) public { require(depositedDAIByAddress[msg.sender] >= _amount); depositedDAIByAddress[msg.sender] = depositedDAIByAddress[msg.sender].sub(_amount); require(daiToken.transfer(msg.sender, _amount)); } function withdrawEth(uint256 _amount) public { require(depositedWEIByAddress[msg.sender] >= _amount); depositedWEIByAddress[msg.sender] = depositedWEIByAddress[msg.sender].sub(_amount); msg.sender.transfer(_amount); } function computeLenderFee(uint256 _value) public view returns (uint256) { return _value.mul(lenderFee).div(100); } function computeBorrowerFee(uint256 _value) public view returns (uint256) { return _value.mul(borrowerFee).div(100); } function getExpirationAfter(uint256 amountOfDays) public view returns (uint256) { return block.timestamp.add(amountOfDays.mul(1 days)); } function requestInfo(uint256 requestId) public view returns (uint256 _tradeId, RequestState _state, address _borrower, address _lender, uint256 _daiAmount, uint256 _durationInDays, uint256 _expireIfNotMatchedOn, uint256 _ltv, uint256 _weiAmount, uint256 _daiVsWeiCurrentPrice, uint256 _lendingFinishesOn) { Request storage r = requests[requestId]; return (requestId, r.state, r.borrower, r.lender, r.daiAmount, r.durationInDays, r.expireIfNotMatchedOn, r.ltv, r.weiAmount, r.daiVsWeiCurrentPrice, r.lendingFinishesOn); } }
5,333,168
[ 1, 45, 654, 39, 3462, 5248, 77, 1345, 273, 467, 654, 39, 3462, 12, 20, 92, 26, 38, 4033, 6564, 5608, 41, 6675, 5908, 24, 39, 6334, 40, 69, 10689, 70, 29, 6564, 41, 73, 323, 2226, 7616, 25, 5324, 21, 72, 20, 42, 1769, 12740, 2758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 423, 338, 275, 8201, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 377, 203, 377, 203, 565, 467, 654, 39, 3462, 290, 338, 275, 1345, 31, 203, 565, 467, 654, 39, 3462, 5248, 77, 1345, 273, 467, 654, 39, 3462, 12, 20, 16275, 29, 41, 8643, 41, 3787, 5895, 72, 20, 8285, 38, 4313, 26, 7140, 37, 7235, 8148, 3103, 41, 22, 72, 42, 21, 42, 25, 7358, 2414, 25, 73, 1769, 203, 565, 2971, 3057, 5869, 58, 23, 40, 10658, 3218, 77, 6205, 5869, 31, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 640, 291, 91, 438, 8259, 31, 203, 377, 203, 565, 1426, 1071, 17781, 273, 629, 31, 203, 565, 1426, 1071, 21906, 11406, 273, 638, 31, 203, 565, 2254, 5034, 1071, 3844, 774, 17631, 1060, 273, 4336, 380, 1728, 2826, 6549, 31, 203, 377, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 443, 1724, 329, 9793, 45, 858, 1887, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 443, 1724, 329, 6950, 45, 858, 1887, 31, 203, 203, 565, 2792, 1567, 1119, 288, 7036, 16, 511, 2345, 6119, 16, 605, 15318, 264, 6119, 16, 10347, 1259, 16, 4639, 329, 16, 25582, 16, 7784, 2921, 16, 28970, 97, 203, 565, 1958, 1567, 288, 203, 3639, 1567, 1119, 919, 31, 203, 3639, 1758, 8843, 429, 29759, 264, 31, 203, 3639, 1758, 8843, 429, 328, 2345, 31, 203, 3639, 2254, 5034, 5248, 77, 6275, 31, 203, 3639, 2254, 5034, 3734, 2 ]
./partial_match/1/0xA5553e3FCf1d003A53Ae9Bd8E94FaC2F4d5E0913/sources/BubbleMaster.sol
Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
15,888,303
[ 1, 19594, 12423, 1147, 358, 4042, 12423, 6835, 18, 4480, 506, 2566, 635, 1281, 476, 18, 1660, 10267, 716, 30188, 6835, 353, 7494, 18, 445, 13187, 12, 11890, 5034, 389, 6610, 13, 1071, 288, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 2867, 12, 81, 2757, 639, 13, 480, 1758, 12, 20, 3631, 315, 22083, 30, 1158, 30188, 8863, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract DAX { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function DAX( ) public { totalSupply = 200000000000000000000000000; // Total supply with the decimal amount balanceOf[msg.sender] = 200000000000000000000000000; // All initial tokens name = "DAX Coin"; // The name for display purposes symbol = "DAX"; // The symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * 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) public { _transfer(msg.sender, _to, _value); } /** * 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) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
The symbol for display purposes
symbol = "DAX";
14,877,301
[ 1, 1986, 3273, 364, 2562, 13694, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 3273, 273, 315, 40, 2501, 14432, 4766, 10402, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xBf3B3b9368262Ed9BD06B621149CA947984D1B31/sources/@openzeppelin/contracts-upgradeable/interfaces/IERC4626Upgradeable.sol
* @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in _Available since v4.7._/
interface IERC4626Upgradeable is IERC20Upgradeable, IERC20MetadataUpgradeable { event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares); event Withdraw( address indexed sender, address indexed receiver, address indexed owner, uint256 assets, uint256 shares ); function asset() external view returns (address assetTokenAddress); function totalAssets() external view returns (uint256 totalManagedAssets); function convertToShares(uint256 assets) external view returns (uint256 shares); function convertToAssets(uint256 shares) external view returns (uint256 assets); function maxDeposit(address receiver) external view returns (uint256 maxAssets); function previewDeposit(uint256 assets) external view returns (uint256 shares); function deposit(uint256 assets, address receiver) external returns (uint256 shares); function maxMint(address receiver) external view returns (uint256 maxShares); function previewMint(uint256 shares) external view returns (uint256 assets); function mint(uint256 shares, address receiver) external returns (uint256 assets); function maxWithdraw(address owner) external view returns (uint256 maxAssets); function previewWithdraw(uint256 assets) external view returns (uint256 shares); function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares); function maxRedeem(address owner) external view returns (uint256 maxShares); function previewRedeem(uint256 shares) external view returns (uint256 assets); function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets); }
4,869,302
[ 1, 1358, 434, 326, 4232, 39, 8749, 5558, 315, 1345, 1235, 17329, 8263, 3113, 487, 2553, 316, 389, 5268, 3241, 331, 24, 18, 27, 6315, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 8749, 5558, 10784, 429, 353, 467, 654, 39, 3462, 10784, 429, 16, 467, 654, 39, 3462, 2277, 10784, 429, 288, 203, 565, 871, 4019, 538, 305, 12, 2867, 8808, 5793, 16, 1758, 8808, 3410, 16, 2254, 5034, 7176, 16, 2254, 5034, 24123, 1769, 203, 203, 565, 871, 3423, 9446, 12, 203, 3639, 1758, 8808, 5793, 16, 203, 3639, 1758, 8808, 5971, 16, 203, 3639, 1758, 8808, 3410, 16, 203, 3639, 2254, 5034, 7176, 16, 203, 3639, 2254, 5034, 24123, 203, 565, 11272, 203, 203, 565, 445, 3310, 1435, 3903, 1476, 1135, 261, 2867, 3310, 1345, 1887, 1769, 203, 203, 565, 445, 2078, 10726, 1435, 3903, 1476, 1135, 261, 11890, 5034, 2078, 10055, 10726, 1769, 203, 203, 565, 445, 8137, 24051, 12, 11890, 5034, 7176, 13, 3903, 1476, 1135, 261, 11890, 5034, 24123, 1769, 203, 203, 565, 445, 8137, 10726, 12, 11890, 5034, 24123, 13, 3903, 1476, 1135, 261, 11890, 5034, 7176, 1769, 203, 203, 565, 445, 943, 758, 1724, 12, 2867, 5971, 13, 3903, 1476, 1135, 261, 11890, 5034, 943, 10726, 1769, 203, 203, 565, 445, 10143, 758, 1724, 12, 11890, 5034, 7176, 13, 3903, 1476, 1135, 261, 11890, 5034, 24123, 1769, 203, 203, 565, 445, 443, 1724, 12, 11890, 5034, 7176, 16, 1758, 5971, 13, 3903, 1135, 261, 11890, 5034, 24123, 1769, 203, 203, 565, 445, 943, 49, 474, 12, 2867, 5971, 13, 3903, 1476, 1135, 261, 11890, 5034, 943, 24051, 1769, 203, 203, 565, 445, 10143, 49, 474, 12, 11890, 5034, 24123, 13, 3903, 1476, 1135, 261, 11890, 2 ]
pragma solidity ^0.4.8; contract Mediator { address public serviceConsumer; address public serviceProvider; uint public costPerRequest; uint public serviceConsumerFunds; uint public serviceProviderFunds; uint public terminationTimeout; uint public tokenRedemptionTimeout; uint public activeTokenId; uint public soonExpiringTokenId; uint public soonExpiringTokenIdTimeout; mapping (uint => uint) public redeemedTokenIds; // id => amountPayed uint public terminationStartedAt; // 0 = not started bool public terminated; event Error(uint8 code); event Redeemed(uint sum); event Payout(uint sum); function Mediator(address _serviceProvider, uint _initialTokenId, uint _costPerRequest, uint _terminationTimeout, uint _tokenRedemptionTimeout) { // Constructor serviceConsumer = msg.sender; serviceProvider = _serviceProvider; activeTokenId = _initialTokenId; serviceConsumerFunds = 0; serviceProviderFunds = 0; terminationStartedAt = 0; costPerRequest = _costPerRequest; terminationTimeout = _terminationTimeout; tokenRedemptionTimeout = _tokenRedemptionTimeout; terminated = false; } function depositForServiceConsumer() payable public { if (terminated) { Error(1); return; } if (msg.sender != serviceConsumer) { Error(3); return; } serviceConsumerFunds = serviceConsumerFunds + msg.value; } function payoutForServiceProvider() public { if (terminated) { Error(1); return; } if (msg.sender != serviceProvider) { Error(2); return; } if (serviceProviderFunds == 0) { return; } uint amount = serviceProviderFunds; serviceProviderFunds = 0; if (amount > 0) { if(!serviceProvider.send(amount)) { throw; } } Payout(amount); } function redeemToken(uint numRequests, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public { if (terminated) { Error(1); return; } if (msg.sender != serviceProvider) { Error(2); return; } if (now < soonExpiringTokenIdTimeout) { Error(30); return; } if (soonExpiringTokenId == 0) { Error(39); return; } bytes32 computedHash = sha256(serviceConsumer, soonExpiringTokenId, this, numRequests); if (computedHash != hash) { Error(4); return; } if(ecrecover(hash, v, r, s) != serviceConsumer) { Error(4); return; } uint amount = costPerRequest * numRequests; if (amount > serviceConsumerFunds) { Error(34); return; } redeemedTokenIds[soonExpiringTokenId] = amount; soonExpiringTokenId = 0; soonExpiringTokenIdTimeout = 0; serviceConsumerFunds = serviceConsumerFunds - amount; serviceProviderFunds = serviceProviderFunds + amount; Redeemed(amount); } function startTokenRedemption(uint newTokenID) public { if (terminated) { Error(1); return; } if (msg.sender != serviceProvider) { Error(2); return; } if (newTokenID == activeTokenId) { Error(31); return; } // do not allow current token id as the new one if (redeemedTokenIds[newTokenID] > 0) { Error(33); return; } // ID was already used once if (soonExpiringTokenId != 0) { Error(32); return; } // another token redemption is already in progress soonExpiringTokenId = activeTokenId; soonExpiringTokenIdTimeout = now + tokenRedemptionTimeout; if (terminationStartedAt == 0) { activeTokenId = newTokenID; } else { activeTokenId = 0; } } function startCloseThroughServiceConsumer() public { if (terminated) { Error(1); return; } if (msg.sender != serviceConsumer) { Error(3); return; } terminationStartedAt = now; } function finalizeCloseThroughServiceConsumer() public { if (terminated) { Error(1); return; } if (msg.sender != serviceConsumer) { Error(3); return; } if (terminationStartedAt == 0) { Error(40); return; } if (terminationStartedAt + terminationTimeout > now) { Error(41); return; } uint amountP = serviceProviderFunds; serviceProviderFunds = 0; if (amountP > 0) { if(!serviceProvider.send(amountP)) { throw; } } uint amountC = serviceConsumerFunds; serviceConsumerFunds = 0; if (amountC > 0) { if(!serviceConsumer.send(amountC)) { throw; } } terminated = true; } function closeThroughServiceProvider() public { if (terminated) { Error(1); return; } if (msg.sender != serviceProvider) { Error(2); return; } uint amountP = serviceProviderFunds; serviceProviderFunds = 0; if (amountP > 0) { if(!serviceProvider.send(amountP)) { throw; } } uint amountC = serviceConsumerFunds; serviceConsumerFunds = 0; if (amountC > 0) { if(!serviceConsumer.send(amountC)) { throw; } } terminated = true; } }
another token redemption is already in progress
if (soonExpiringTokenId != 0) { Error(32); return; }
946,218
[ 1, 304, 3011, 1147, 283, 19117, 375, 353, 1818, 316, 4007, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 309, 261, 2048, 265, 2966, 11256, 1345, 548, 480, 374, 13, 288, 1068, 12, 1578, 1769, 327, 31, 289, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; //TODO reward system //TODO reward token //TODO rarity calculator contract Masterdemon is Ownable { using SafeMath for uint256; using Address for address; struct NftInfo { uint256 rarity; // rarity to calculate reward minting strategy uint256 stakeFee; // entry fee (might be 0) uint256 withdrawFee; // exit fee (might be 0) uint256 booster; // each nft will have rewards booster } struct UserInfo { uint256 amountStaked; // how many nfts did user staked } /// @notice id => each nft mapping(uint256 => NftInfo) public nftInfo; /// @notice address => each user mapping(address => UserInfo) public userInfo; /// @notice cryptodemonz v1 official address address public demonz = 0xAE16529eD90FAfc927D774Ea7bE1b95D826664E3; /// @notice fee for staking uint256 stakingFee = 0.06 ether; /// @notice fee for withdrawing uint256 withdrawFee = 0.08 ether; event UserStaked(uint256 amount, address staker); //TODO amount event UserUnstaked(address unstaker); // ------------------------ PUBLIC ------------------------ // /// @notice stake multiple tokens at same time /// @param _id array of tokens user wants to stake at same time function StakeNFT(uint256[] memory _id) public payable { require(msg.value >= stakingFee, "ERR: FEE NOT COVERED"); uint256 amount = 0; for (uint256 i; i<=_id.length; ++i) { require(IERC721(demonz).ownerOf(_id[i]) == address(msg.sender), "ERR: YOU DONT OWN THESE TOKENS"); IERC721(demonz).safeTransferFrom(msg.sender, address(this), _id[i]); amount += 1; nftInfo[_id[i]] = NftInfo(0, 0, 0, 0); //TODO test userInfo[msg.sender] = UserInfo(amount); } emit UserStaked(amount, msg.sender); //TODO check for more cases //TODO replace amount with something better } /// @notice unstake NFT, no rewards given here! /// @param _id array fo tokens user wants to unstake at same time function UnstakeNFT(uint256[] memory _id) public payable { require(msg.value >= withdrawFee, "ERR: FEE NOT COVERED"); for (uint256 i; i<=_id.length; ++i) { require(IERC721(demonz).ownerOf(_id[i]) == address(msg.sender), "ERR: YOU DONT OWN THESE TOKENS"); IERC721(demonz).safeTransferFrom(address(this), msg.sender, _id[i]); delete nftInfo[_id[i]]; //TODO test } emit UserUnstaked(msg.sender); //TODO update user info as well //TODO add more require checks } // ------------------------ DEV ------------------------ // function changeStakingFee(uint256 _staking) public onlyOwner() { require(stakingFee != _staking, "DEV_ERR: VALUE ALREADY SET"); stakingFee = _staking; } function changeUnstakingFee(uint256 _unstaking) public onlyOwner() { require(withdrawFee != _unstaking, "DEV_ERR: VALUE ALREADY SET"); withdrawFee = _unstaking; } function changeDemonzAddress(address _newAddress) public onlyOwner() { require(demonz != _newAddress, "DEV_ERR: ADDRESS ALREADY SET"); demonz = _newAddress; } function onERC721Received( address, address, uint256, bytes calldata ) external returns (bytes4) { return bytes4( keccak256("onERC721Received(address,address,uint256,bytes)") ); } }
@notice unstake NFT, no rewards given here! @param _id array fo tokens user wants to unstake at same time
function UnstakeNFT(uint256[] memory _id) public payable { require(msg.value >= withdrawFee, "ERR: FEE NOT COVERED"); for (uint256 i; i<=_id.length; ++i) { require(IERC721(demonz).ownerOf(_id[i]) == address(msg.sender), "ERR: YOU DONT OWN THESE TOKENS"); IERC721(demonz).safeTransferFrom(address(this), msg.sender, _id[i]); } emit UserUnstaked(msg.sender);
1,776,478
[ 1, 23412, 911, 423, 4464, 16, 1158, 283, 6397, 864, 2674, 5, 225, 389, 350, 526, 18261, 2430, 729, 14805, 358, 640, 334, 911, 622, 1967, 813, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1351, 334, 911, 50, 4464, 12, 11890, 5034, 8526, 3778, 389, 350, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 598, 9446, 14667, 16, 315, 9712, 30, 478, 9383, 4269, 7910, 2204, 2056, 8863, 203, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 32, 33, 67, 350, 18, 2469, 31, 965, 77, 13, 288, 203, 1850, 203, 5411, 2583, 12, 45, 654, 39, 27, 5340, 12, 323, 2586, 94, 2934, 8443, 951, 24899, 350, 63, 77, 5717, 422, 1758, 12, 3576, 18, 15330, 3631, 315, 9712, 30, 1624, 26556, 463, 10079, 531, 5665, 12786, 1090, 14275, 55, 8863, 203, 203, 5411, 467, 654, 39, 27, 5340, 12, 323, 2586, 94, 2934, 4626, 5912, 1265, 12, 2867, 12, 2211, 3631, 1234, 18, 15330, 16, 389, 350, 63, 77, 19226, 203, 3639, 289, 203, 203, 3639, 3626, 2177, 984, 334, 9477, 12, 3576, 18, 15330, 1769, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/97/0x2e1703166e0620139a33Fcc169fF9E14Fe68D820/sources/PresaleBEP20.sol
* @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; }
11,478,764
[ 1, 2785, 326, 924, 364, 288, 529, 97, 471, 288, 7175, 5779, 11643, 288, 31734, 97, 598, 279, 805, 460, 434, 6549, 18, 2974, 2027, 279, 3775, 460, 364, 288, 31734, 5779, 999, 288, 67, 8401, 31809, 5496, 4826, 8925, 434, 4259, 924, 854, 11732, 30, 2898, 848, 1338, 506, 444, 3647, 4982, 16171, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 261, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 1071, 95, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 3639, 389, 31734, 273, 6549, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xeb70EaC1371Ef898AC2781D7168c0d5A11da10cf/sources/contracts/trove-factory.sol
* @dev insert a trove in the sorted list of troves. the troves must be sorted by collateralisation ratio CR the sender must be the trove which will be inserted in the list @param _newNextTrove is the trove before which the trove will be added/ if now hint is provided we start by trying the last trove in the list if the NewNextTrove is the same as the trove being changed, then it should be changed to the trove's nextTrove unless the trove is the lastTrove in which case it is changed to the previousTrove insertTrove is never called if there is only one trove in the list the lastTrove has itself as the nextTrove troves with zero debt have infinite collateralisation and can be put safely at the end of the list if the first trove in the list has a bigger CR then this trove becomes the new first trove. No loop required the previous trove of the new next trove should have a smaller or equal CR to the inserted trove it is cheaper (in gas) to assign the reference to the previous trove and insert after than to check twice for the CR this is why the loop is a "do while" instead of a "while do" the ICR of the newNextTrove is smaller than the inserted trove's only loop through the troves if the newNextTrove is not the last the previous trove of the new next trove should have a smaller or equal CR to the inserted trove
function insertTrove(address _token, address _newNextTrove) public override troveExists(_token, msg.sender) { require(containsTrove(_token, _newNextTrove) || _newNextTrove == address(0), "3a669 the trove hint must exist in the list or be 0x0"); if (_newNextTrove == address(0)) { _newNextTrove = lastTrove(_token); } if (_newNextTrove == msg.sender) { address nextTroveAddress = nextTrove(_token, _newNextTrove); _newNextTrove = _newNextTrove != nextTroveAddress ? nextTroveAddress : prevTrove(_token, _newNextTrove); } ITrove trove = ITrove(msg.sender); ITrove ref = ITrove(_newNextTrove); bool insertBefore = true; if (trove.debt() == 0) { require(_troves[_token].list.add(address(trove), address(0x0), false), "3a669 trove could not be inserted in the list"); emit TroveInserted(_token, address(trove), address(0x0), false); uint256 icr = trove.collateralization(); uint256 refIcr = ref.collateralization(); if (refIcr >= icr) { if (_newNextTrove != firstTrove(_token)) { do { ref = ITrove(prevTrove(_token, address(ref))); refIcr = ref.collateralization(); } while (refIcr > icr && address(ref) != _troves[_token].list._first); } } else { if (_newNextTrove != lastTrove(_token)) { do { ref = ITrove(nextTrove(_token, address(ref))); refIcr = ref.collateralization(); } while (refIcr < icr && address(ref) != _troves[_token].list._last); } } insertBefore = refIcr > icr; require(_troves[_token].list.add(address(trove), address(ref), insertBefore), "3a669 trove could not be inserted in the list"); emit TroveInserted(_token, address(trove), address(ref), insertBefore); } }
9,539,842
[ 1, 6387, 279, 23432, 537, 316, 326, 3115, 666, 434, 23432, 3324, 18, 326, 23432, 3324, 1297, 506, 3115, 635, 4508, 2045, 287, 10742, 7169, 6732, 326, 5793, 1297, 506, 326, 23432, 537, 1492, 903, 506, 9564, 316, 326, 666, 225, 389, 2704, 2134, 56, 303, 537, 353, 326, 23432, 537, 1865, 1492, 326, 23432, 537, 903, 506, 3096, 19, 309, 2037, 7380, 353, 2112, 732, 787, 635, 8374, 326, 1142, 23432, 537, 316, 326, 666, 309, 326, 1166, 2134, 56, 303, 537, 353, 326, 1967, 487, 326, 23432, 537, 3832, 3550, 16, 1508, 518, 1410, 506, 3550, 358, 326, 23432, 537, 1807, 1024, 56, 303, 537, 3308, 326, 23432, 537, 353, 326, 1142, 56, 303, 537, 316, 1492, 648, 518, 353, 3550, 358, 326, 2416, 56, 303, 537, 2243, 56, 303, 537, 353, 5903, 2566, 309, 1915, 353, 1338, 1245, 23432, 537, 316, 326, 666, 326, 1142, 56, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 225, 445, 2243, 56, 303, 537, 12, 2867, 389, 2316, 16, 1758, 389, 2704, 2134, 56, 303, 537, 13, 1071, 3849, 23432, 537, 4002, 24899, 2316, 16, 1234, 18, 15330, 13, 288, 203, 565, 2583, 12, 12298, 56, 303, 537, 24899, 2316, 16, 389, 2704, 2134, 56, 303, 537, 13, 747, 389, 2704, 2134, 56, 303, 537, 422, 1758, 12, 20, 3631, 315, 23, 69, 6028, 29, 326, 23432, 537, 7380, 1297, 1005, 316, 326, 666, 578, 506, 374, 92, 20, 8863, 203, 203, 565, 309, 261, 67, 2704, 2134, 56, 303, 537, 422, 1758, 12, 20, 3719, 288, 203, 1377, 389, 2704, 2134, 56, 303, 537, 273, 1142, 56, 303, 537, 24899, 2316, 1769, 203, 565, 289, 203, 203, 565, 309, 261, 67, 2704, 2134, 56, 303, 537, 422, 1234, 18, 15330, 13, 288, 203, 1377, 1758, 1024, 56, 303, 537, 1887, 273, 1024, 56, 303, 537, 24899, 2316, 16, 389, 2704, 2134, 56, 303, 537, 1769, 203, 1377, 389, 2704, 2134, 56, 303, 537, 273, 389, 2704, 2134, 56, 303, 537, 480, 1024, 56, 303, 537, 1887, 692, 1024, 56, 303, 537, 1887, 294, 2807, 56, 303, 537, 24899, 2316, 16, 389, 2704, 2134, 56, 303, 537, 1769, 203, 565, 289, 203, 203, 565, 24142, 303, 537, 23432, 537, 273, 24142, 303, 537, 12, 3576, 18, 15330, 1769, 203, 565, 24142, 303, 537, 1278, 273, 24142, 303, 537, 24899, 2704, 2134, 56, 303, 537, 1769, 203, 565, 1426, 18004, 273, 638, 31, 203, 203, 565, 309, 261, 88, 303, 537, 18, 323, 2 ]
/** From the devs of CAT (Capital Aggregator) We present DW Capital - Dont worry your profits are SAFU **/ // SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Ownable is Context { address payable private _owner; address payable private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { _owner = payable(msg.sender); emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = payable(address(0)); } function transferOwnership(address payable newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = payable(address(0)); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until defined days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; _previousOwner = payable(address(0)); } } interface uniSwapFactory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IPancakePair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IPancakeRouter01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface uniSwapRouter02 is IPancakeRouter01 { 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; } library Utils { using SafeMath for uint256; function swapTokensForEth( address routerAddress, uint256 tokenAmount ) internal { uniSwapRouter02 uniSwapRouter = uniSwapRouter02(routerAddress); // generate the pancake pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniSwapRouter.WETH(); // make the swap uniSwapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of BNB path, address(this), block.timestamp + 360 ); } function swapETHForTokens( address routerAddress, address recipient, uint256 ethAmount ) internal { uniSwapRouter02 uniSwapRouter = uniSwapRouter02(routerAddress); // generate the pancake pair path of token -> weth address[] memory path = new address[](2); path[0] = uniSwapRouter.WETH(); path[1] = address(this); // make the swap uniSwapRouter.swapExactETHForTokensSupportingFeeOnTransferTokens{value: ethAmount}( 0, // accept any amount of BNB path, address(recipient), block.timestamp + 360 ); } function addLiquidity( address routerAddress, address owner, uint256 tokenAmount, uint256 ethAmount ) internal { uniSwapRouter02 uniSwapRouter = uniSwapRouter02(routerAddress); // add the liquidity uniSwapRouter.addLiquidityETH{value : ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner, block.timestamp + 360 ); } } abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } 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; } modifier isHuman() { require(tx.origin == msg.sender, "sorry humans only"); _; } } contract DWCAPITAL is Context, IERC20, Ownable, ReentrancyGuard { using SafeMath for uint256; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private bots; mapping(address => uint256) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1e12 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "DONT WORRY CAPITAL"; string private constant _symbol = "$DWC"; uint8 private constant _decimals = 9; uniSwapRouter02 public uniSwapRouter; address public uniSwapPair; bool private _antiwhale = true; //once switched on, can never be switched off. bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint256 _maxTxAmount); event antiWaleUpdate(bool enabled); modifier lockTheSwap() { inSwap = true; _; inSwap = false; } constructor() { _feeAddrWallet1 = payable(0xd5ab171Ec8165C2245b5c5457b50740FA4750EBE); _feeAddrWallet2 = payable(0xd5ab171Ec8165C2245b5c5457b50740FA4750EBE); _rOwned[_msgSender()] = _rTotal; uniSwapRouter02 _pancakeRouter = uniSwapRouter02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a pancake pair for this new token uniSwapPair = uniSwapFactory(_pancakeRouter.factory()) .createPair(address(this), _pancakeRouter.WETH()); // set the rest of the contract variables uniSwapRouter = _pancakeRouter; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x7786B2455637420c7752D48bEe485F00E4c6aa6a), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function setCooldownEnabled(bool onoff) external onlyOwner { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 2; _feeAddr2 = 8; if (!_antiwhale) { require(to != uniSwapPair, "ERC20: antiwhale is not enabled yet"); } if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if ( from == uniSwapPair && to != address(uniSwapRouter) && !_isExcludedFromFee[to] && cooldownEnabled ) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if ( to == uniSwapPair && from != address(uniSwapRouter) && !_isExcludedFromFee[from] ) { _feeAddr1 = 5; _feeAddr2 = 5; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniSwapPair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from, to, amount); } function antiWhaleStatus(bool _state) public onlyOwner { _antiwhale = _state; emit antiWaleUpdate(_state); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniSwapRouter.WETH(); _approve(address(this), address(uniSwapRouter), tokenAmount); uniSwapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet2.transfer(amount); } function openTrading() external onlyOwner { require(!tradingOpen, "trading is already open"); uniSwapRouter02 _uniswapV2Router = uniSwapRouter02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); uniSwapRouter = _uniswapV2Router; _approve(address(this), address(uniSwapRouter), _tTotal); uniSwapPair = uniSwapFactory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniSwapRouter.addLiquidityETH{value: address(this).balance}( address(this), balanceOf(address(this)), 0, 0, owner(), block.timestamp ); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 300000000000 * 10 ** 9; tradingOpen = true; IERC20(uniSwapPair).approve( address(uniSwapRouter), type(uint256).max ); } function nonosquare(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer( address sender, address recipient, uint256 amount ) private { _transferStandard(sender, recipient, amount); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues( tAmount, _feeAddr1, _feeAddr2 ); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tTeam, currentRate ); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 taxFee, uint256 TeamFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
generate the pancake pair path of token -> weth make the swap
) internal { uniSwapRouter02 uniSwapRouter = uniSwapRouter02(routerAddress); address[] memory path = new address[](2); path[0] = address(this); path[1] = uniSwapRouter.WETH(); uniSwapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp + 360 ); }
5,600
[ 1, 7163, 326, 2800, 23780, 3082, 589, 434, 1147, 317, 341, 546, 1221, 326, 7720, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 2713, 288, 203, 3639, 7738, 12521, 8259, 3103, 7738, 12521, 8259, 273, 7738, 12521, 8259, 3103, 12, 10717, 1887, 1769, 203, 203, 3639, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 22, 1769, 203, 3639, 589, 63, 20, 65, 273, 1758, 12, 2211, 1769, 203, 3639, 589, 63, 21, 65, 273, 7738, 12521, 8259, 18, 59, 1584, 44, 5621, 203, 203, 3639, 7738, 12521, 8259, 18, 22270, 14332, 5157, 1290, 1584, 44, 6289, 310, 14667, 1398, 5912, 5157, 12, 203, 5411, 1147, 6275, 16, 203, 5411, 589, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 1203, 18, 5508, 397, 12360, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// CD->09.11.2015 wordentry_set CannotBeNounAdjunct= { eng_noun:passing{}, // The zing of the passing bullet. eng_noun:how{}, eng_noun:why{}, eng_noun:where{}, eng_noun:what{}, // What units make sense? eng_noun:fighting{}, eng_noun:working{}, eng_noun:Belgian{}, eng_noun:sinking{}, // With a sinking heart eng_noun:rising{}, // A rising market. eng_noun:not{}, eng_noun:domestic{}, eng_noun:open{}, eng_noun:two{}, eng_noun:three{}, eng_noun:four{}, eng_noun:five{}, eng_noun:six{}, eng_noun:eight{}, eng_noun:night{}, eng_noun:ten{}, eng_noun:married{}, eng_noun:nominal{}, eng_noun:different{}, eng_noun:singing{}, // Listen to that singing bird eng_noun:calico{}, // A calico cat. eng_noun:caloric{}, // The caloric content of foods. eng_noun:deep{}, // The canicular heat of the Deep South. eng_noun:carpetbag{}, // A carpetbag government. eng_noun:cereal{}, // A cereal beverage. eng_noun:municipal{}, // A municipal park. eng_noun:clerical{}, // Clerical work. eng_noun:Constitutional{}, // Constitutional walk. eng_noun:military{}, // Military law eng_noun:nominative{}, // Nominative noun endings eng_noun:numeral{}, // A numeral adjective. eng_noun:oral{}, // An oral vaccine. eng_noun:vocal{}, // A vocal assembly. eng_noun:verbal{}, // A verbal protest. eng_noun:blank{}, // A blank stare. eng_noun:comparable{}, // Pianists of comparable ability. eng_noun:summary{}, // A summary formulation of a wide-ranging subject. eng_noun:undecided{}, // Undecided voters eng_noun:absolute{}, // Absolute freedom eng_noun:rank{}, // A rank outsider. eng_noun:total{}, // A total disaster. eng_noun:incomplete{}, // An incomplete forward pass. eng_noun:half{}, // She gave me a half smile. eng_noun:partial{}, // A partial monopoly. eng_noun:comprehensive{}, // A comprehensive survey. eng_noun:broad{}, // An invention with broad applications. eng_noun:cosmopolitan{}, // An issue of cosmopolitan import. eng_noun:universal{}, // Universal experience. eng_noun:plenary{}, // A plenary session of the legislature. eng_noun:super{}, // A super experiment. eng_noun:thick{}, // Thick hair eng_noun:crisp{}, // A crisp retort. eng_noun:cryptic{}, // A cryptic note. eng_noun:determinate{}, // A determinate answer to the problem. eng_noun:conditional{}, // Conditional acceptance of the terms. eng_noun:provisional{}, // A provisional government. eng_noun:blunt{}, // The blunt truth. eng_noun:crude{}, // The crude facts. eng_noun:identical{}, // Identical triangles eng_noun:extreme{}, // Egality represents an extreme leveling of society. eng_noun:national{}, // We support the armed services in the name of national security. eng_noun:class{}, // National independence takes priority over class struggle. eng_noun:connective{}, // Connective tissue in animals. eng_noun:invincible{}, // Her invincible spirit. eng_noun:votive{}, // Votive prayers. eng_noun:Contradictory{}, // Contradictory attributes of unjust justice and loving vindictiveness eng_noun:controversial{}, // A controversial decision on affirmative action. eng_noun:spectacular{}, // A spectacular rise in prices. eng_noun:constant{}, // A constant lover. eng_noun:free{}, // A staunch defender of free speech. eng_noun:creative{}, // Creative work. eng_noun:formative{}, // A formative experience. eng_noun:affirmative{}, // A controversial decision on affirmative action. eng_noun:back{}, // The back hall is an inconvenient place for the telephone. eng_noun:local{}, // Local customs eng_noun:legal{}, // The legal profession eng_noun:Judicial{}, // Judicial system eng_noun:illative{}, // The illative faculty of the mind. eng_noun:incendiary{}, // An incendiary fire eng_noun:imperial{}, eng_noun:British{}, // The imperial gallon was standardized legally throughout the British Empire eng_noun:humanist{}, // The humanist belief in continuous emergent evolution. eng_noun:horary{}, // The horary cycle eng_noun:home{}, // My home town eng_noun:graphic{}, // A graphic presentation of the data eng_noun:generic{}, // The generic name eng_noun:existentialist{}, // The existentialist character of his ideas eng_noun:fishy{}, // The soup had a fishy smell. eng_noun:Byzantine{}, // Byzantine monks eng_noun:Occipital{}, // Occipital bone eng_noun:Angular{}, // Angular momentum eng_noun:Educational{}, // Educational psychology eng_noun:Developmental{}, // Developmental psychology eng_noun:Epileptic{}, // Epileptic seizure eng_noun:Transdermal{}, // Transdermal estrogen eng_noun:sectional{}, // A sectional view eng_noun:African{}, // African languages{}, // African languages eng_noun:Anglican{}, // An Anglican bishop eng_noun:Christian{}, // Christian rites eng_noun:Dutch{}, // Dutch painting eng_noun:Danish{}, // Danish furniture eng_noun:Norwegian{}, // Norwegian herring eng_noun:Swedish{}, // Swedish punch eng_noun:Finnish{}, // Finnish architecture eng_noun:Austrian{}, // Austrian music eng_noun:Mormon{}, // Mormon leaders eng_noun:Methodist{}, // Methodist theology eng_noun:Lutheran{}, // Lutheran doctrines eng_noun:Bavarian{}, // Bavarian beer eng_noun:Cuban{}, // Cuban rum eng_noun:Salvadoran{}, // Salvadoran coffee eng_noun:Asian{}, // Asian countries eng_noun:European{}, // European Community eng_noun:Korean{}, // Korean handicrafts eng_noun:Colombian{}, // Colombian coffee eng_noun:Argentinian{}, // Argentinian tango eng_noun:Venezuelan{}, // Venezuelan oil eng_noun:Panamanian{}, // Panamanian economy eng_noun:Ecuadorian{}, // Ecuadorian folklore eng_noun:Peruvian{}, // Peruvian artifacts eng_noun:Chilean{}, // Chilean volcanoes eng_noun:Tibetan{}, // Tibetan monks eng_noun:Paradigmatic{}, // Paradigmatic learning eng_noun:Japanese{}, // Japanese cars eng_noun:Chinese{}, // Chinese food eng_noun:Slovenian{}, // Slovenian independence eng_noun:Croatian{}, // Croatian villages eng_noun:Protestant{}, // A Protestant denomination eng_noun:physical{}, // A study of the physical properties of atomic particles eng_noun:street{}, // Liverpudlian street urchins eng_noun:Haitian{}, // Haitian shantytowns eng_noun:Guatemalan{}, // Guatemalan coffee eng_noun:Gothic{}, // Gothic migrations eng_noun:Gabonese{}, // Gabonese hills eng_noun:Franciscan{}, // Franciscan monks eng_noun:Ethiopian{}, // Ethiopian immigrants eng_noun:Empiric{}, // Empiric treatment eng_noun:Dominican{}, // Dominican monks eng_noun:creole{}, // creole cooking eng_noun:Malawian{}, // Malawian hills eng_noun:Macedonian{}, // Macedonian hills eng_noun:Liverpudlian{}, // Liverpudlian streets eng_noun:Lilliputian{}, // The Lilliputian population eng_noun:Libyan{}, // The Libyan desert eng_noun:inevitable{}, // The inevitable result. eng_noun:metal{}, // The steady dripping of water rusted the metal stopper in the sink. eng_noun:motive{}, // A motive force. eng_noun:incurable{}, // An incurable optimist. eng_noun:static{}, // A static population. eng_noun:chemical{}, // A reversible chemical reaction. eng_noun:social{}, // A rise in crime symptomatic of social breakdown. eng_noun:rash{}, // A rash symptomatic of scarlet fever. eng_noun:marginal{}, // The marginal strip of beach. eng_noun:certifiable{}, // A certifiable fact. eng_noun:third{}, // The third generation of computers. eng_noun:regular{}, // The regular sequence of the seasons. eng_noun:incandescent{}, // An incandescent bulb. eng_noun:delicate{}, // His delicate health. eng_noun:human{}, // The human condition. eng_noun:family{}, // He charted his family tree genealogically. eng_noun:metric{}, // The metric system eng_noun:special{}, // a special antenna for public relations eng_noun:public{}, // a special antenna for public relations eng_noun:living{}, // The relatedness of all living things. eng_noun:animal{}, // The animal constituent of plankton. eng_noun:proverbial{}, // The proverbial grasshopper eng_noun:capitalist{}, // A capitalist nation eng_noun:Utopian{}, // A Utopian novel eng_noun:ceramic{}, // A ceramic dish eng_noun:industrial{}, // The industrial base of Japan eng_noun:divine{}, // a sort of divine madness eng_noun:reading{}, // A diagnostic reading test eng_noun:diagnostic{}, // A diagnostic reading test eng_noun:citrus{}, // The citrus production of Florida eng_noun:Cameroonian{}, // The Cameroonian capital eng_noun:Fijian{}, // The Fijian population eng_noun:feudatory{}, // A feudatory relationship eng_noun:Djiboutian{}, // A Djiboutian storyteller eng_noun:modern{}, // Economics in its modern disciplinary sense eng_noun:Mongolian{}, // The Mongolian embassy eng_noun:indicative{}, // Indicative mood eng_noun:Pre-Raphaelite{}, // The Pre-Raphaelite painters eng_noun:polynomial{}, // A polynomial expression eng_noun:Philharmonic{}, // Philharmonic players eng_noun:Paralytic{}, // Paralytic symptoms eng_noun:ruling{}, // The Qatari ruling family eng_noun:rapid{}, // His rapid manner of talking eng_noun:pharmaceutical{}, // The pharmaceutical industry eng_noun:Partitive{}, // Partitive tendencies in education eng_noun:Participial{}, // Participial inflections eng_noun:Parthian{}, // Parthian archeology eng_noun:Papuan{}, // Papuan vowels eng_noun:native{}, // Papuan native crafts eng_noun:Reversionary{}, // Reversionary interest eng_noun:folk{}, // Romany folk songs eng_noun:gypsy{}, // A Gypsy fortune-teller eng_noun:Rwandan{}, // Rwandan mountains eng_noun:shakedown{}, eng_noun:Pyrrhic{}, // A Pyrrhic victory eng_noun:Quadratic{}, // Quadratic equation eng_noun:Antiphonal{}, // Antiphonal laughter eng_noun:Processional{}, // Processional music eng_noun:procedural{}, // A procedural violation eng_noun:Seychellois{}, // Seychellois fishermen eng_noun:Senegalese{}, // Senegalese villages eng_noun:regional{}, // Regional flora eng_noun:Singaporean{}, // Singaporean rubber eng_noun:Siberian{}, // Siberian coal miners eng_noun:Zairean{}, // Zairean elections eng_noun:Yemeni{}, // Yemeni mountains eng_noun:wheaten{}, // wheaten bread eng_noun:Welsh{}, // The Welsh coast eng_noun:Vietnamese{}, // Vietnamese boat people eng_noun:vestal{}, // Vestal virgin eng_noun:tutorial{}, // Tutorial sessions eng_noun:Trinidadian{}, // Trinidadian rum eng_noun:Syphilitic{}, // Syphilitic symptoms eng_noun:tertian{}, // Tertian fever eng_noun:textile{}, // Textile research eng_noun:fresh{}, // Crispness of fresh lettuce eng_noun:spastic{}, // A spastic colon eng_noun:mutual{}, // The mutual adhesiveness of cells eng_noun:scalar{}, // Scalar quantity eng_noun:acrocentric{}, // An acrocentric chromosome eng_noun:metacentric{}, // A metacentric chromosome eng_noun:communist{}, // Communist Party eng_noun:Hypoglycemic{}, // Hypoglycemic agents eng_noun:Hypodermic{}, // Hypodermic needle eng_noun:Serbian{}, // the three possible classes of Serbian nouns eng_noun:continental{}, // The continental divide eng_noun:diatomic{}, // A diatomic molecule eng_noun:genital{}, // Genital herpes eng_noun:mural{}, // Mural painting eng_noun:frontal{}, // Frontal rainfall eng_noun:Juvenile{}, // Juvenile diabetes eng_noun:Ecclesiastic{}, // Ecclesiastic history eng_noun:Antediluvian{}, // Antediluvian man eng_noun:floral{}, // Floral organs eng_noun:professional{}, // Professional training eng_noun:ocular{}, // An ocular organ eng_noun:gnostic{}, // Gnostic writings eng_noun:Lacteal{}, // Lacteal fluids eng_noun:Funicular{}, // Funicular railway eng_noun:fiducial{}, // A fiducial point eng_noun:fiduciary{}, // A fiduciary contract eng_noun:Mauritanian{}, // Mauritanian tropical fish eng_noun:Machiavellian{}, // Machiavellian thinking eng_noun:Liberian{}, // Liberian ship owners eng_noun:Latin{}, // Latin verb conjugations eng_noun:Iranian{}, // Iranian security police eng_noun:Indo-European{}, // Indo-European migrations eng_noun:Exponential{}, // Exponential growth eng_noun:Italian{}, // Italian cooking eng_noun:German{}, // German philosophers eng_noun:Anglo-Saxon{}, // poetry eng_noun:Laryngeal{}, // Laryngeal infection eng_noun:viral{}, // Viral infection eng_noun:commercial{}, // Commercial law eng_noun:molar{}, // molar weight eng_noun:iambic{}, // iambic pentameter eng_noun:jugular{}, // jugular vein eng_noun:vocative{}, // Vocative verb endings eng_noun:subjunctive{}, // Subjunctive verb endings eng_noun:optative{}, // Optative verb endings eng_noun:facial{}, // A facial massage eng_noun:intravenous{}, // An intravenous inflammation eng_noun:rental{}, // A rental car eng_noun:ritual{}, // A ritual dance of Haiti eng_noun:personal{}, // personal verb endings eng_noun:pastoral{}, // a pastoral letter eng_noun:lyric{}, // the lyric stage eng_noun:hematic{}, // A hematic cyst eng_noun:wide{}, // That team needs a decent wide player eng_noun:sylvan{}, // A shady sylvan glade eng_noun:hostile{}, // Freeze the assets of this hostile government. eng_noun:seven{}, // The prisoner's resistance weakened after seven days. eng_noun:mnemonic{}, // the mnemonic device eng_noun:woolen{}, // a woolen sweater eng_noun:Akkadian{}, // Let's eliminate the course on Akkadian hieroglyphics. eng_noun:octal{}, // An octal digit. eng_noun:audile{}, // An audile person. eng_noun:acoustic{}, // Acoustic properties of a hall eng_noun:Mercurial{}, // The Mercurial canals. eng_noun:musical{}, // A musical evening eng_noun:twelve{}, // Here is a hen with twelve chickens eng_noun:wild{}, // I see neither human nor wild animal eng_noun:arithmetic{}, // Some type of arithmetic computations produces an invalid result that exceeds the range of the data type involved in the computation eng_noun:eleven{}, // The bell at eleven o'clock tells us that lesson is finished eng_noun:nine{}, // Richard slept until nine o'clock eng_noun:Disciplinary{}, // Disciplinary problems in the classroom eng_noun:tatty{}, // An old house with dirty windows and tatty curtains eng_noun:Antipodal{}, // Antipodal regions of the earth eng_noun:reproductive{}, // Urbanization in Spain is distinctly correlated with a fall in reproductive rate. eng_noun:luxury{}, // Sales of luxury cars dropped markedly. eng_noun:several{}, // He gave liberally to several charities. eng_noun:medical{}, // Amazingly, he finished medical school in three years. eng_noun:all{}, // Visit us by all means. eng_noun:prepositional{}, // The prepositional phrase here is used adverbially. eng_noun:genitive{}, // The genitive noun is used attributively. eng_noun:natural{}, // A natural conclusion follows thence. eng_noun:global{}, // Greenspan's fraud: how two decades of his policies have undermined the global economy eng_noun:Georgian{}, // The Georgian capital is Tbilisi. eng_noun:final{}, // The final runners were far behind. eng_noun:ninth{}, // The ninth century was the spiritually freest period. eng_noun:iron{}, // That iron gate is made of iron that came from England eng_noun:stone{}, // The moss undergrew the stone patio. eng_noun:enemy{}, // The landscape was deforested by the enemy attacks. eng_noun:remote{}, // The remote areas of the country were gradually built up. eng_noun:upper{}, // This exercise will strengthen your upper body. eng_noun:following{}, // Develop the function in the following form. eng_noun:stock{}, // The stock market fluctuates. eng_noun:sudden{}, // The sudden storm immobilized the traffic. eng_noun:entire{}, // The bureaucracy paralyzes the entire operation. eng_noun:political{}, // Reform a political system. eng_noun:extra{}, // Add some extra plates to the dinner table. eng_noun:plastic{}, // The temple was garishly decorated with bright plastic flowers. eng_noun:bright{}, // The temple was garishly decorated with bright plastic flowers. eng_noun:basic{}, // He light-heartedly overlooks some of the basic facts of life. eng_noun:black{}, // She danced the part of the Black Swan very lyrically. eng_noun:main{}, // He drove down the main road eng_noun:next{}, // The boy in the next desk borrowed my pencil eng_noun:first{}, // The first job is already done. eng_noun:sweet{}, // These small apples have a SWEET taste eng_noun:and{}, // the hammer AND sickle eng_noun:will{}, // The boy WILL play with another dog eng_noun:best{}, // He is my best friend eng_noun:good{}, // He is a good player eng_noun:big{}, // The big dog chased me eng_noun:simple{}, eng_noun:invalid{}, // an invalid result exceeds the range of the data type involved in the computation eng_noun:sharp{}, // A sharp knife cuts cleanly. eng_noun:early{}, // An early riser gets up early. eng_noun:straight{}, // Run in a straight line. eng_noun:whole{}, // I ate a whole fish eng_noun:new{}, // Have you seen my new bicycle? eng_noun:second{}, // We were in the second class last year eng_noun:small{}, // The small boy rings the bell eng_noun:great{}, // The ship sank in the great storm eng_noun:heavy{}, // Henry can lift that heavy box eng_noun:past{}, // Don't sentimentalize the past events. eng_noun:an{}, // We have an hour to burn. eng_noun:running{}, // The running horse galloped down the road eng_noun:one{}, eng_noun:no{}, eng_noun:yesterday{}, // I did the work yesterday eng_noun:English{}, // He has an English book eng_noun:Russian{}, eng_noun:French{}, // She spoke English with a French accent eng_noun:Greek{}, // Ultimately, I have been studying Greek at evening classes. eng_noun:particular{}, // Let's abstract away from this particular example. eng_noun:over{}, // Let me think that over. eng_noun:each{}, // Each partition acts like a separate hard drive eng_noun:separate{}, // Each partition acts like a separate hard drive eng_noun:hard{}, // Each partition acts like a separate hard drive eng_noun:high{}, // The headmaster's desk stood on a high platform eng_noun:right{}, // We didn't know the right time eng_noun:white{}, // I see the big white cat eng_noun:stupid{}, // a very stupid dog eng_noun:most{}, // Most flare stars are dim red dwarfs eng_noun:out{}, // Wrap the baby before taking her out. eng_noun:at{}, eng_noun:clean{}, // The thieves made a clean getaway. eng_noun:fine{}, // Don't sign a contract without reading the fine print. eng_noun:wet{}, // The wet road was shining sleekly. eng_noun:temporary{}, // The temporary camps were inadequately equipped. eng_noun:single{}, // A single chicken was scratching forlornly in the yard. eng_noun:thin{}, // The dress hung shapelessly on her thin body. eng_noun:kind{}, // I must regretfully decline your kind invitation. eng_noun:setting{}, // They traveled westward toward the setting sun. eng_noun:former{}, // He treats his former wife civilly. eng_noun:blue{}, // Birds flew zigzag across the blue sky. eng_noun:relative{}, // This relative clause is used restrictively. eng_noun:cold{}, eng_noun:common{}, // A common remedy is uncommonly difficult to find. eng_noun:red{}, // I have two RED apples eng_noun:lightning{}, eng_noun:hanging{}, eng_noun:cunning{}, eng_noun:dancing{}, eng_noun:foreboding{}, eng_noun:bearing{}, eng_noun:listing{}, eng_noun:standing{}, eng_noun:knowing{}, eng_noun:ongoing{}, eng_noun:fitting{}, eng_noun:mounting{}, eng_noun:ranking{}, eng_noun:thieving{}, eng_noun:cooking{}, eng_noun:pleading{}, eng_noun:travelling{}, eng_noun:testing{}, eng_noun:nursing{}, eng_noun:upbraiding{}, eng_noun:blinding{}, eng_noun:trotting{}, eng_noun:greening{}, eng_noun:whacking{}, eng_noun:vining{}, eng_noun:grudging{}, eng_noun:upset{}, eng_noun:evening{}, eng_noun:brown{}, eng_noun:adjective{}, eng_noun:adjectival{}, eng_noun:Fabian{}, eng_noun:abbreviate{}, eng_noun:abject{}, eng_noun:abluent{}, eng_noun:abortive{}, eng_noun:above{}, eng_noun:absolutist{}, eng_noun:abstractionist{}, eng_noun:Accadian{}, eng_noun:acceptant{}, eng_noun:Achean{}, eng_noun:orange{}, eng_noun:singular{}, eng_noun:andante{}, eng_noun:urban{}, eng_noun:mobile{}, eng_noun:wireless{}, eng_noun:epidemic{}, eng_noun:welcome{}, eng_noun:automatic{}, eng_noun:abstergent{}, eng_noun:absurd{}, eng_noun:general{}, eng_noun:Yiddish{}, eng_noun:Indian{}, eng_noun:Jacobian{}, eng_noun:minuscule{}, eng_noun:Slovene{}, eng_noun:gold{}, eng_noun:magenta{}, eng_noun:dual{}, eng_noun:weekend{}, eng_noun:counterfeit{}, eng_noun:parallel{}, eng_noun:pi{}, eng_noun:X - ray{}, eng_noun:antecedent{}, eng_noun:imperative{}, eng_noun:irregular{}, eng_noun:Castilian{}, eng_noun:pommy{}, eng_noun:quadrilateral{}, eng_noun:northeast{}, eng_noun:honey{}, eng_noun:male{}, eng_noun:anterior{}, eng_noun:collateral{}, eng_noun:weekly{}, eng_noun:quarterly{}, eng_noun:fuchsia{}, eng_noun:khaki{}, eng_noun:coral{}, eng_noun:lavender{}, eng_noun:olive{}, eng_noun:sienna{}, eng_noun:teal{}, eng_noun:taupe{}, eng_noun:amber{}, eng_noun:grape{}, eng_noun:avocado{}, eng_noun:auburn{}, eng_noun:buff{}, eng_noun:overweight{}, eng_noun:Melburnian{}, eng_noun:polycystine{}, eng_noun:canary{}, eng_noun:slim{}, eng_noun:Romanian{}, eng_noun:transgender{}, eng_noun:Muslim{}, eng_noun:blond{}, eng_noun:blonde{}, eng_noun:archaic{}, eng_noun:ideal{}, eng_noun:then{}, eng_noun:diminutive{}, eng_noun:ephemeral{}, eng_noun:stiff{}, eng_noun:fricative{}, eng_noun:cuckoo{}, eng_noun:short{}, eng_noun:salt{}, eng_noun:rough{}, eng_noun:sand{}, eng_noun:flame{}, eng_noun:horizontal{}, eng_noun:totalitarian{}, eng_noun:selenoid{}, eng_noun:flash{}, eng_noun:Ukrainian{}, eng_noun:objective{}, eng_noun:spoony{}, eng_noun:transsexual{}, eng_noun:upcast{}, eng_noun:incorrigible{}, eng_noun:reprehensible{}, eng_noun:Angolan{}, eng_noun:instrumental{}, eng_noun:maslin{}, eng_noun:dank{}, eng_noun:Faeroese{}, eng_noun:Hispano{}, eng_noun:acataleptic{}, eng_noun:alert{}, eng_noun:eclectic{}, eng_noun:precedent{}, eng_noun:intuitive{}, eng_noun:essential{}, eng_noun:Australian{}, eng_noun:quorate{}, eng_noun:hangdog{}, eng_noun:magic{}, eng_noun:due{}, eng_noun:alpha{}, eng_noun:beta{}, eng_noun:crazy{}, eng_noun:premier{}, eng_noun:sulfur{}, eng_noun:invertebrate{}, eng_noun:extraterrestrial{}, eng_noun:republican{}, eng_noun:neurotic{}, eng_noun:quick{}, eng_noun:Transylvanian{}, eng_noun:Tasmanian{}, eng_noun:Boolean{}, eng_noun:individual{}, eng_noun:Muscovite{}, eng_noun:psycho{}, eng_noun:ordinary{}, eng_noun:brash{}, eng_noun:maximum{}, eng_noun:micro{}, eng_noun:acerate{}, eng_noun:vegan{}, eng_noun:Saturnian{}, eng_noun:libertarian{}, eng_noun:characteristic{}, eng_noun:center{}, eng_noun:aqua{}, eng_noun:nonflammable{}, eng_noun:yearly{}, eng_noun:unknown{}, eng_noun:sandwich{}, eng_noun:hundred - first{}, eng_noun:hundred{}, eng_noun:Aruban{}, eng_noun:Azerbaijani{}, eng_noun:Bangladeshi{}, eng_noun:Belizean{}, eng_noun:Beninese{}, eng_noun:barbarian{}, eng_noun:Nigerien{}, eng_noun:Mauritian{}, eng_noun:Cambodian{}, eng_noun:Iraqi{}, eng_noun:Zimbabwean{}, eng_noun:Ugandan{}, eng_noun:Tuvaluan{}, eng_noun:Caymanian{}, eng_noun:Maldivian{}, eng_noun:Qatari{}, eng_noun:Samoan{}, eng_noun:Congolese{}, eng_noun:Eritrean{}, eng_noun:Nepalese{}, eng_noun:Jordanian{}, eng_noun:Kuwaiti{}, eng_noun:Malagasy{}, eng_noun:Corinthian{}, eng_noun:arcadian{}, eng_noun:Boeotian{}, eng_noun:Belizian{}, eng_noun:Kiribatian{}, eng_noun:Tokelauan{}, eng_noun:megalopolitan{}, eng_noun:trademark{}, eng_noun:Somalian{}, eng_noun:underline{}, eng_noun:zany{}, eng_noun:standout{}, eng_noun:Calabrian{}, eng_noun:monastic{}, eng_noun:land{}, eng_noun:Rosicrucian{}, eng_noun:virtual{}, eng_noun:retail{}, eng_noun:random{}, eng_noun:simian{}, eng_noun:roman{}, eng_noun:cosy{}, eng_noun:evergreen{}, eng_noun:puritan{}, eng_noun:nasty{}, eng_noun:blueberry{}, eng_noun:ersatz{}, eng_noun:nude{}, eng_noun:primavera{}, eng_noun:Marshallese{}, eng_noun:bimonthly{}, eng_noun:biweekly{}, eng_noun:decennial{}, eng_noun:bicentennial{}, eng_noun:trimillennial{}, eng_noun:killer{}, eng_noun:medium{}, eng_noun:homo{}, eng_noun:top{}, eng_noun:nudist{}, eng_noun:derogatory{}, eng_noun:wack{}, eng_noun:bulk{}, eng_noun:draft{}, eng_noun:semi - weekly{}, eng_noun:independent{}, eng_noun:alternative{}, eng_noun:sexist{}, eng_noun:ovine{}, eng_noun:opposite{}, eng_noun:sleepy{}, eng_noun:dependent{}, eng_noun:token{}, eng_noun:leviathan{}, eng_noun:dandy{}, eng_noun:pejorative{}, eng_noun:moccasin{}, eng_noun:active{}, eng_noun:actual{}, eng_noun:adhesive{}, eng_noun:adjacent{}, eng_noun:heterosexual{}, eng_noun:Buddhist{}, eng_noun:fils{}, eng_noun:vandal{}, eng_noun:ajar{}, eng_noun:sham{}, eng_noun:KIA{}, eng_noun:alternate{}, eng_noun:glutton{}, eng_noun:Asturian{}, eng_noun:intensive{}, eng_noun:amyl{}, eng_noun:anarchist{}, eng_noun:treble{}, eng_noun:ancient{}, eng_noun:Romany{}, eng_noun:Scottish{}, eng_noun:outside{}, eng_noun:agnostic{}, eng_noun:interstitial{}, eng_noun:plenty{}, eng_noun:functional{}, eng_noun:sesquipedalian{}, eng_noun:AWOL{}, eng_noun:episcopal{}, eng_noun:episcopalian{}, eng_noun:crescent{}, eng_noun:lunate{}, eng_noun:Thatcherite{}, eng_noun:serial{}, eng_noun:pedestrian{}, eng_noun:submarine{}, eng_noun:jolly{}, eng_noun:period{}, eng_noun:narrative{}, eng_noun:lowercase{}, eng_noun:fortnightly{}, eng_noun:racist{}, eng_noun:maglev{}, eng_noun:patient{}, eng_noun:stoic{}, eng_noun:print{}, eng_noun:radical{}, eng_noun:electrical{}, eng_noun:beef{}, eng_noun:supplicant{}, eng_noun:utmost{}, eng_noun:sour{}, eng_noun:moral{}, eng_noun:subversive{}, eng_noun:okay{}, eng_noun:hexadecimal{}, eng_noun:brave{}, eng_noun:incipient{}, eng_noun:Alsatian{}, eng_noun:damn{}, eng_noun:junior{}, eng_noun:Sikh{}, eng_noun:antique{}, eng_noun:med{}, eng_noun:possessive{}, eng_noun:kiasu{}, eng_noun:calm{}, eng_noun:Slovakian{}, eng_noun:horsey{}, eng_noun:tatterdemalion{}, eng_noun:Belarussian{}, eng_noun:Faroese{}, eng_noun:scotch{}, eng_noun:elective{}, eng_noun:select{}, eng_noun:cult{}, eng_noun:mercenary{}, eng_noun:vast{}, eng_noun:hardcore{}, eng_noun:eccentric{}, eng_noun:coordinate{}, eng_noun:conservative{}, eng_noun:dope{}, eng_noun:nondescript{}, eng_noun:Brobdingnagian{}, eng_noun:occidental{}, eng_noun:octuple{}, eng_noun:impossible{}, eng_noun:vanilla{}, eng_noun:bosom{}, eng_noun:azurine{}, eng_noun:axillar{}, eng_noun:awk{}, eng_noun:Avesta{}, eng_noun:savage{}, eng_noun:camp{}, eng_noun:icebox{}, eng_noun:alienate{}, eng_noun:Braille{}, eng_noun:medieval{}, eng_noun:yew{}, eng_noun:bilabial{}, eng_noun:lobster{}, eng_noun:scant{}, eng_noun:deaf{}, eng_noun:batty{}, eng_noun:artist{}, eng_noun:waterproof{}, eng_noun:technical{}, eng_noun:phosphorescent{}, eng_noun:googly{}, eng_noun:plosive{}, eng_noun:swish{}, eng_noun:Karelian{}, eng_noun:loden{}, eng_noun:clambake{}, eng_noun:velar{}, eng_noun:palatal{}, eng_noun:concomitant{}, eng_noun:leeward{}, eng_noun:plenipotentiary{}, eng_noun:virgin{}, eng_noun:adjutant{}, eng_noun:alar{}, eng_noun:neo - nazi{}, eng_noun:descendant{}, eng_noun:bygone{}, eng_noun:joint{}, eng_noun:passional{}, eng_noun:level{}, eng_noun:representative{}, eng_noun:Romaic{}, eng_noun:limit{}, eng_noun:trick{}, eng_noun:model{}, eng_noun:jazeraint{}, eng_noun:inchoate{}, eng_noun:phonetic{}, eng_noun:inchoactive{}, eng_noun:principal{}, eng_noun:tributary{}, eng_noun:pygmy{}, eng_noun:ribald{}, eng_noun:delivery{}, eng_noun:superior{}, eng_noun:lateral{}, eng_noun:reverse{}, eng_noun:endemic{}, eng_noun:cormorant{}, eng_noun:myopic{}, eng_noun:privy{}, eng_noun:verbatim{}, eng_noun:piggy{}, eng_noun:slinky{}, eng_noun:wizard{}, eng_noun:cocktail{}, eng_noun:cacuminal{}, eng_noun:blind{}, eng_noun:contrary{}, eng_noun:Novocastrian{}, eng_noun:limey{}, eng_noun:parvenu{}, eng_noun:Syracusan{}, eng_noun:ruddy{}, eng_noun:frail{}, eng_noun:bawd{}, eng_noun:borax{}, eng_noun:marcel{}, eng_noun:solute{}, eng_noun:swank{}, eng_noun:strait{}, eng_noun:botanical{}, eng_noun:cavalier{}, eng_noun:customary{}, eng_noun:devout{}, eng_noun:discount{}, eng_noun:disquiet{}, eng_noun:dominant{}, eng_noun:eleemosynary{}, eng_noun:equivocal{}, eng_noun:Erse{}, eng_noun:faint{}, eng_noun:farewell{}, eng_noun:feint{}, eng_noun:fellow{}, eng_noun:flirt{}, eng_noun:Fuegian{}, eng_noun:grand{}, eng_noun:hircine{}, eng_noun:hortatory{}, eng_noun:invective{}, eng_noun:mellow{}, eng_noun:migrant{}, eng_noun:ophidian{}, eng_noun:oyster{}, eng_noun:patrician{}, eng_noun:priority{}, eng_noun:prophylactic{}, eng_noun:sanguine{}, eng_noun:secondary{}, eng_noun:slight{}, eng_noun:snide{}, eng_noun:statistic{}, eng_noun:stray{}, eng_noun:moderate{}, eng_noun:teak{}, eng_noun:unlikely{}, eng_noun:whirlwind{}, eng_noun:formal{}, eng_noun:gimcrack{}, eng_noun:worthy{}, eng_noun:offside{}, eng_noun:auricular{}, eng_noun:reciprocal{}, eng_noun:phoney{}, eng_noun:desmoid{}, eng_noun:motel{}, eng_noun:Francophile{}, eng_noun:hyaline{}, eng_noun:Oregonian{}, eng_noun:offensive{}, eng_noun:larghetto{}, eng_noun:butch{}, eng_noun:tardy{}, eng_noun:Babylonian{}, eng_noun:miniature{}, eng_noun:adenoid{}, eng_noun:mammoth{}, eng_noun:diacritic{}, eng_noun:theatrical{}, eng_noun:mid - february{}, eng_noun:mid - june{}, eng_noun:mid - august{}, eng_noun:mid - fall{}, eng_noun:jean{}, eng_noun:sectarian{}, eng_noun:diabolic{}, eng_noun:progressive{}, eng_noun:tellurian{}, eng_noun:afferent{}, eng_noun:neutral{}, eng_noun:prompt{}, eng_noun:churchy{}, eng_noun:mammary{}, eng_noun:interim{}, eng_noun:Lesvonian{}, eng_noun:orderly{}, eng_noun:hood{}, eng_noun:googlish{}, eng_noun:nontrinitarian{}, eng_noun:cordial{}, eng_noun:asbestos{}, eng_noun:audible{}, eng_noun:tickle{}, eng_noun:kindred{}, eng_noun:Oliver{}, eng_noun:plus{}, eng_noun:Filipino{}, eng_noun:spiffy{}, eng_noun:organic{}, eng_noun:concave{}, eng_noun:repellent{}, eng_noun:embonpoint{}, eng_noun:precision{}, eng_noun:appositive{}, eng_noun:Chaldean{}, eng_noun:cetacean{}, eng_noun:sturdy{}, eng_noun:oriental{}, eng_noun:Balinese{}, eng_noun:instructive{}, eng_noun:itinerant{}, eng_noun:solo{}, eng_noun:familiar{}, eng_noun:narcotic{}, eng_noun:Walloon{}, eng_noun:capacity{}, eng_noun:pommie{}, eng_noun:daffodil{}, eng_noun:redeye{}, eng_noun:oval{}, eng_noun:geranium{}, eng_noun:custom{}, eng_noun:inland{}, eng_noun:excess{}, eng_noun:tinsel{}, eng_noun:canonical{}, eng_noun:oblong{}, eng_noun:commuter{}, eng_noun:agnate{}, eng_noun:cosmetic{}, eng_noun:moribund{}, eng_noun:preantepenultimate{}, eng_noun:mutant{}, eng_noun:faithful{}, eng_noun:catholic{}, eng_noun:exempt{}, eng_noun:traunch{}, eng_noun:plebeian{}, eng_noun:casual{}, eng_noun:suspect{}, eng_noun:alveolar{}, eng_noun:nonconformist{}, eng_noun:opiate{}, eng_noun:assistant{}, eng_noun:favourite{}, eng_noun:aerosol{}, eng_noun:autograph{}, eng_noun:hopeful{}, eng_noun:aphrodisiac{}, eng_noun:isometric{}, eng_noun:heliotrope{}, eng_noun:cynic{}, eng_noun:aero{}, eng_noun:flit{}, eng_noun:anti{}, eng_noun:sensitive{}, eng_noun:minus{}, eng_noun:septuagenarian{}, eng_noun:termagant{}, eng_noun:Etruscan{}, eng_noun:mimic{}, eng_noun:castaway{}, eng_noun:polycyclic{}, eng_noun:bicyclic{}, eng_noun:periodical{}, eng_noun:initial{}, eng_noun:antipodean{}, eng_noun:roundabout{}, eng_noun:comedogenic{}, eng_noun:psychic{}, eng_noun:frizzy{}, eng_noun:Andean{}, eng_noun:mutton{}, eng_noun:shortwave{}, eng_noun:illiterate{}, eng_noun:eugeroic{}, eng_noun:asthmatic{}, eng_noun:hominid{}, eng_noun:observable{}, eng_noun:observant{}, eng_noun:obverse{}, eng_noun:romantic{}, eng_noun:ultraconservative{}, eng_noun:ancillary{}, eng_noun:uggo{}, eng_noun:Caroline{}, eng_noun:diluent{}, eng_noun:deadpan{}, eng_noun:supernumerary{}, eng_noun:outboard{}, eng_noun:commonplace{}, eng_noun:knockdown{}, eng_noun:Yugoslav{}, eng_noun:nutrient{}, eng_noun:nymphomaniac{}, eng_noun:swarth{}, eng_noun:supine{}, eng_noun:solvent{}, eng_noun:blow - by - blow{}, eng_noun:extracurricular{}, eng_noun:westerly{}, eng_noun:woodland{}, eng_noun:memorial{}, eng_noun:likely{}, eng_noun:blow - up{}, eng_noun:blah{}, eng_noun:audio{}, eng_noun:wobbly{}, eng_noun:degenerate{}, eng_noun:desirable{}, eng_noun:workday{}, eng_noun:tribal{}, eng_noun:Elysium{}, eng_noun:jaded{}, eng_noun:doggy{}, eng_noun:upstage{}, eng_noun:Exoduster{}, eng_noun:Vatican{}, eng_noun:veteran{}, eng_noun:veterinary{}, eng_noun:virgate{}, eng_noun:immeasurable{}, eng_noun:flamboyant{}, eng_noun:quadragenarian{}, eng_noun:quintuplicate{}, eng_noun:ambient{}, eng_noun:Californian{}, eng_noun:haggard{}, eng_noun:umbilical{}, eng_noun:maudlin{}, eng_noun:unattractive{}, eng_noun:barefoot{}, eng_noun:dead - end{}, eng_noun:utilitarian{}, eng_noun:syllabic{}, eng_noun:preterite{}, eng_noun:bovine{}, eng_noun:polyzoan{}, eng_noun:shojo{}, eng_noun:bryozoan{}, eng_noun:italic{}, eng_noun:upstate{}, eng_noun:cleanup{}, eng_noun:petit{}, eng_noun:provincial{}, eng_noun:Malaysian{}, eng_noun:Freudian{}, eng_noun:Promethean{}, eng_noun:palmate{}, eng_noun:hairshirt{}, eng_noun:picky{}, eng_noun:upskirt{}, eng_noun:tandem{}, eng_noun:acrylic{}, eng_noun:wholemeal{}, eng_noun:adulterine{}, eng_noun:carotenoid{}, eng_noun:incognito{}, eng_noun:shoddy{}, eng_noun:knee - jerk{}, eng_noun:clumsy{}, eng_noun:noteworthy{}, eng_noun:transcendental{}, eng_noun:Finnophone{}, eng_noun:Russophone{}, eng_noun:Sinophone{}, eng_noun:Chewa{}, eng_noun:Manichaean{}, eng_noun:doggerel{}, eng_noun:Siamese{}, eng_noun:plantigrade{}, eng_noun:denialist{}, eng_noun:conscript{}, eng_noun:transitory{}, eng_noun:translative{}, eng_noun:brutalitarian{}, eng_noun:Eoarchean{}, eng_noun:Tonian{}, eng_noun:Holocene{}, eng_noun:Paleocene{}, eng_noun:unfortunate{}, eng_noun:antineoplastic{}, eng_noun:authoritarian{}, eng_noun:Laplacian{}, eng_noun:borderline{}, eng_noun:Eurasian{}, eng_noun:performant{}, eng_noun:multimedia{}, eng_noun:decadent{}, eng_noun:quinquagenarian{}, eng_noun:sibilant{}, eng_noun:topaz{}, eng_noun:claret{}, eng_noun:one - off{}, eng_noun:cinnabar{}, eng_noun:gainsboro{}, eng_noun:gunmetal - grey{}, eng_noun:brittle{}, eng_noun:vulnerary{}, eng_noun:hoar{}, eng_noun:postmodern{}, eng_noun:modernist{}, eng_noun:postmodernist{}, eng_noun:ethical{}, eng_noun:mazarine{}, eng_noun:pseudointellectual{}, eng_noun:pearly{}, eng_noun:preliminary{}, eng_noun:designer{}, eng_noun:penitentiary{}, eng_noun:hyoid{}, eng_noun:Attic{}, eng_noun:Ecuadorean{}, eng_noun:Ottoman{}, eng_noun:Renaissance{}, eng_noun:Salvadorean{}, eng_noun:Scorpion{}, eng_noun:Sicilian{}, eng_noun:Udmurt{}, eng_noun:Zen{}, eng_noun:boutique{}, eng_noun:cuneiform{}, eng_noun:champagne{}, eng_noun:hackney{}, eng_noun:capitate{}, eng_noun:ethmoid{}, eng_noun:interlocutory{}, eng_noun:unreliable{}, eng_noun:hereditary{}, eng_noun:wacko{}, eng_noun:turbinate{}, eng_noun:turbinal{}, eng_noun:mocha{}, eng_noun:feminist{}, eng_noun:easter{}, eng_noun:troglophile{}, eng_noun:ecru{}, eng_noun:piedmont{}, eng_noun:magnolia{}, eng_noun:head - on{}, eng_noun:Euro - sceptic{}, eng_noun:potty{}, eng_noun:nephritic{}, eng_noun:paratyphoid{}, eng_noun:doomsday{}, eng_noun:ocker{}, eng_noun:handheld{}, eng_noun:Shiite{}, eng_noun:Geraldine{}, eng_noun:quintuple{}, eng_noun:upland{}, eng_noun:ovoid{}, eng_noun:heavyweight{}, eng_noun:urticant{}, eng_noun:differential{}, eng_noun:guerrilla{}, eng_noun:literal{}, eng_noun:abhesive{}, eng_noun:semiautomatic{}, eng_noun:dink{}, eng_noun:tsarist{}, eng_noun:quantifiable{}, eng_noun:antidepressant{}, eng_noun:antimonarchist{}, eng_noun:dreadful{}, eng_noun:maxi{}, eng_noun:emphatic{}, eng_noun:anti - inflammatory{}, eng_noun:antimalarial{}, eng_noun:proletarian{}, eng_noun:Phoenician{}, eng_noun:Anglo - indian{}, eng_noun:teleost{}, eng_noun:parathyroid{}, eng_noun:smock{}, eng_noun:mockney{}, eng_noun:paraplegic{}, eng_noun:exquisite{}, eng_noun:flimsy{}, eng_noun:goofball{}, eng_noun:no - go{}, eng_noun:not - for - profit{}, eng_noun:colloid{}, eng_noun:proficient{}, eng_noun:intrusive{}, eng_noun:corkscrew{}, eng_noun:mattoid{}, eng_noun:shortie{}, eng_noun:ceremonial{}, eng_noun:germane{}, eng_noun:deviant{}, eng_noun:lunatic{}, eng_noun:tricolor{}, eng_noun:Hegelian{}, eng_noun:Calgarian{}, eng_noun:twilight{}, eng_noun:anticlerical{}, eng_noun:psychotic{}, eng_noun:jake{}, eng_noun:eligible{}, eng_noun:milquetoast{}, eng_noun:phocine{}, eng_noun:upbeat{}, eng_noun:aspic{}, eng_noun:Glagolitic{}, eng_noun:gewgaw{}, eng_noun:desktop{}, eng_noun:insomniac{}, eng_noun:incidental{}, eng_noun:dreary{}, eng_noun:aliped{}, eng_noun:prostrate{}, eng_noun:simoniac{}, eng_noun:alabaster{}, eng_noun:welter - weight{}, eng_noun:laggard{}, eng_noun:sophomore{}, eng_noun:bittersweet{}, eng_noun:westward{}, eng_noun:compassionate{}, eng_noun:bully{}, eng_noun:antirust{}, eng_noun:mammalian{}, eng_noun:paedo{}, eng_noun:antiterrorist{}, eng_noun:fantom{}, eng_noun:walk - off{}, eng_noun:scud{}, eng_noun:orthorexic{}, eng_noun:vermifuge{}, eng_noun:antispasmodic{}, eng_noun:benedictive{}, eng_noun:glossy{}, eng_noun:quinquennial{}, eng_noun:valetudinarian{}, eng_noun:nationalist{}, eng_noun:beserk{}, eng_noun:Thomist{}, eng_noun:ruderal{}, eng_noun:zygenid{}, eng_noun:gridelin{}, eng_noun:emergent{}, eng_noun:mezzanine{}, eng_noun:Nordic{}, eng_noun:traditionary{}, eng_noun:peripheral{}, eng_noun:egalitarian{}, eng_noun:thespian{}, eng_noun:Playboy{}, eng_noun:Lett{}, eng_noun:streetwise{}, eng_noun:tropic{}, eng_noun:bicuspid{}, eng_noun:pinpoint{}, eng_noun:chalybeate{}, eng_noun:delinquent{}, eng_noun:doctrinaire{}, eng_noun:peregrine{}, eng_noun:causal{}, eng_noun:hellion{}, eng_noun:octoploid{}, eng_noun:colly{}, eng_noun:backstage{}, eng_noun:centuple{}, eng_noun:metazoan{}, eng_noun:postgraduate{}, eng_noun:Visayan{}, eng_noun:all - in{}, eng_noun:second - rate{}, eng_noun:tandoori{}, eng_noun:perfective{}, eng_noun:preliterate{}, eng_noun:midair{}, eng_noun:confessional{}, eng_noun:Ionian{}, eng_noun:crypto{}, eng_noun:coelomate{}, eng_noun:comitative{}, eng_noun:Phrygian{}, eng_noun:aorist{}, eng_noun:Paralympian{}, eng_noun:unimpressive{}, eng_noun:futilitarian{}, eng_noun:operative{}, eng_noun:unfamiliar{}, eng_noun:conventual{}, eng_noun:modal{}, eng_noun:favorite{}, eng_noun:dusky{}, eng_noun:Mayan{}, eng_noun:third - rate{}, eng_noun:veggo{}, eng_noun:hereditarian{}, eng_noun:susceptible{}, eng_noun:nouveau{}, eng_noun:correspondent{}, eng_noun:bissextile{}, eng_noun:northward{}, eng_noun:expendable{}, eng_noun:experient{}, eng_noun:apocalyptic{}, eng_noun:clement{}, eng_noun:easterly{}, eng_noun:magistral{}, eng_noun:Choctaw{}, eng_noun:cometary{}, eng_noun:impracticable{}, eng_noun:alcaic{}, eng_noun:influent{}, eng_noun:unificationist{}, eng_noun:batrachian{}, eng_noun:cimmerian{}, eng_noun:digestive{}, eng_noun:unsuccessful{}, eng_noun:truant{}, eng_noun:Dacian{}, eng_noun:emollient{}, eng_noun:etesian{}, eng_noun:perishable{}, eng_noun:Newtonian{}, eng_noun:thermoplastic{}, eng_noun:thoroughbred{}, eng_noun:thunderstruck{}, eng_noun:Prussian{}, eng_noun:austral{}, eng_noun:eutherian{}, eng_noun:addolorato{}, eng_noun:touch - and - go{}, eng_noun:Unitarian{}, eng_noun:multinational{}, eng_noun:debit{}, eng_noun:montane{}, eng_noun:unproductive{}, eng_noun:irreconcilable{}, eng_noun:fractional{}, eng_noun:honorific{}, eng_noun:consequent{}, eng_noun:ultralight{}, eng_noun:scholastic{}, eng_noun:preppy{}, eng_noun:Hittite{}, eng_noun:dyspeptic{}, eng_noun:paperback{}, eng_noun:appellant{}, eng_noun:recombinant{}, eng_noun:sanitarian{}, eng_noun:Ossetic{}, eng_noun:surrealist{}, eng_noun:superplastic{}, eng_noun:copycat{}, eng_noun:fractal{}, eng_noun:naif{}, eng_noun:rheumatic{}, eng_noun:op - ed{}, eng_noun:litoral{}, eng_noun:laic{}, eng_noun:grownup{}, eng_noun:Quartodeciman{}, eng_noun:excelsior{}, eng_noun:prosthetic{}, eng_noun:schematic{}, eng_noun:prebendary{}, eng_noun:nonstop{}, eng_noun:caretaker{}, eng_noun:hatstand{}, eng_noun:seaside{}, eng_noun:matronymic{}, eng_noun:probiotic{}, eng_noun:Plutonian{}, eng_noun:monoclonal{}, eng_noun:Bostonian{}, eng_noun:fixative{}, eng_noun:arytenoid{}, eng_noun:hissy{}, eng_noun:cutthroat{}, eng_noun:predominant{}, eng_noun:teiid{}, eng_noun:quadrillionth{}, eng_noun:carotid{}, eng_noun:Lagrangian{}, eng_noun:dielectric{}, eng_noun:combustible{}, eng_noun:downstream{}, eng_noun:push - up{}, eng_noun:Berber{}, eng_noun:crapola{}, eng_noun:Geordie{}, eng_noun:Brummie{}, eng_noun:dotty{}, eng_noun:bendy{}, eng_noun:Aotearoan{}, eng_noun:Lusatian{}, eng_noun:dastard{}, eng_noun:assurgent{}, eng_noun:froggy{}, eng_noun:autistic{}, eng_noun:anorexic{}, eng_noun:cohortative{}, eng_noun:deist{}, eng_noun:polychrome{}, eng_noun:centauroid{}, eng_noun:metonymic{}, eng_noun:lenitive{}, eng_noun:vocable{}, eng_noun:bacchant{}, eng_noun:maladroit{}, eng_noun:Rastafarian{}, eng_noun:whist{}, eng_noun:homoiousian{}, eng_noun:polygastric{}, eng_noun:Discordian{}, eng_noun:chirpy{}, eng_noun:breakable{}, eng_noun:movable{}, eng_noun:immovable{}, eng_noun:unchangeable{}, eng_noun:guttural{}, eng_noun:southward{}, eng_noun:nonstandard{}, eng_noun:Theban{}, eng_noun:logistic{}, eng_noun:supertall{}, eng_noun:Maoist{}, eng_noun:prepollent{}, eng_noun:presbyterian{}, eng_noun:lowbrow{}, eng_noun:unquestionable{}, eng_noun:birdy{}, eng_noun:Canarian{}, eng_noun:heteroaromatic{}, eng_noun:abducent{}, eng_noun:jemmy{}, eng_noun:pandeist{}, eng_noun:fayre{}, eng_noun:scratch{}, eng_noun:dysthymic{}, eng_noun:chelicerate{}, eng_noun:organosilicon{}, eng_noun:tetraplicate{}, eng_noun:gamine{}, eng_noun:desiccant{}, eng_noun:irresponsible{}, eng_noun:singsong{}, eng_noun:southerly{}, eng_noun:Palauan{}, eng_noun:behavioralist{}, eng_noun:wormy{}, eng_noun:Carthusian{}, eng_noun:matrimonial{}, eng_noun:isolationist{}, eng_noun:blameless{}, eng_noun:imperforate{}, eng_noun:sing - song{}, eng_noun:Ngoni{}, eng_noun:Oscan{}, eng_noun:Melungeon{}, eng_noun:leathern{}, eng_noun:radge{}, eng_noun:aerospace{}, eng_noun:infralittoral{}, eng_noun:broon{}, eng_noun:tricenarian{}, eng_noun:constabulary{}, eng_noun:piezoelectric{}, eng_noun:fortean{}, eng_noun:mariachi{}, eng_noun:clarion{}, eng_noun:narcoleptic{}, eng_noun:stigmatic{}, eng_noun:recitative{}, eng_noun:braxy{}, eng_noun:deaf - mute{}, eng_noun:knee - high{}, eng_noun:shan{}, eng_noun:kiddy{}, eng_noun:adjoint{}, eng_noun:bombe{}, eng_noun:pre - op{}, eng_noun:punky{}, eng_noun:rough - and - tumble{}, eng_noun:stop - gap{}, eng_noun:egocentric{}, eng_noun:ergative{}, eng_noun:revivalist{}, eng_noun:mimetic{}, eng_noun:ducky{}, eng_noun:ebon{}, eng_noun:understage{}, eng_noun:somnifacient{}, eng_noun:inaugural{}, eng_noun:pulmonate{}, eng_noun:Moldovan{}, eng_noun:publique{}, eng_noun:run - on{}, eng_noun:denarian{}, eng_noun:sforzando{}, eng_noun:plebian{}, eng_noun:Windian{}, eng_noun:vendible{}, eng_noun:evangelical{}, eng_noun:poddy{}, eng_noun:uttermost{}, eng_noun:sparky{}, eng_noun:superordinate{}, eng_noun:pectinate{}, eng_noun:privative{}, eng_noun:Vegliot{}, eng_noun:accompagnato{}, eng_noun:Nilotic{}, eng_noun:superhuman{}, eng_noun:cast - iron{}, eng_noun:pose{}, eng_noun:quede{}, eng_noun:waxen{}, eng_noun:Iroquoian{}, eng_noun:curtal{}, eng_noun:stylistic{}, eng_noun:one - on - one{}, eng_noun:magique{}, eng_noun:deerskin{}, eng_noun:doeskin{}, eng_noun:frou - frou{}, eng_noun:duty - free{}, eng_noun:Nahua{}, eng_noun:polytechnic{}, eng_noun:proteid{}, eng_noun:dependable{}, eng_noun:ascendent{}, eng_noun:unpronounceable{}, eng_noun:geriatric{}, eng_noun:anticommunist{}, eng_noun:Austronesian{}, eng_noun:mesel{}, eng_noun:renewable{}, eng_noun:twisty{}, eng_noun:Quebecois{}, eng_noun:insensate{}, eng_noun:Comanche{}, eng_noun:crackerjack{}, eng_noun:Bielorussian{}, eng_noun:Moldovian{}, eng_noun:antipollution{}, eng_noun:appurtenant{}, eng_noun:dicky{}, eng_noun:ellipsoid{}, eng_noun:disposable{}, eng_noun:resale{}, eng_noun:devotional{}, eng_noun:unfruitful{}, eng_noun:microlaser{}, eng_noun:sacroiliac{}, eng_noun:Hibernian{}, eng_noun:eristic{}, eng_noun:expansionist{}, eng_noun:extempore{}, eng_noun:earthbound{}, eng_noun:eatable{}, eng_noun:fungoid{}, eng_noun:futurist{}, eng_noun:grown - up{}, eng_noun:bombproof{}, eng_noun:lapsarian{}, eng_noun:thigh - high{}, eng_noun:schizoid{}, eng_noun:nucleate{}, eng_noun:subsurface{}, eng_noun:smoggy{}, eng_noun:unwearable{}, eng_noun:suppliant{}, eng_noun:meridional{}, eng_noun:subwavelength{}, eng_noun:carnivoran{}, eng_noun:predicable{}, eng_noun:disyllabic{}, eng_noun:amygdalate{}, eng_noun:militarian{}, eng_noun:predicative{}, eng_noun:storybook{}, eng_noun:plainclothes{}, eng_noun:millenarian{}, eng_noun:deictic{}, eng_noun:dialup{}, eng_noun:spheroidal{}, eng_noun:Oxonian{}, eng_noun:terminative{}, eng_noun:ginny{}, eng_noun:indeterminant{}, eng_noun:nonprofit{}, eng_noun:historicist{}, eng_noun:streight{}, eng_noun:sextile{}, eng_noun:anticlinal{}, eng_noun:thermoelectric{}, eng_noun:jihadist{}, eng_noun:runtime{}, eng_noun:clericalist{}, eng_noun:coalescent{}, eng_noun:coalitionist{}, eng_noun:Javan{}, eng_noun:Okinawan{}, eng_noun:high - hat{}, eng_noun:determinative{}, eng_noun:redistributable{}, eng_noun:nacroleptic{}, eng_noun:stubby{}, eng_noun:frontpage{}, eng_noun:shorthorn{}, eng_noun:colonialist{}, eng_noun:come - hither{}, eng_noun:amenorrhoeic{}, eng_noun:nonzero{}, eng_noun:quadruplex{}, eng_noun:ringside{}, eng_noun:jannock{}, eng_noun:Tungusic{}, eng_noun:paraphilic{}, eng_noun:consumable{}, eng_noun:monoglot{}, eng_noun:corroborative{}, eng_noun:Orcadian{}, eng_noun:Shetlander{}, eng_noun:counteractive{}, eng_noun:Commie{}, eng_noun:placental{}, eng_noun:half - and - half{}, eng_noun:bluey{}, eng_noun:druggy{}, eng_noun:vigoroso{}, eng_noun:polyaromatic{}, eng_noun:paroxytone{}, eng_noun:polymorphonucleate{}, eng_noun:imparisyllabic{}, eng_noun:unmoral{}, eng_noun:brindle{}, eng_noun:suprasegmental{}, eng_noun:polypiarian{}, eng_noun:hydroid{}, eng_noun:preterm{}, eng_noun:tectiform{}, eng_noun:Lazarist{}, eng_noun:cytostatic{}, eng_noun:amygdaloid{}, eng_noun:flippy{}, eng_noun:Leonese{}, eng_noun:Valencian{}, eng_noun:acromegalic{}, eng_noun:Adelaidian{}, eng_noun:demoniac{}, eng_noun:tinhorn{}, eng_noun:chump - change{}, eng_noun:formalist{}, eng_noun:buffalo - skin{}, eng_noun:polyplacophoran{}, eng_noun:polygonial{}, eng_noun:actinopterygian{}, eng_noun:Edmontonian{}, eng_noun:broadleaf{}, eng_noun:aulic{}, eng_noun:equivoque{}, eng_noun:zetetic{}, eng_noun:Alabaman{}, eng_noun:coelurosaurian{}, eng_noun:hardcover{}, eng_noun:hortative{}, eng_noun:diaphoretic{}, eng_noun:intervarsity{}, eng_noun:primigravid{}, eng_noun:multistory{}, eng_noun:deflationary{}, eng_noun:determinable{}, eng_noun:drive - through{}, eng_noun:drop - in{}, eng_noun:luminal{}, eng_noun:make - up{}, eng_noun:pinchbeck{}, eng_noun:hardball{}, eng_noun:make - do{}, eng_noun:nonperishable{}, eng_noun:genethliac{}, eng_noun:tristate{}, eng_noun:alate{}, eng_noun:cut - off{}, eng_noun:Earthian{}, eng_noun:proinflammatory{}, eng_noun:reentrant{}, eng_noun:propellent{}, eng_noun:trimonthly{}, eng_noun:zig - zag{}, eng_noun:half - track{}, eng_noun:paraprofessional{}, eng_noun:praetorian{}, eng_noun:jackleg{}, eng_noun:sternutatory{}, eng_noun:ubersexual{}, eng_noun:precipitant{}, eng_noun:prekindergarten{}, eng_noun:monetarist{}, eng_noun:noneffective{}, eng_noun:measureless{}, eng_noun:immunosuppressive{}, eng_noun:multiform{}, eng_noun:multifamily{}, eng_noun:molluscan{}, eng_noun:emunctory{}, eng_noun:smoother{}, eng_noun:Antarctican{}, eng_noun:populist{}, eng_noun:neocolonialist{}, eng_noun:neutralist{}, eng_noun:butthurt{}, eng_noun:hit - and - run{}, eng_noun:trinomial{}, eng_noun:ofay{}, eng_noun:phasianid{}, eng_noun:intrant{}, eng_noun:alpinist{}, eng_noun:reconcilable{}, eng_noun:ceratopsid{}, eng_noun:underweight{}, eng_noun:melic{}, eng_noun:dyspraxic{}, eng_noun:protoctist{}, eng_noun:pseudocoelomate{}, eng_noun:pteropodine{}, eng_noun:Puebloan{}, eng_noun:adversative{}, eng_noun:returnable{}, eng_noun:dithyrambic{}, eng_noun:oppidan{}, eng_noun:equalitarian{}, eng_noun:downstyle{}, eng_noun:Biafran{}, eng_noun:organohalogen{}, eng_noun:organoiodine{}, eng_noun:crenate{}, eng_noun:Christofascist{}, eng_noun:footlong{}, eng_noun:tutelar{}, eng_noun:synchromesh{}, eng_noun:pentimal{}, eng_noun:replicant{}, eng_noun:non - human{}, eng_noun:squaloid{}, eng_noun:neopagan{}, eng_noun:Dakotan{}, eng_noun:nonexempt{}, eng_noun:Paphian{}, eng_noun:jerk - water{}, eng_noun:meristic{}, eng_noun:Galatian{}, eng_noun:paralysant{}, eng_noun:malglico{}, eng_noun:chelonian{}, eng_noun:nonnarcotic{}, eng_noun:nonobjective{}, eng_noun:benzenoid{}, eng_noun:nonreturnable{}, eng_noun:nonprofessional{}, eng_noun:nonofficial{}, eng_noun:nonresident{}, eng_noun:nonsympathizer{}, eng_noun:polynoid{}, eng_noun:Bozal{}, eng_noun:Darwinian{}, eng_noun:nematic{}, eng_noun:sociopathic{}, eng_noun:smectic{}, eng_noun:backstreet{}, eng_noun:processionary{}, eng_noun:Afghanistani{}, eng_noun:poikilotherm{}, eng_noun:gamomaniac{}, eng_noun:Franquist{}, eng_noun:Rhodesian{}, eng_noun:dement{}, eng_noun:unprovable{}, eng_noun:nitrenoid{}, eng_noun:Moravian{}, eng_noun:Gibraltarian{}, eng_noun:equipotential{}, eng_noun:salvationist{}, eng_noun:expiratory{}, eng_noun:Alabamian{}, eng_noun:ammonoid{}, eng_noun:aliquant{}, eng_noun:aphidian{}, eng_noun:eleutheromaniac{}, eng_noun:antifascist{}, eng_noun:amandine{}, eng_noun:versant{}, eng_noun:Kosovan{}, eng_noun:responsorial{}, eng_noun:for - profit{}, eng_noun:Patagonian{}, eng_noun:goony{}, eng_noun:buckshee{}, eng_noun:escharotic{}, eng_noun:technic{}, eng_noun:arsenical{}, eng_noun:corrigent{}, eng_noun:monoaromatic{}, eng_noun:organonitrogen{}, eng_noun:multiphase{}, eng_noun:ethoxy{}, eng_noun:aminoethoxy{}, eng_noun:asphyxiant{}, eng_noun:supramembrane{}, eng_noun:Titanian{}, eng_noun:Callistoan{}, eng_noun:corporatist{}, eng_noun:deere{}, eng_noun:sarmentose{}, eng_noun:Marist{}, eng_noun:nitroaryl{}, eng_noun:hexactine{}, eng_noun:embryoid{}, eng_noun:Japhetite{}, eng_noun:euploid{}, eng_noun:Lydian{}, eng_noun:inebriant{}, eng_noun:cholic{}, eng_noun:eutectoid{}, eng_noun:multivariate{}, eng_noun:natriuretic{}, eng_noun:nonmutant{}, eng_noun:multifunction{}, eng_noun:snotnose{}, eng_noun:exercitive{}, eng_noun:radiochemical{}, eng_noun:Jungian{}, eng_noun:Euroskeptic{}, eng_noun:querulent{}, eng_noun:Eutychian{}, eng_noun:Kurdistani{}, eng_noun:holo{}, eng_noun:Sienese{}, eng_noun:behabitive{}, eng_noun:commissive{}, eng_noun:Angevin{}, eng_noun:caudatan{}, eng_noun:dinocephalian{}, eng_noun:Rousseauian{}, eng_noun:Camunian{}, eng_noun:cooty{}, eng_noun:orthotic{}, eng_noun:antiscience{}, eng_noun:want - away{}, eng_noun:slimmer{}, eng_noun:semiliquid{}, eng_noun:renunciate{}, eng_noun:arval{}, eng_noun:tenuis{}, eng_noun:cameloid{}, eng_noun:multicast{}, eng_noun:Chaucerian{}, eng_noun:gradable{}, eng_noun:Kalmyk{}, eng_noun:brachycephalic{}, eng_noun:Mordovian{}, eng_noun:Tuvan{}, eng_noun:Buryatian{}, eng_noun:Kareli{}, eng_noun:Russki{}, eng_noun:polyschematist{}, eng_noun:polynemoid{}, eng_noun:lactoovovegetarian{}, eng_noun:tribrid{}, eng_noun:papish{}, eng_noun:megapod{}, eng_noun:audient{}, eng_noun:hemipteran{}, eng_noun:Judaean{}, eng_noun:Natufian{}, eng_noun:Philippian{}, eng_noun:mercantilist{}, eng_noun:sesquiquadrate{}, eng_noun:buffy{}, eng_noun:obscurant{}, eng_noun:immunotherapeutic{}, eng_noun:bracteate{}, eng_noun:Louisianan{}, eng_noun:jasperoid{}, eng_noun:paedophiliac{}, eng_noun:Xanthian{}, eng_noun:mirk{}, eng_noun:superpremium{}, eng_noun:Carolinian{}, eng_noun:Wyomingite{}, eng_noun:Delawarean{}, eng_noun:slapstickery{}, eng_noun:ultrarevolutionary{}, eng_noun:Technicolor{}, eng_noun:Cancerian{}, eng_noun:Geminian{}, eng_noun:Sammarinese{}, eng_noun:reconstructivist{}, eng_noun:postcanine{}, eng_noun:superexplosive{}, eng_noun:hymenopteran{}, eng_noun:lepidopteran{}, eng_noun:lucinid{}, eng_noun:Ithacan{}, eng_noun:pogonophoran{}, eng_noun:sepiolid{}, eng_noun:nutriceutical{}, eng_noun:butoh{}, eng_noun:cutover{}, eng_noun:chitty{}, eng_noun:semifluid{}, eng_noun:perciform{}, eng_noun:supermajor{}, eng_noun:Manichean{}, eng_noun:marly{}, eng_noun:mammaliaform{}, eng_noun:somnolytic{}, eng_noun:caridoid{}, eng_noun:mountant{}, eng_noun:one - piece{}, eng_noun:jugal{}, eng_noun:unlockable{}, eng_noun:articulatory{}, eng_noun:indexical{}, eng_noun:mesocephalic{}, eng_noun:collagist{}, eng_noun:Comoran{}, eng_noun:Monacan{}, eng_noun:Kittsian{}, eng_noun:homarine{}, eng_noun:compostable{}, eng_noun:techno - utopian{}, eng_noun:ultrashort{}, eng_noun:cerumenolytic{}, eng_noun:computerphobic{}, eng_noun:allopolyploid{}, eng_noun:amphidiploid{}, eng_noun:informatic{}, eng_noun:ameriginal{}, eng_noun:whacko{}, eng_noun:neurochemical{}, eng_noun:antiphonary{}, eng_noun:antiepileptic{}, eng_noun:unaccusative{}, eng_noun:postcareer{}, eng_noun:premarket{}, eng_noun:postgame{}, eng_noun:localist{}, eng_noun:antimodern{}, eng_noun:nonexecutive{}, eng_noun:midseason{}, eng_noun:neoliberal{}, eng_noun:Yeniseian{}, eng_noun:delipidate{}, eng_noun:bistable{}, eng_noun:psychostimulant{}, eng_noun:Thessalonican{}, eng_noun:four - poster{}, eng_noun:midsong{}, eng_noun:Caesarist{}, eng_noun:Sabbatian{}, eng_noun:equative{}, eng_noun:Dolomite{}, eng_noun:Atacaman{}, eng_noun:bilevel{}, eng_noun:ultrafundamentalist{}, eng_noun:Goan{}, eng_noun:Maharashtrian{}, eng_noun:Mangalorean{}, eng_noun:Malayali{}, eng_noun:Mumbaikar{}, eng_noun:Mapuche{}, eng_noun:nonschool{}, eng_noun:floaty{}, eng_noun:low - pass{}, eng_noun:psittacine{}, eng_noun:prosimian{}, eng_noun:oceanview{}, eng_noun:nonblack{}, eng_noun:nongay{}, eng_noun:antimilitarist{}, eng_noun:supermax{}, eng_noun:extremal{}, eng_noun:skookum{}, eng_noun:Picard{}, eng_noun:nonbilaterian{}, eng_noun:segregant{}, eng_noun:greyscale{}, eng_noun:diffusionist{}, eng_noun:ethnobotanical{}, eng_noun:universalist{}, eng_noun:glossopharyngeal{}, eng_noun:serialist{}, eng_noun:nonmusical{}, eng_noun:prehuman{}, eng_noun:anticapitalist{}, eng_noun:antiauthoritarian{}, eng_noun:authenticist{}, eng_noun:antiracist{}, eng_noun:contextualist{}, eng_noun:deconstructionist{}, eng_noun:softcover{}, eng_noun:nondance{}, eng_noun:semivegetarian{}, eng_noun:subregional{}, eng_noun:nonliterate{}, eng_noun:nonfamily{}, eng_noun:decisionist{}, eng_noun:evidentialist{}, eng_noun:conventionalist{}, eng_noun:compatibilist{}, eng_noun:symbolist{}, eng_noun:nonparty{}, eng_noun:regionalist{}, eng_noun:multi - storey{}, eng_noun:antinuke{}, eng_noun:readymade{}, eng_noun:structureless{}, eng_noun:suspensory{}, eng_noun:automatist{}, eng_noun:anticoagulation{}, eng_noun:midroll{}, eng_noun:poststructuralist{}, eng_noun:situationist{}, eng_noun:Mallorcan{}, eng_noun:Mallorquin{}, eng_noun:mumsy{}, eng_noun:nondyslexic{}, eng_noun:dead - set{}, eng_noun:crowdy{}, eng_noun:antirad{}, eng_noun:nonrecyclable{}, eng_noun:superspeed{}, eng_noun:backcast{}, eng_noun:nonclass{}, eng_noun:Hitlerite{}, eng_noun:manuary{}, eng_noun:multiplane{}, eng_noun:cheapass{}, eng_noun:cyberutopian{}, eng_noun:meseraic{}, eng_noun:vasorelaxant{}, eng_noun:nonhybrid{}, eng_noun:antisecretory{}, eng_noun:Lusitanian{}, eng_noun:Marlovian{}, eng_noun:Martiniquais{}, eng_noun:librul{}, eng_noun:Sirian{}, eng_noun:bunodont{}, eng_noun:peaker{}, eng_noun:dissolvent{}, eng_noun:noncola{}, eng_noun:nonsuicide{}, eng_noun:Araucanian{}, eng_noun:preggo{}, eng_noun:bioidentical{}, eng_noun:Bloquiste{}, eng_noun:matrist{}, eng_noun:midsession{}, eng_noun:non - relative{}, eng_noun:normotensive{}, eng_noun:nonvitamin{}, eng_noun:ballotechnic{}, eng_noun:antinationalist{}, eng_noun:antidepressive{}, eng_noun:supersessionist{}, eng_noun:posthuman{}, eng_noun:Meccan{}, eng_noun:Bucharestian{}, eng_noun:Belgradian{}, eng_noun:Nicosian{}, eng_noun:Sofian{}, eng_noun:Zagrebian{}, eng_noun:Osloite{}, eng_noun:Jakartan{}, eng_noun:Rangoonese{}, eng_noun:Kabulese{}, eng_noun:Baghdadi{}, eng_noun:pushbutton{}, eng_noun:Bushist{}, eng_noun:purgatoric{}, eng_noun:Megarian{}, eng_noun:Ivoirian{}, eng_noun:Sabaean{}, eng_noun:tufty{}, eng_noun:roughspun{}, eng_noun:antiphlogistic{}, eng_noun:deskside{}, eng_noun:Anglian{}, eng_noun:jimcrack{}, eng_noun:pre - socratic{}, eng_noun:Kalmuck{}, eng_noun:eobiotic{}, eng_noun:roll - on{}, eng_noun:largemouth{}, eng_noun:chemophobic{}, eng_noun:anorexigenic{}, eng_noun:Muscovian{}, eng_noun:entent{}, eng_noun:hypothenar{}, eng_noun:finikin{}, eng_noun:pensionary{}, eng_noun:antihistaminic{}, eng_noun:flatscreen{}, eng_noun:sourdine{}, eng_noun:nonaffected{}, eng_noun:Colophonian{}, eng_noun:noncrime{}, eng_noun:nonpsychotic{}, eng_noun:nonschizophrenic{}, eng_noun:nonuniversity{}, eng_noun:nonpagan{}, eng_noun:nonstative{}, eng_noun:noncancer{}, eng_noun:antiflatulent{}, eng_noun:nonindividual{}, eng_noun:nonhomosexual{}, eng_noun:antielitist{}, eng_noun:antiformalist{}, eng_noun:anticharm{}, eng_noun:nonfemale{}, eng_noun:Hebridean{}, eng_noun:antiholiday{}, eng_noun:Salian{}, eng_noun:scorpionate{}, eng_noun:nonalcohol{}, eng_noun:nonequal{}, eng_noun:epic{}, eng_noun:antiinfective{}, eng_noun:antipsoriatic{}, eng_noun:Masovian{}, eng_noun:radioprotective{}, eng_noun:Memphite{}, eng_noun:nondissident{}, eng_noun:multicuspid{}, eng_noun:nonvirus{}, eng_noun:nonfungible{}, eng_noun:nonprotectionist{}, eng_noun:noninnocent{}, eng_noun:nonadult{}, eng_noun:integrant{}, eng_noun:Osakan{}, eng_noun:nontranssexual{}, eng_noun:nonadolescent{}, eng_noun:muscid{}, eng_noun:champian{}, eng_noun:nonlesbian{}, eng_noun:nonmystic{}, eng_noun:occipitofrontal{}, eng_noun:nonsquare{}, eng_noun:superheavy{}, eng_noun:nonafrican{}, eng_noun:intercycle{}, eng_noun:nanofluid{}, eng_noun:sapphirine{}, eng_noun:nonequestrian{}, eng_noun:alkynyl{}, eng_noun:nonrelationship{}, eng_noun:carryable{}, eng_noun:Spinozist{}, eng_noun:paleoconservative{}, eng_noun:nonemployment{}, eng_noun:tetracuspid{}, eng_noun:schemey{}, eng_noun:Lemurian{}, eng_noun:millikelvin{}, eng_noun:incog{}, eng_noun:antifield{}, eng_noun:anticatarrhal{}, eng_noun:nonagreement{}, eng_noun:nonpolicy{}, eng_noun:superluxury{}, eng_noun:resolvent{}, eng_noun:multinomial{}, eng_noun:antithrombotic{}, eng_noun:multicomplex{}, eng_noun:antileukemic{}, eng_noun:antileukaemic{}, eng_noun:Transjordanian{}, eng_noun:nonpathology{}, eng_noun:nonradical{}, eng_noun:Mimantean{}, eng_noun:Ecumenopolitan{}, eng_noun:alkadienyl{}, eng_noun:nonsystem{}, eng_noun:bignose{}, eng_noun:submonolayer{}, eng_noun:carcinostatic{}, eng_noun:nonrepublic{}, eng_noun:nonjuvenile{}, eng_noun:implex{}, eng_noun:prec.{}, eng_noun:nondesigner{}, eng_noun:noninvestment{}, eng_noun:Franco - manitoban{}, eng_noun:antirheumatic{}, eng_noun:overside{}, eng_noun:superwide{}, eng_noun:second - to - last{}, eng_noun:digastric{}, eng_noun:calefactory{}, eng_noun:cancroid{}, eng_noun:capitulary{}, eng_noun:vasopressor{}, eng_noun:cavicorn{}, eng_noun:extravasate{}, eng_noun:antiunitary{}, eng_noun:Proto - iranian{}, eng_noun:cebine{}, eng_noun:ranid{}, eng_noun:Lacedemonian{}, eng_noun:shitfuck{}, eng_noun:Numidian{}, eng_noun:mooey{}, eng_noun:Servian{}, eng_noun:southron{}, eng_noun:Hanoverian{}, eng_noun:Sassanian{}, eng_noun:Sasanid{}, eng_noun:Manichaeist{}, eng_noun:presphenoid{}, eng_noun:Erewhonian{}, eng_noun:Yerevanian{}, eng_noun:stiddy{}, eng_noun:noncharismatic{}, eng_noun:nonethnic{}, eng_noun:rammy{}, eng_noun:quot.{}, eng_noun:nonfugitive{}, eng_noun:Transvaalian{}, eng_noun:Saxonian{}, eng_noun:Livornian{}, eng_noun:Marquesan{}, eng_noun:fucoid{}, eng_noun:congratulant{}, eng_noun:antidiarrhoeic{}, eng_noun:heterometal{}, eng_noun:fluoroaromatic{}, eng_noun:nonevergreen{}, eng_noun:hematinic{}, eng_noun:sextan{}, eng_noun:spagiric{}, eng_noun:Ghanan{}, eng_noun:vomitive{}, eng_noun:vitalist{}, eng_noun:vesicatory{}, eng_noun:ex - pat{}, eng_noun:Mazandarani{}, eng_noun:necessitarian{}, eng_noun:residentiary{}, eng_noun:nonblonde{}, eng_noun:invitatory{}, eng_noun:inequivalve{}, eng_noun:equivalve{}, eng_noun:Tarentine{}, eng_noun:Gallophone{}, eng_noun:sideway{}, eng_noun:Kittitian{}, eng_noun:Rhenish{}, eng_noun:antidivision{}, eng_noun:exclusionist{}, eng_noun:dozenal{}, eng_noun:tony{}, eng_noun:cyprinoid{}, eng_noun:loxodont{}, eng_noun:dilambdodont{}, eng_noun:labyrinthodont{}, eng_noun:antirepublican{}, eng_noun:antisyphilitic{}, eng_noun:antiromantic{}, eng_noun:antiarthritic{}, eng_noun:agrypnotic{}, eng_noun:multiplay{}, eng_noun:nonunity{}, eng_noun:sparoid{}, eng_noun:preadult{}, eng_noun:nonperennial{}, eng_noun:Khurrite{}, eng_noun:emulgent{}, eng_noun:attrahent{}, eng_noun:awesome - sauce{}, eng_noun:awesomesauce{}, eng_noun:nonassociation{}, eng_noun:Toisanese{}, eng_noun:Taishanese{}, eng_noun:neotraditionalist{}, eng_noun:serbophile{}, eng_noun:Barcelonian{}, eng_noun:Sevillian{}, eng_noun:Bilbaoan{}, eng_noun:goodwilly{}, eng_noun:transpondian{}, eng_noun:schizophasic{}, eng_noun:Exmoorian{}, eng_noun:Gergovian{}, eng_noun:headful{}, eng_noun:nonfeature{}, eng_noun:antisnob{}, eng_noun:Pentecostalist{}, eng_noun:anchal{}, eng_noun:pomosexual{}, eng_noun:Nueir{}, eng_noun:fissiped{}, eng_noun:mass - energy{}, eng_noun:appeasatory{}, eng_noun:bummy{}, eng_noun:multicable{}, eng_noun:Directoire{}, eng_noun:alabastre{}, eng_noun:nonextremist{}, eng_noun:Philipino{}, eng_noun:Humean{}, eng_noun:Humeian{}, eng_noun:Humian{}, eng_noun:Novgorodian{}, eng_noun:thrice - monthly{}, eng_noun:Trifluvien{}, eng_noun:Trifluvienne{}, eng_noun:Belgravian{}, eng_noun:Gandharan{}, eng_noun:swike{}, eng_noun:tinclad{}, eng_noun:robosexual{}, eng_noun:schizosexual{}, eng_noun:skimble - skamble{}, eng_noun:noncancellation{}, eng_noun:Bessarabian{}, eng_noun:portside{}, eng_noun:Ostian{}, eng_noun:looksist{}, eng_noun:Neo - pythagorean{}, eng_noun:midstorm{}, eng_noun:prasine{}, eng_noun:Tarragonan{}, eng_noun:masculist{}, eng_noun:Malaitan{}, eng_noun:subsalt{}, eng_noun:injectible{}, eng_noun:splitist{}, eng_noun:Dahomeyan{}, eng_noun:sternutative{}, eng_noun:Zamoran{}, eng_noun:iguanian{}, eng_noun:parasomniac{}, eng_noun:zygodactyle{}, eng_noun:ziphioid{}, eng_noun:jibberish{}, eng_noun:papionine{}, eng_noun:Feejeean{}, eng_noun:slappy{}, eng_noun:Atlantan{}, eng_noun:wayn{}, eng_noun:turkophone{}, eng_noun:connexive{}, eng_noun:Segovian{}, eng_noun:Wollof{}, eng_noun:antiequalitarian{}, eng_noun:gneissoid{}, eng_noun:Icelandish{}, eng_noun:odontalgic{}, eng_noun:nonchain{}, eng_noun:antiparty{}, eng_noun:prework{}, eng_noun:Rumelian{}, eng_noun:nondependent{}, eng_noun:antirationalist{}, eng_noun:antiprogressive{}, eng_noun:antinociceptive{}, eng_noun:preshave{}, eng_noun:friendy{}, eng_noun:juniour{}, eng_noun:Shirburnian{}, eng_noun:lampriform{}, eng_noun:Palestinean{}, eng_noun:plastick{}, eng_noun:Homoean{}, eng_noun:clashy{}, eng_noun:Malayalee{}, eng_noun:multilobe{}, eng_noun:unworth{}, eng_noun:Monothelete{}, eng_noun:mystick{}, eng_noun:hieroglyphick{}, eng_noun:scholastick{}, eng_noun:ecclesiastick{}, eng_noun:panick{}, eng_noun:Theatine{}, eng_noun:diuretick{}, eng_noun:eccentrick{}, eng_noun:emetick{}, eng_noun:endemick{}, eng_noun:fanatick{}, eng_noun:georgick{}, eng_noun:hectick{}, eng_noun:heretick{}, eng_noun:hysterick{}, eng_noun:iambick{}, eng_noun:melancholick{}, eng_noun:metaphysick{}, eng_noun:Pindarick{}, eng_noun:polemick{}, eng_noun:posteriour{}, eng_noun:Romantick{}, eng_noun:soporifick{}, eng_noun:styptick{}, eng_noun:Stoick{}, eng_noun:nonsonant{}, eng_noun:perticular{}, eng_noun:antihydropic{}, eng_noun:Orkneyan{}, eng_noun:Kurilian{}, eng_noun:doggrel{}, eng_noun:tropick{}, eng_noun:neo - creo{}, eng_noun:bitch - ass{}, eng_noun:arfarfanarf{}, eng_noun:Cephalonian{}, eng_noun:preelection{}, eng_noun:distillatory{}, eng_noun:underhead{}, eng_noun:lamellibranchiate{}, eng_noun:interpause{}, eng_noun:bezoardic{}, eng_noun:theaterical{}, eng_noun:antepileptic{}, eng_noun:Asmonean{}, eng_noun:Biscayan{}, eng_noun:supermaterial{}, eng_noun:reservatory{}, eng_noun:gould{}, eng_noun:foreshot{}, eng_noun:metronymic{}, eng_noun:gallaunt{}, eng_noun:Turanian{}, eng_noun:dickgirl{}, eng_noun:Hutchinsonian{}, eng_noun:fouth{}, eng_noun:Waldensian{}, eng_noun:nash{}, eng_noun:Universalian{}, eng_noun:Tribecan{}, eng_noun:Tyrian{}, eng_noun:nautiloid{}, eng_noun:Socotran{}, eng_noun:curvative{}, eng_noun:depressomotor{}, eng_noun:nucleobranch{}, eng_noun:elasmobranchiate{}, eng_noun:shlenter{}, eng_noun:preobservation{}, eng_noun:antihydrophobic{}, eng_noun:Khazarian{}, eng_noun:neurosyphilitic{}, eng_noun:superdominant{}, eng_noun:ophiurioid{}, eng_noun:ostracoid{}, eng_noun:payen{}, eng_noun:absorbefacient{}, eng_noun:interneural{}, eng_noun:Thuringian{}, eng_noun:classick{}, eng_noun:Shelbyvillian{}, eng_noun:pluriliteral{}, eng_noun:ischuretic{}, eng_noun:tympanohyal{}, eng_noun:carborexic{}, eng_noun:beesome{}, eng_noun:epipterygoid{}, eng_noun:freelage{}, eng_noun:freeledge{}, eng_noun:interrenal{}, eng_noun:Observantine{}, eng_noun:hypobranchial{}, eng_noun:crackerass{}, eng_noun:subopercular{}, eng_noun:Brunonian{}, eng_noun:antipsoric{}, eng_noun:cloam{}, eng_noun:clome{}, eng_noun:sage{}, eng_noun:hand{}, eng_noun:bloom{}, eng_noun:firm{}, eng_noun:grave{}, eng_noun:compact{}, eng_noun:abrupt{}, eng_noun:major{}, eng_noun:window{}, eng_noun:winter{}, eng_noun:exit{}, eng_noun:adulterant{}, eng_noun:ageless{}, eng_noun:antacid{}, eng_noun:anthozoan{}, eng_noun:arboreal{}, eng_noun:asiatic{}, eng_noun:argent{}, eng_noun:aroid{}, eng_noun:bareback{}, eng_noun:batiste{}, eng_noun:bigamy{}, eng_noun:binominal{}, eng_noun:braggart{}, eng_noun:bouffant{}, eng_noun:buccaneer{}, eng_noun:chorine{}, eng_noun:chappy{}, eng_noun:carpal{}, eng_noun:confederate{}, eng_noun:corporal{}, eng_noun:crystalloid{}, eng_noun:combatant{}, eng_noun:cotton{}, eng_noun:covenant{}, eng_noun:coverall{}, eng_noun:cycloid{}, eng_noun:contemplative{}, eng_noun:complex{}, eng_noun:contrast{}, eng_noun:downstairs{}, eng_noun:disincentive{}, eng_noun:druid{}, eng_noun:expectorant{}, eng_noun:encaustic{}, eng_noun:fave{}, eng_noun:fawn{}, eng_noun:fossil{}, eng_noun:freestyle{}, eng_noun:gaudy{}, eng_noun:incentive{}, eng_noun:instant{}, eng_noun:holothurian{}, eng_noun:holstein{}, eng_noun:hominoid{}, eng_noun:itinerary{}, eng_noun:lean{}, eng_noun:interglacial{}, eng_noun:labiovelar{}, eng_noun:laconian{}, eng_noun:julian{}, eng_noun:lamarckism{}, eng_noun:kamikaze{}, eng_noun:maximal{}, eng_noun:minimum{}, eng_noun:livelong{}, eng_noun:maigre{}, eng_noun:medley{}, eng_noun:mammal{}, eng_noun:maniac{}, eng_noun:mohican{}, eng_noun:manual{}, eng_noun:lubricant{}, eng_noun:monogenesis{}, eng_noun:midland{}, eng_noun:moot{}, eng_noun:northumbrian{}, eng_noun:novelty{}, eng_noun:optimum{}, eng_noun:oxytone{}, eng_noun:mulatto{}, eng_noun:nescient{}, eng_noun:neurology{}, eng_noun:orography{}, eng_noun:murrey{}, eng_noun:nile{}, eng_noun:nitrous{}, eng_noun:octosyllable{}, eng_noun:outcast{}, eng_noun:nonpareil{}, eng_noun:overglaze{}, eng_noun:penult{}, eng_noun:perennial{}, eng_noun:parliamentarian{}, eng_noun:party{}, eng_noun:perpendicular{}, eng_noun:psychotherapy{}, eng_noun:ragtime{}, eng_noun:prole{}, eng_noun:premolar{}, eng_noun:rear{}, eng_noun:rodent{}, eng_noun:reptile{}, eng_noun:respondent{}, eng_noun:restorative{}, eng_noun:retardate{}, eng_noun:refrigeratory{}, eng_noun:reverend{}, eng_noun:revolutionary{}, eng_noun:sexennial{}, eng_noun:sextuple{}, eng_noun:sole{}, eng_noun:southpaw{}, eng_noun:septcentenary{}, eng_noun:sigmoid{}, eng_noun:signatory{}, eng_noun:sundry{}, eng_noun:tan{}, eng_noun:straightaway{}, eng_noun:supremacist{}, eng_noun:stable{}, eng_noun:subcontrary{}, eng_noun:submultiple{}, eng_noun:subscript{}, eng_noun:steel{}, eng_noun:substituent{}, eng_noun:tense{}, eng_noun:uliginose{}, eng_noun:ultimate{}, eng_noun:triplicate{}, eng_noun:warrigal{}, eng_noun:wrong{}, eng_noun:vicegerent{}, eng_noun:whit{}, eng_noun:viverrid{}, eng_noun:plain{}, eng_noun:limp{}, eng_noun:bible{}, eng_noun:donovan{}, eng_noun:hesperian{}, eng_noun:mexica{}, eng_noun:murcian{}, eng_noun:qallunaaq{}, eng_noun:velcro{}, eng_noun:cleft{}, eng_noun:lush{}, eng_noun:creed{}, eng_noun:arched{}, eng_noun:bicorn{}, eng_noun:lesser{}, eng_noun:mizzen{}, eng_noun:cimeter{}, eng_noun:gallican{}, eng_noun:filicoid{}, eng_noun:podagric{}, eng_noun:palmiped{}, eng_noun:squamate{}, eng_noun:incompetent{}, eng_noun:repercussive{}, eng_noun:consuetudinary{}, eng_noun:bona{}, eng_noun:bung{}, eng_noun:tagrag{}, eng_noun:cocket{}, eng_noun:game{}, eng_noun:rate{}, eng_noun:nova{}, eng_noun:wont{}, eng_noun:algal{}, eng_noun:offal{}, eng_noun:bluff{}, eng_noun:piano{}, eng_noun:prime{}, eng_noun:pokey{}, eng_noun:rummy{}, eng_noun:contra{}, eng_noun:grunge{}, eng_noun:poison{}, eng_noun:allegro{}, eng_noun:analyte{}, eng_noun:subject{}, eng_noun:olivine{}, eng_noun:singlet{}, eng_noun:topping{}, eng_noun:runaway{}, eng_noun:meaning{}, eng_noun:gangland{}, eng_noun:midfield{}, eng_noun:amnesiac{}, eng_noun:dementia{}, eng_noun:underage{}, eng_noun:civilian{}, eng_noun:halftone{}, eng_noun:malonate{}, eng_noun:initiate{}, eng_noun:glyceryl{}, eng_noun:archrival{}, eng_noun:monoblock{}, eng_noun:ponderosa{}, eng_noun:threonine{}, eng_noun:absurdist{}, eng_noun:hydration{}, eng_noun:millinery{}, eng_noun:firstborn{}, eng_noun:leucovorin{}, eng_noun:riverfront{}, eng_noun:agglomerate{}, eng_noun:exonuclease{}, eng_noun:creationist{}, eng_noun:rechargeable{}, eng_noun:recreational{}, eng_noun:vaudevillian{}, eng_noun:antihypertensive{}, eng_noun:coloured{}, eng_noun:wraparound{}, eng_noun:fizgig{}, eng_noun:derivate{}, eng_noun:trilingual{}, eng_noun:semi{}, eng_noun:encyclical{}, eng_noun:hentai{}, eng_noun:blobber{}, eng_noun:lipoid{}, eng_noun:saint{}, eng_noun:deductible{}, eng_noun:humanoid{}, eng_noun:cruciform{}, eng_noun:gallant{}, eng_noun:vagabond{}, eng_noun:adagio{}, eng_noun:paratransit{}, eng_noun:biochemical{}, eng_noun:hoop{}, eng_noun:voluptuary{}, eng_noun:reach{}, eng_noun:reprobate{}, eng_noun:navarrese{}, eng_noun:crescendo{}, eng_noun:freehold{}, eng_noun:multicellular{}, eng_noun:desiderative{}, eng_noun:bald{}, eng_noun:maroon{}, eng_noun:tercentennial{}, eng_noun:tun{}, eng_noun:doris{}, eng_noun:enclitic{}, eng_noun:mini{}, eng_noun:summa{}, eng_noun:fleet{}, eng_noun:romance{}, eng_noun:continuative{}, eng_noun:float{}, eng_noun:fore{}, eng_noun:dark{}, eng_noun:plainchant{}, eng_noun:obligato{}, eng_noun:catenary{}, eng_noun:psychosurgery{}, eng_noun:fair{}, eng_noun:sexagesimal{}, eng_noun:cossack{}, eng_noun:new york{}, eng_noun:kook{}, eng_noun:laterite{}, eng_noun:interventionist{}, eng_noun:promo{}, eng_noun:hairsplitting{}, eng_noun:blowhard{}, eng_noun:majuscule{}, eng_noun:county{}, eng_noun:bilingual{}, eng_noun:mineral{}, eng_noun:adept{}, eng_noun:natal{}, eng_noun:lay{}, eng_noun:papist{}, eng_noun:novel{}, eng_noun:tiptop{}, eng_noun:default{}, eng_noun:Hayekian{}, eng_noun:preordination{}, eng_noun:triphibian{}, eng_noun:peery{}, eng_noun:antiacetylcholinesterase{}, eng_noun:deafmute{}, eng_noun:postdisco{}, eng_noun:vegetive{}, eng_noun:lyrick{}, eng_noun:monastick{}, eng_noun:italick{}, eng_noun:epidemick{}, eng_noun:exotick{}, eng_noun:dynamick{}, eng_noun:eclectick{}, eng_noun:epileptick{}, eng_noun:escharotick{}, eng_noun:quadratick{}, eng_noun:sudorifick{}, eng_noun:Koorilian{}, eng_noun:Thibetan{}, eng_noun:urodelian{}, eng_noun:pre - cana{}, eng_noun:metallorganic{}, eng_noun:might - be{}, eng_noun:urohyal{}, eng_noun:Pestalozzian{}, eng_noun:Genevese{}, eng_noun:maxillopalatine{}, eng_noun:utilitarianist{}, eng_noun:dodecastyle{}, eng_noun:uncuth{}, eng_noun:Esculapian{}, eng_noun:circumjovial{}, eng_noun:aflagellate{}, eng_noun:aromatick{}, eng_noun:antiparalytic{}, eng_noun:technoid{}, eng_noun:laniary{}, eng_noun:epipharyngeal{}, eng_noun:far{}, eng_noun:which{}, eng_noun:day{}, eng_noun:counter{}, eng_noun:ill{}, eng_noun:adrenal{}, eng_noun:anabolic{}, eng_noun:anglophobe{}, eng_noun:bedouin{}, eng_noun:binomial{}, eng_noun:circular{}, eng_noun:coward{}, eng_noun:crackpot{}, eng_noun:downstate{}, eng_noun:downwind{}, eng_noun:decorative{}, eng_noun:diamagnetic{}, eng_noun:estonian{}, eng_noun:gourmand{}, eng_noun:glare{}, eng_noun:illuminant{}, eng_noun:herbal{}, eng_noun:justiciary{}, eng_noun:malacostracan{}, eng_noun:metalloid{}, eng_noun:luddite{}, eng_noun:opponent{}, eng_noun:nemertean{}, eng_noun:pontifical{}, eng_noun:pseud{}, eng_noun:proboscidean{}, eng_noun:raven{}, eng_noun:quartile{}, eng_noun:regent{}, eng_noun:relaxant{}, eng_noun:spiracle{}, eng_noun:tart{}, eng_noun:tricolour{}, eng_noun:wholegrain{}, eng_noun:well{}, eng_noun:hollow{}, eng_noun:cambrian{}, eng_noun:chaldee{}, eng_noun:pauline{}, eng_noun:textuary{}, eng_noun:cathedra{}, eng_noun:braggadocian{}, eng_noun:self{}, eng_noun:sear{}, eng_noun:haut{}, eng_noun:foul{}, eng_noun:nomen{}, eng_noun:tailor{}, eng_noun:billiard{}, eng_noun:colubrid{}, eng_noun:converse{}, eng_noun:mercurian{}, eng_noun:nighttime{}, eng_noun:antisense{}, eng_noun:southside{}, eng_noun:plaintext{}, eng_noun:antivirus{}, eng_noun:teleporter{}, eng_noun:middleweight{}, eng_noun:dissociative{}, eng_noun:maniraptoran{}, eng_noun:preselection{}, eng_noun:chloroformate{}, eng_noun:concessionary{}, eng_noun:flip{}, eng_noun:interlinear{}, eng_noun:fait{}, eng_noun:dipteran{}, eng_noun:yonder{}, eng_noun:semblant{}, eng_noun:turbo{}, eng_noun:loggerhead{}, eng_noun:platonic{}, eng_noun:corrective{}, eng_noun:slavonian{}, eng_noun:preadolescent{}, eng_noun:purgatory{}, eng_noun:choroid{}, eng_noun:net{}, eng_noun:glamour{}, eng_noun:dud{}, eng_noun:elder{}, eng_noun:postseason{}, eng_noun:carmine{}, eng_noun:feeling{}, eng_noun:darling{}, eng_noun:fishing{}, eng_noun:opening{}, eng_noun:ballooning{}, eng_noun:daring{}, eng_noun:farming{}, eng_noun:birthing{}, eng_noun:screaming{}, eng_noun:wayfaring{}, eng_noun:Acadian{}, eng_noun:alien{}, eng_noun:country{}, eng_noun:market{}, eng_noun:current{}, eng_noun:academic{}, eng_noun:accessory{}, eng_noun:accusative{}, eng_noun:Algerian{}, eng_noun:derivative{}, eng_noun:Brazilian{}, eng_noun:green{}, eng_noun:purple{}, eng_noun:polyglot{}, eng_noun:consonant{}, eng_noun:adamant{}, eng_noun:Indonesian{}, eng_noun:north{}, eng_noun:rainbow{}, eng_noun:bisque{}, eng_noun:cream{}, eng_noun:ivory{}, eng_noun:ebony{}, eng_noun:saffron{}, eng_noun:lilac{}, eng_noun:ochre{}, eng_noun:silly{}, eng_noun:primrose{}, eng_noun:fascist{}, eng_noun:emerald{}, eng_noun:marinara{}, eng_noun:Taiwanese{}, eng_noun:Desi{}, eng_noun:Lithuanian{}, eng_noun:brief{}, eng_noun:spin{}, eng_noun:cover{}, eng_noun:blanket{}, eng_noun:electric{}, eng_noun:shallow{}, eng_noun:sorry{}, eng_noun:vertical{}, eng_noun:analog{}, eng_noun:corporate{}, eng_noun:yon{}, eng_noun:Manchu{}, eng_noun:mock{}, eng_noun:gourmet{}, eng_noun:coffee{}, eng_noun:diurnal{}, eng_noun:original{}, eng_noun:ordinal{}, eng_noun:flight{}, eng_noun:buggy{}, eng_noun:PC{}, eng_noun:steam{}, eng_noun:holy{}, eng_noun:weird{}, eng_noun:tangent{}, eng_noun:negro{}, eng_noun:Bahraini{}, eng_noun:Bolivian{}, eng_noun:Uzbek{}, eng_noun:Jamaican{}, eng_noun:Moroccan{}, eng_noun:Mozambican{}, eng_noun:Chadian{}, eng_noun:Burmese{}, eng_noun:burkinabe{}, eng_noun:Nauruan{}, eng_noun:Micronesian{}, eng_noun:Montserratian{}, eng_noun:Niuean{}, eng_noun:Adrianopolitan{}, eng_noun:soporific{}, eng_noun:Ilocano{}, eng_noun:flamingo{}, eng_noun:festival{}, eng_noun:perspective{}, eng_noun:reliable{}, eng_noun:double{}, eng_noun:kitsch{}, eng_noun:bimillennial{}, eng_noun:diamond{}, eng_noun:heuristic{}, eng_noun:practical{}, eng_noun:empty{}, eng_noun:pyro{}, eng_noun:rogue{}, eng_noun:angelic{}, eng_noun:ornamental{}, eng_noun:expert{}, eng_noun:regulation{}, eng_noun:bisexual{}, eng_noun:remainder{}, eng_noun:uppercase{}, eng_noun:panic{}, eng_noun:component{}, eng_noun:middle{}, eng_noun:maybe{}, eng_noun:oak{}, eng_noun:Islamist{}, eng_noun:roast{}, eng_noun:royal{}, eng_noun:les{}, eng_noun:spiral{}, eng_noun:incident{}, eng_noun:chronic{}, eng_noun:hypothetical{}, eng_noun:penitent{}, eng_noun:aggravative{}, eng_noun:ambulatory{}, eng_noun:giant{}, eng_noun:ay{}, eng_noun:hetty{}, eng_noun:Chechen{}, eng_noun:fatty{}, eng_noun:atheist{}, eng_noun:oblique{}, eng_noun:mild{}, eng_noun:mortal{}, eng_noun:sticky{}, eng_noun:blag{}, eng_noun:lingual{}, eng_noun:pectoral{}, eng_noun:magnetic{}, eng_noun:beryl{}, eng_noun:cornflower{}, eng_noun:subsidiary{}, eng_noun:crispy{}, eng_noun:surrogate{}, eng_noun:virtuoso{}, eng_noun:vivid{}, eng_noun:barren{}, eng_noun:aggro{}, eng_noun:brassy{}, eng_noun:cerise{}, eng_noun:onyx{}, eng_noun:phobic{}, eng_noun:Tory{}, eng_noun:asexual{}, eng_noun:banner{}, eng_noun:midweek{}, eng_noun:mother - of - pearl{}, eng_noun:operant{}, eng_noun:provocative{}, eng_noun:surplus{}, eng_noun:tabby{}, eng_noun:tithe{}, eng_noun:bunny{}, eng_noun:pantheist{}, eng_noun:quantum{}, eng_noun:mid - october{}, eng_noun:mid - march{}, eng_noun:ruminant{}, eng_noun:emetic{}, eng_noun:dexter{}, eng_noun:adolescent{}, eng_noun:lovely{}, eng_noun:pygmalion{}, eng_noun:demotic{}, eng_noun:variant{}, eng_noun:anesthetic{}, eng_noun:thermal{}, eng_noun:sore{}, eng_noun:motor{}, eng_noun:foster{}, eng_noun:Inuit{}, eng_noun:ageist{}, eng_noun:nostalgic{}, eng_noun:aliquot{}, eng_noun:chapel{}, eng_noun:gentle{}, eng_noun:bumper{}, eng_noun:submissive{}, eng_noun:auxiliary{}, eng_noun:radiant{}, eng_noun:woody{}, eng_noun:shank{}, eng_noun:aliphatic{}, eng_noun:editorial{}, eng_noun:soviet{}, eng_noun:fond{}, eng_noun:uniform{}, eng_noun:grande{}, eng_noun:anthropoid{}, eng_noun:intimate{}, eng_noun:chipotle{}, eng_noun:downcast{}, eng_noun:pneumatic{}, eng_noun:fluorescent{}, eng_noun:crank{}, eng_noun:executive{}, eng_noun:heterocyclic{}, eng_noun:cantheist{}, eng_noun:horrible{}, eng_noun:wrath{}, eng_noun:oxytocic{}, eng_noun:stimulant{}, eng_noun:flocculent{}, eng_noun:triskaidekaphobic{}, eng_noun:deadweight{}, eng_noun:warm - up{}, eng_noun:slap - back{}, eng_noun:tactic{}, eng_noun:Hindu{}, eng_noun:wayside{}, eng_noun:droll{}, eng_noun:Victorian{}, eng_noun:Marxist{}, eng_noun:flank{}, eng_noun:utile{}, eng_noun:Urartian{}, eng_noun:underneath{}, eng_noun:craven{}, eng_noun:pedal{}, eng_noun:ormolu{}, eng_noun:Cryogenian{}, eng_noun:blockbuster{}, eng_noun:convalescent{}, eng_noun:specialist{}, eng_noun:labiate{}, eng_noun:anhedral{}, eng_noun:virid{}, eng_noun:cerulean{}, eng_noun:celadon{}, eng_noun:buckskin{}, eng_noun:butterscotch{}, eng_noun:cinereous{}, eng_noun:citrine{}, eng_noun:dirigible{}, eng_noun:antiseptic{}, eng_noun:stammel{}, eng_noun:subfusc{}, eng_noun:terra - cotta{}, eng_noun:amaranthine{}, eng_noun:breakthrough{}, eng_noun:measurable{}, eng_noun:Brythonic{}, eng_noun:purpure{}, eng_noun:polysyllabic{}, eng_noun:detergent{}, eng_noun:Aztec{}, eng_noun:Cantonese{}, eng_noun:Maltese{}, eng_noun:Walachian{}, eng_noun:navicular{}, eng_noun:triquetral{}, eng_noun:mickle{}, eng_noun:Taoist{}, eng_noun:prognostic{}, eng_noun:Eurosceptic{}, eng_noun:stalwart{}, eng_noun:getaway{}, eng_noun:lapidary{}, eng_noun:mendicant{}, eng_noun:retrofit{}, eng_noun:dissident{}, eng_noun:anticonvulsant{}, eng_noun:Blairite{}, eng_noun:expedient{}, eng_noun:pyrotic{}, eng_noun:relict{}, eng_noun:Canuck{}, eng_noun:troy{}, eng_noun:Cajun{}, eng_noun:delectable{}, eng_noun:docent{}, eng_noun:neoteric{}, eng_noun:burlesque{}, eng_noun:malfeasant{}, eng_noun:elegiac{}, eng_noun:chickenshit{}, eng_noun:mystic{}, eng_noun:charismatic{}, eng_noun:composite{}, eng_noun:extremist{}, eng_noun:antistatic{}, eng_noun:recyclable{}, eng_noun:plug - in{}, eng_noun:agrarian{}, eng_noun:tetraploid{}, eng_noun:gammy{}, eng_noun:cheapo{}, eng_noun:trendy{}, eng_noun:bootleg{}, eng_noun:protozoan{}, eng_noun:damson{}, eng_noun:spartan{}, eng_noun:hammy{}, eng_noun:essive{}, eng_noun:yachty{}, eng_noun:topiary{}, eng_noun:unwonted{}, eng_noun:unpredictable{}, eng_noun:Tridentine{}, eng_noun:monochrome{}, eng_noun:mosaic{}, eng_noun:chinky{}, eng_noun:coloratura{}, eng_noun:epidural{}, eng_noun:resultant{}, eng_noun:consumptive{}, eng_noun:sedative{}, eng_noun:initiative{}, eng_noun:carbolic{}, eng_noun:underarm{}, eng_noun:heteroclitic{}, eng_noun:quadruplicate{}, eng_noun:Dalmatian{}, eng_noun:obsidian{}, eng_noun:Ossetian{}, eng_noun:vermillion{}, eng_noun:parenthetical{}, eng_noun:epispastic{}, eng_noun:midcareer{}, eng_noun:peg - leg{}, eng_noun:perfecto{}, eng_noun:mignon{}, eng_noun:incomparable{}, eng_noun:hourly{}, eng_noun:irreducible{}, eng_noun:chauvinist{}, eng_noun:downslope{}, eng_noun:Mycenaean{}, eng_noun:retentive{}, eng_noun:seltzer{}, eng_noun:pincer{}, eng_noun:decillionth{}, eng_noun:zillionth{}, eng_noun:excommunicate{}, eng_noun:stirrup{}, eng_noun:goldy{}, eng_noun:Assyrian{}, eng_noun:drinkable{}, eng_noun:fallback{}, eng_noun:chipper{}, eng_noun:implosive{}, eng_noun:psychotomimetic{}, eng_noun:intoxicant{}, eng_noun:vermeil{}, eng_noun:imperfective{}, eng_noun:fremd{}, eng_noun:cayenne{}, eng_noun:juridical{}, eng_noun:marriageable{}, eng_noun:Straussian{}, eng_noun:Bashkir{}, eng_noun:solitaire{}, eng_noun:downstage{}, eng_noun:mortuary{}, eng_noun:ferroelectric{}, eng_noun:mair{}, eng_noun:outbound{}, eng_noun:valedictory{}, eng_noun:larrikin{}, eng_noun:panzoist{}, eng_noun:Vegliote{}, eng_noun:extrusive{}, eng_noun:hymeneal{}, eng_noun:visitant{}, eng_noun:multiracial{}, eng_noun:polymorphonuclear{}, eng_noun:swidden{}, eng_noun:sensationalist{}, eng_noun:Newfie{}, eng_noun:nonacid{}, eng_noun:parabolic{}, eng_noun:jumbo{}, eng_noun:dolichocephalic{}, eng_noun:roborant{}, eng_noun:beat - up{}, eng_noun:zebrine{}, eng_noun:hypnotizable{}, eng_noun:lenticular{}, eng_noun:Thessalonian{}, eng_noun:coequal{}, eng_noun:sourdough{}, eng_noun:instructional{}, eng_noun:sit - down{}, eng_noun:communicant{}, eng_noun:sequent{}, eng_noun:constructionist{}, eng_noun:Atlantean{}, eng_noun:Mende{}, eng_noun:infective{}, eng_noun:polysilicon{}, eng_noun:unperceptive{}, eng_noun:unknowable{}, eng_noun:Reichian{}, eng_noun:undefeatable{}, eng_noun:miz{}, eng_noun:globalist{}, eng_noun:unsuspicious{}, eng_noun:metatherian{}, eng_noun:Mazanderani{}, eng_noun:Mccarthyite{}, eng_noun:horseflesh{}, eng_noun:extern{}, eng_noun:patch - up{}, eng_noun:Chinggisid{}, eng_noun:dactylic{}, eng_noun:outstation{}, eng_noun:Islamofascist{}, eng_noun:Kymric{}, eng_noun:intrastate{}, eng_noun:Confucian{}, eng_noun:incommensurable{}, eng_noun:arachnoid{}, eng_noun:dogtrot{}, eng_noun:downbeat{}, eng_noun:ticky - tacky{}, eng_noun:newsy{}, eng_noun:Ligurian{}, eng_noun:nonacademic{}, eng_noun:antiretroviral{}, eng_noun:alternant{}, eng_noun:postnoun{}, eng_noun:Pelasgian{}, eng_noun:subtonic{}, eng_noun:affluential{}, eng_noun:upstyle{}, eng_noun:down - style{}, eng_noun:unionist{}, eng_noun:globoid{}, eng_noun:Appalachian{}, eng_noun:graminoid{}, eng_noun:slam - bang{}, eng_noun:splittist{}, eng_noun:levirate{}, eng_noun:Japonica{}, eng_noun:noncriminal{}, eng_noun:Washingtonian{}, eng_noun:haplodiploid{}, eng_noun:nonintellectual{}, eng_noun:keene{}, eng_noun:Scythian{}, eng_noun:conductant{}, eng_noun:administrant{}, eng_noun:omphaloskeptic{}, eng_noun:binational{}, eng_noun:omnilingual{}, eng_noun:aminoethyl{}, eng_noun:Europan{}, eng_noun:meshuggener{}, eng_noun:Carian{}, eng_noun:Czechoslovak{}, eng_noun:phytopharmaceutical{}, eng_noun:bedrel{}, eng_noun:nonprotein{}, eng_noun:sympathomimetic{}, eng_noun:microphase{}, eng_noun:antihemorrhagic{}, eng_noun:antirachitic{}, eng_noun:rejectionist{}, eng_noun:verdictive{}, eng_noun:shortcrust{}, eng_noun:Labradorian{}, eng_noun:coin - op{}, eng_noun:Dagestani{}, eng_noun:intersex{}, eng_noun:tricuspid{}, eng_noun:paintery{}, eng_noun:antilithic{}, eng_noun:constitutionalist{}, eng_noun:amphiprostyle{}, eng_noun:Stuckist{}, eng_noun:pedophiliac{}, eng_noun:therian{}, eng_noun:Piscean{}, eng_noun:Libran{}, eng_noun:lepetodrilid{}, eng_noun:nuchal{}, eng_noun:melony{}, eng_noun:aquaholic{}, eng_noun:rectosigmoid{}, eng_noun:Guadeloupian{}, eng_noun:supralittoral{}, eng_noun:postcapillary{}, eng_noun:yogist{}, eng_noun:unergative{}, eng_noun:Camun{}, eng_noun:nondiabetic{}, eng_noun:nonstate{}, eng_noun:Tanganyikan{}, eng_noun:tetradactyl{}, eng_noun:Genoan{}, eng_noun:nonroyal{}, eng_noun:counterterrorist{}, eng_noun:Magdeburgian{}, eng_noun:auteurist{}, eng_noun:galliform{}, eng_noun:nondurable{}, eng_noun:externalist{}, eng_noun:sortal{}, eng_noun:multitouch{}, eng_noun:photorealist{}, eng_noun:midmarket{}, eng_noun:paternalist{}, eng_noun:postadolescent{}, eng_noun:autosexual{}, eng_noun:prestimulation{}, eng_noun:aliterate{}, eng_noun:cyberian{}, eng_noun:noncountry{}, eng_noun:intermorph{}, eng_noun:reassortant{}, eng_noun:quinoid{}, eng_noun:gastrokinetic{}, eng_noun:Martiniquan{}, eng_noun:antihyperglycemic{}, eng_noun:midgame{}, eng_noun:Pequiste{}, eng_noun:nonrelative{}, eng_noun:habiline{}, eng_noun:nonasthmatic{}, eng_noun:nonmortal{}, eng_noun:selachian{}, eng_noun:Varsovian{}, eng_noun:Budapestian{}, eng_noun:Lisboner{}, eng_noun:Tallinner{}, eng_noun:elevenish{}, eng_noun:Medinan{}, eng_noun:Megrelian{}, eng_noun:Sabean{}, eng_noun:lemuroid{}, eng_noun:oolitic{}, eng_noun:Sahelian{}, eng_noun:forprofit{}, eng_noun:Katangese{}, eng_noun:farmaceutical{}, eng_noun:multiduplex{}, eng_noun:shelly{}, eng_noun:cocktailian{}, eng_noun:biomusical{}, eng_noun:Ordophone{}, eng_noun:anti - christian{}, eng_noun:Zapotecan{}, eng_noun:nonserial{}, eng_noun:Brutalist{}, eng_noun:uniglot{}, eng_noun:nonheterosexual{}, eng_noun:noninjury{}, eng_noun:nonnovel{}, eng_noun:Transcaucasian{}, eng_noun:Medean{}, eng_noun:nonpolynomial{}, eng_noun:Pompeiian{}, eng_noun:nonpsychic{}, eng_noun:noncompound{}, eng_noun:Londonian{}, eng_noun:noncrystal{}, eng_noun:algebroid{}, eng_noun:operculate{}, eng_noun:ablutophiliac{}, eng_noun:shortfin{}, eng_noun:nonliberal{}, eng_noun:Calmuck{}, eng_noun:superinvariant{}, eng_noun:equant{}, eng_noun:predoc{}, eng_noun:lumbricine{}, eng_noun:tabanid{}, eng_noun:multiskyrmion{}, eng_noun:conditionate{}, eng_noun:Manichee{}, eng_noun:Shimerian{}, eng_noun:stipendiary{}, eng_noun:postcommunist{}, eng_noun:Antiochan{}, eng_noun:Hartlepudlian{}, eng_noun:nonresistor{}, eng_noun:hydatoid{}, eng_noun:epinician{}, eng_noun:hyperepidemic{}, eng_noun:mid - season{}, eng_noun:outland{}, eng_noun:anticonvulsive{}, eng_noun:acoelomate{}, eng_noun:misocapnist{}, eng_noun:Torontarian{}, eng_noun:Cabindan{}, eng_noun:theocratical{}, eng_noun:Pannonian{}, eng_noun:Sogdian{}, eng_noun:unthrift{}, eng_noun:Barcelonan{}, eng_noun:Navarran{}, eng_noun:feudalist{}, eng_noun:Paracelsian{}, eng_noun:nibbly{}, eng_noun:Wykehamist{}, eng_noun:perlative{}, eng_noun:umbratile{}, eng_noun:Oviedan{}, eng_noun:cybertopian{}, eng_noun:nonretirement{}, eng_noun:Palamite{}, eng_noun:neosocialist{}, eng_noun:suprematist{}, eng_noun:culturist{}, eng_noun:homeful{}, eng_noun:nonroyalty{}, eng_noun:Wessexian{}, eng_noun:Jugoslavian{}, eng_noun:Idumean{}, eng_noun:psychoneurotic{}, eng_noun:zoantharian{}, eng_noun:Butlerian{}, eng_noun:whity{}, eng_noun:polyodont{}, eng_noun:dicty{}, eng_noun:nongroup{}, eng_noun:acting{}, eng_noun:striking{}, eng_noun:taking{}, eng_noun:piping{}, eng_noun:bleeding{}, eng_noun:boding{}, eng_noun:ageing{}, eng_noun:youngling{}, eng_noun:bitter{}, eng_noun:head{}, eng_noun:abortifacient{}, eng_noun:accessary{}, eng_noun:plural{}, eng_noun:autumn{}, eng_noun:Polish{}, eng_noun:zero{}, eng_noun:Irish{}, eng_noun:Mexican{}, eng_noun:Spanish{}, eng_noun:absorbent{}, eng_noun:Afghan{}, eng_noun:dilettante{}, eng_noun:henna{}, eng_noun:cherry{}, eng_noun:mauve{}, eng_noun:edible{}, eng_noun:Hawaiian{}, eng_noun:Zuni{}, eng_noun:Hebrew{}, eng_noun:square{}, eng_noun:myriad{}, eng_noun:adjunct{}, eng_noun:concrete{}, eng_noun:neuter{}, eng_noun:west{}, eng_noun:ordinate{}, eng_noun:northwest{}, eng_noun:cyan{}, eng_noun:gun{}, eng_noun:cinnamon{}, eng_noun:melancholy{}, eng_noun:Adelaidean{}, eng_noun:polycystid{}, eng_noun:adherent{}, eng_noun:graduate{}, eng_noun:business{}, eng_noun:contemporary{}, eng_noun:wildcat{}, eng_noun:dairy{}, eng_noun:expletive{}, eng_noun:dead{}, eng_noun:dull{}, eng_noun:crown{}, eng_noun:feminine{}, eng_noun:clutch{}, eng_noun:kin{}, eng_noun:homosexual{}, eng_noun:Cypriot{}, eng_noun:Emirian{}, eng_noun:Antiguan{}, eng_noun:Antillean{}, eng_noun:obsessive{}, eng_noun:garden{}, eng_noun:paper{}, eng_noun:oddball{}, eng_noun:damp{}, eng_noun:neon{}, eng_noun:platinum{}, eng_noun:Scandinavian{}, eng_noun:gut{}, eng_noun:Achaean{}, eng_noun:minion{}, eng_noun:vegetarian{}, eng_noun:Tagalog{}, eng_noun:flammable{}, eng_noun:acute{}, eng_noun:cross{}, eng_noun:Botswanan{}, eng_noun:Nigerian{}, eng_noun:lesbian{}, eng_noun:Honduran{}, eng_noun:Guamanian{}, eng_noun:Guyanese{}, eng_noun:Syrian{}, eng_noun:Tajik{}, eng_noun:Surinamese{}, eng_noun:Lao{}, eng_noun:Magnesian{}, eng_noun:Nicaraguan{}, eng_noun:Tanzanian{}, eng_noun:Wallachian{}, eng_noun:mushroom{}, eng_noun:biennial{}, eng_noun:occult{}, eng_noun:castrato{}, eng_noun:wheat{}, eng_noun:minor{}, eng_noun:Francophone{}, eng_noun:pretty{}, eng_noun:puce{}, eng_noun:annual{}, eng_noun:Urdu{}, eng_noun:rad{}, eng_noun:similar{}, eng_noun:arch{}, eng_noun:diagonal{}, eng_noun:jelly{}, eng_noun:largo{}, eng_noun:snug{}, eng_noun:hardy{}, eng_noun:skinny{}, eng_noun:amiss{}, eng_noun:clairvoyant{}, eng_noun:brilliant{}, eng_noun:antiquarian{}, eng_noun:anosmic{}, eng_noun:bastard{}, eng_noun:bubbly{}, eng_noun:average{}, eng_noun:venti{}, eng_noun:inverse{}, eng_noun:poly{}, eng_noun:shithouse{}, eng_noun:cesarean{}, eng_noun:Keynesian{}, eng_noun:senior{}, eng_noun:analogue{}, eng_noun:celibate{}, eng_noun:offbeat{}, eng_noun:fou{}, eng_noun:equine{}, eng_noun:positive{}, eng_noun:belligerent{}, eng_noun:part{}, eng_noun:avocative{}, eng_noun:turnkey{}, eng_noun:apostate{}, eng_noun:patronymic{}, eng_noun:granny{}, eng_noun:amphibian{}, eng_noun:Shakespearean{}, eng_noun:pocket{}, eng_noun:resident{}, eng_noun:Livonian{}, eng_noun:immortal{}, eng_noun:makeshift{}, eng_noun:material{}, eng_noun:dyslexic{}, eng_noun:orphan{}, eng_noun:eagre{}, eng_noun:colic{}, eng_noun:Norman{}, eng_noun:nasal{}, eng_noun:tantamount{}, eng_noun:Islamite{}, eng_noun:inferior{}, eng_noun:pandemic{}, eng_noun:beloved{}, eng_noun:epoxy{}, eng_noun:macho{}, eng_noun:plumb{}, eng_noun:slurry{}, eng_noun:bridal{}, eng_noun:circumstantial{}, eng_noun:eager{}, eng_noun:expatriate{}, eng_noun:liege{}, eng_noun:mignonette{}, eng_noun:skimp{}, eng_noun:slack{}, eng_noun:tally{}, eng_noun:unicellular{}, eng_noun:vassal{}, eng_noun:trip{}, eng_noun:corrosive{}, eng_noun:lastborn{}, eng_noun:international{}, eng_noun:derelict{}, eng_noun:aspirate{}, eng_noun:retractable{}, eng_noun:legion{}, eng_noun:Bajan{}, eng_noun:sissy{}, eng_noun:mid - may{}, eng_noun:mid - autumn{}, eng_noun:hepatic{}, eng_noun:cathartic{}, eng_noun:addictive{}, eng_noun:fairytale{}, eng_noun:innocent{}, eng_noun:metacarpal{}, eng_noun:opaque{}, eng_noun:grotesque{}, eng_noun:noble{}, eng_noun:equestrian{}, eng_noun:Ilokano{}, eng_noun:everyday{}, eng_noun:specific{}, eng_noun:Syriac{}, eng_noun:western{}, eng_noun:circumflex{}, eng_noun:bomber{}, eng_noun:household{}, eng_noun:defensive{}, eng_noun:portable{}, eng_noun:atypical{}, eng_noun:phantom{}, eng_noun:illegal{}, eng_noun:centenarian{}, eng_noun:Ulster{}, eng_noun:multiple{}, eng_noun:gross{}, eng_noun:oatmeal{}, eng_noun:helter - skelter{}, eng_noun:furry{}, eng_noun:heteroclite{}, eng_noun:intangible{}, eng_noun:canine{}, eng_noun:gutter{}, eng_noun:inner{}, eng_noun:coy{}, eng_noun:angiosperm{}, eng_noun:greeny{}, eng_noun:menial{}, eng_noun:melancholic{}, eng_noun:cripple{}, eng_noun:contraband{}, eng_noun:suave{}, eng_noun:influential{}, eng_noun:duplicate{}, eng_noun:colonial{}, eng_noun:coeval{}, eng_noun:conspecific{}, eng_noun:heterospecific{}, eng_noun:chordate{}, eng_noun:gradual{}, eng_noun:vinyl{}, eng_noun:vitreous{}, eng_noun:stannary{}, eng_noun:moldy{}, eng_noun:peekaboo{}, eng_noun:morning - after{}, eng_noun:germanophone{}, eng_noun:lax{}, eng_noun:monosyllabic{}, eng_noun:perse{}, eng_noun:meta{}, eng_noun:sable{}, eng_noun:digitigrade{}, eng_noun:transorbital{}, eng_noun:Hadean{}, eng_noun:Ectasian{}, eng_noun:Cisuralian{}, eng_noun:deodorant{}, eng_noun:lightweight{}, eng_noun:sexagenarian{}, eng_noun:Serb{}, eng_noun:cornsilk{}, eng_noun:rustic{}, eng_noun:heather{}, eng_noun:honeydew{}, eng_noun:incarnadine{}, eng_noun:malachite{}, eng_noun:hairpin{}, eng_noun:intermediate{}, eng_noun:monotreme{}, eng_noun:cuboid{}, eng_noun:metatarsal{}, eng_noun:Ewe{}, eng_noun:Grit{}, eng_noun:Kiwi{}, eng_noun:Samaritan{}, eng_noun:bonny{}, eng_noun:sesamoid{}, eng_noun:kneejerk{}, eng_noun:refractory{}, eng_noun:lowdown{}, eng_noun:antibiotic{}, eng_noun:Paleolithic{}, eng_noun:breakaway{}, eng_noun:povvo{}, eng_noun:leftover{}, eng_noun:Neptunian{}, eng_noun:antiknock{}, eng_noun:GI{}, eng_noun:Jovian{}, eng_noun:smartass{}, eng_noun:antivivisectionist{}, eng_noun:bohemian{}, eng_noun:midi{}, eng_noun:schemie{}, eng_noun:antichristian{}, eng_noun:pineal{}, eng_noun:lymphatic{}, eng_noun:collective{}, eng_noun:aspirational{}, eng_noun:fribble{}, eng_noun:anaesthetic{}, eng_noun:haploid{}, eng_noun:Devanagari{}, eng_noun:effluent{}, eng_noun:cozy{}, eng_noun:receivable{}, eng_noun:Haligonian{}, eng_noun:tricolpate{}, eng_noun:freelance{}, eng_noun:luke{}, eng_noun:antiparallel{}, eng_noun:directional{}, eng_noun:distaff{}, eng_noun:antiarrhythmic{}, eng_noun:requisite{}, eng_noun:antitrust{}, eng_noun:reactionary{}, eng_noun:dapple{}, eng_noun:reflex{}, eng_noun:Baptist{}, eng_noun:jet - black{}, eng_noun:Aleut{}, eng_noun:equinoctial{}, eng_noun:baptismal{}, eng_noun:antimissile{}, eng_noun:linden{}, eng_noun:Lycian{}, eng_noun:humanitarian{}, eng_noun:hickory{}, eng_noun:diametral{}, eng_noun:moony{}, eng_noun:intercostal{}, eng_noun:abessive{}, eng_noun:Hessian{}, eng_noun:needful{}, eng_noun:Aleutian{}, eng_noun:ensuite{}, eng_noun:dodecyl{}, eng_noun:incumbent{}, eng_noun:cycloplegic{}, eng_noun:depressive{}, eng_noun:glassy{}, eng_noun:bijou{}, eng_noun:hyperborean{}, eng_noun:Laodicean{}, eng_noun:inboard{}, eng_noun:diehard{}, eng_noun:trillionth{}, eng_noun:Tyrolean{}, eng_noun:cricoid{}, eng_noun:lusk{}, eng_noun:ponent{}, eng_noun:postpositive{}, eng_noun:Carolingian{}, eng_noun:riverside{}, eng_noun:denominative{}, eng_noun:cinderblock{}, eng_noun:saltwater{}, eng_noun:ptarmic{}, eng_noun:equilateral{}, eng_noun:prohibitive{}, eng_noun:Beotian{}, eng_noun:paisley{}, eng_noun:bolshie{}, eng_noun:polyacoustic{}, eng_noun:lardy{}, eng_noun:polybromide{}, eng_noun:saurian{}, eng_noun:ack - ack{}, eng_noun:anthelmintic{}, eng_noun:sav{}, eng_noun:lesbigay{}, eng_noun:Montenegrin{}, eng_noun:carminative{}, eng_noun:suction{}, eng_noun:Oceanian{}, eng_noun:northerly{}, eng_noun:suicidal{}, eng_noun:spiritualist{}, eng_noun:co - ordinate{}, eng_noun:pitmatic{}, eng_noun:nanoscale{}, eng_noun:adoptionist{}, eng_noun:athel{}, eng_noun:virginal{}, eng_noun:Tokyoite{}, eng_noun:Galwegian{}, eng_noun:wussy{}, eng_noun:claustrophobic{}, eng_noun:neanderthal{}, eng_noun:water - repellent{}, eng_noun:denary{}, eng_noun:Sudovian{}, eng_noun:confederationist{}, eng_noun:wrinkly{}, eng_noun:two - piece{}, eng_noun:Hindoo{}, eng_noun:sackful{}, eng_noun:helminthic{}, eng_noun:Earthican{}, eng_noun:tabletop{}, eng_noun:unpalatable{}, eng_noun:mitigant{}, eng_noun:apotreptic{}, eng_noun:darnedest{}, eng_noun:untouchable{}, eng_noun:hooky{}, eng_noun:intersexual{}, eng_noun:subnormal{}, eng_noun:uninsured{}, eng_noun:monoploid{}, eng_noun:glenoid{}, eng_noun:Australopithecine{}, eng_noun:opioid{}, eng_noun:purist{}, eng_noun:codependent{}, eng_noun:Umbrian{}, eng_noun:semipro{}, eng_noun:gentilic{}, eng_noun:multiplicative{}, eng_noun:falsificationist{}, eng_noun:nonreproductive{}, eng_noun:Miztec{}, eng_noun:hugger - mugger{}, eng_noun:lactovegetarian{}, eng_noun:molariform{}, eng_noun:Druze{}, eng_noun:ataractic{}, eng_noun:polypharmaceutical{}, eng_noun:cheapjack{}, eng_noun:manufactory{}, eng_noun:extractive{}, eng_noun:coliform{}, eng_noun:pendent{}, eng_noun:unregenerate{}, eng_noun:quickset{}, eng_noun:properispomenon{}, eng_noun:genderqueer{}, eng_noun:Acheulian{}, eng_noun:precognitive{}, eng_noun:throwaway{}, eng_noun:optoelectronic{}, eng_noun:watchet{}, eng_noun:Transnistrian{}, eng_noun:cryptofascist{}, eng_noun:Pohnpeian{}, eng_noun:preflight{}, eng_noun:purty{}, eng_noun:ragtag{}, eng_noun:Filipina{}, eng_noun:Sicanian{}, eng_noun:Dundonian{}, eng_noun:decapod{}, eng_noun:tip - top{}, eng_noun:hyracoid{}, eng_noun:daimonic{}, eng_noun:protostomian{}, eng_noun:proturan{}, eng_noun:psittacosaurid{}, eng_noun:pteropod{}, eng_noun:Pueblan{}, eng_noun:organofluorine{}, eng_noun:nonwhite{}, eng_noun:preorder{}, eng_noun:criss - cross{}, eng_noun:cyprinid{}, eng_noun:invasionist{}, eng_noun:nonnative{}, eng_noun:cholesteric{}, eng_noun:cepheid{}, eng_noun:bughouse{}, eng_noun:catawampus{}, eng_noun:mammillary{}, eng_noun:sarcoid{}, eng_noun:hypergeometric{}, eng_noun:Cantabrigian{}, eng_noun:murrion{}, eng_noun:cheveril{}, eng_noun:split - squad{}, eng_noun:pharmaceutic{}, eng_noun:aminomethoxy{}, eng_noun:nitroaromatic{}, eng_noun:Nassuvian{}, eng_noun:carriable{}, eng_noun:sinusoid{}, eng_noun:nonbiodegradable{}, eng_noun:proteinomimetic{}, eng_noun:untime{}, eng_noun:salientian{}, eng_noun:Nietzschean{}, eng_noun:Venizelist{}, eng_noun:univariate{}, eng_noun:Reginan{}, eng_noun:edentate{}, eng_noun:Mordvinian{}, eng_noun:Buryat{}, eng_noun:Udmurtian{}, eng_noun:polynemid{}, eng_noun:megapode{}, eng_noun:duoplural{}, eng_noun:xerophytic{}, eng_noun:Cumbrian{}, eng_noun:Salopian{}, eng_noun:unicursal{}, eng_noun:Montanan{}, eng_noun:prostyle{}, eng_noun:Xaverian{}, eng_noun:hemichordate{}, eng_noun:Sagittarian{}, eng_noun:scombrid{}, eng_noun:thyasirid{}, eng_noun:virostatic{}, eng_noun:musculotropic{}, eng_noun:Catalonian{}, eng_noun:disphenoid{}, eng_noun:hobohemian{}, eng_noun:Argentinean{}, eng_noun:technoutopian{}, eng_noun:allotetraploid{}, eng_noun:practic{}, eng_noun:Illinoisan{}, eng_noun:cartilaginoid{}, eng_noun:diamante{}, eng_noun:beachside{}, eng_noun:depositary{}, eng_noun:nonbank{}, eng_noun:mucolytic{}, eng_noun:didacticist{}, eng_noun:institutionalist{}, eng_noun:umbre{}, eng_noun:Jansenist{}, eng_noun:Savonian{}, eng_noun:Madagascarian{}, eng_noun:Madeiran{}, eng_noun:ticky{}, eng_noun:knockabout{}, eng_noun:curbside{}, eng_noun:postfeminist{}, eng_noun:indolic{}, eng_noun:unilateralist{}, eng_noun:tephritid{}, eng_noun:cardio{}, eng_noun:boine{}, eng_noun:prestart{}, eng_noun:internalist{}, eng_noun:primitivist{}, eng_noun:Baconian{}, eng_noun:midtempo{}, eng_noun:Seljuk{}, eng_noun:dualist{}, eng_noun:inferentialist{}, eng_noun:Malabarian{}, eng_noun:midmeal{}, eng_noun:superheavyweight{}, eng_noun:anti - rad{}, eng_noun:sexcentenary{}, eng_noun:anticholesterol{}, eng_noun:functionless{}, eng_noun:corsive{}, eng_noun:Marcosian{}, eng_noun:venitive{}, eng_noun:hemiplegic{}, eng_noun:jaden{}, eng_noun:dispensationalist{}, eng_noun:Helsinkian{}, eng_noun:Seoulite{}, eng_noun:beardy{}, eng_noun:zalambdodont{}, eng_noun:misotheist{}, eng_noun:Bahian{}, eng_noun:valgus{}, eng_noun:antepaenultimate{}, eng_noun:latitudinarian{}, eng_noun:albuminoid{}, eng_noun:eclecticist{}, eng_noun:nonprimitive{}, eng_noun:antidemocracy{}, eng_noun:antimonial{}, eng_noun:calmative{}, eng_noun:deadeye{}, eng_noun:prefeminism{}, eng_noun:slipover{}, eng_noun:prototherian{}, eng_noun:quadrumane{}, eng_noun:agnathan{}, eng_noun:speciest{}, eng_noun:syrphid{}, eng_noun:nonanxiety{}, eng_noun:Pawnee{}, eng_noun:subharmonic{}, eng_noun:Zambezian{}, eng_noun:feodatory{}, eng_noun:antiasthmatic{}, eng_noun:bifundamental{}, eng_noun:interarrival{}, eng_noun:litho{}, eng_noun:subfilter{}, eng_noun:bimillenary{}, eng_noun:Arietian{}, eng_noun:beavery{}, eng_noun:declensionist{}, eng_noun:overdede{}, eng_noun:comprovincial{}, eng_noun:nonmarxist{}, eng_noun:gymnic{}, eng_noun:Nisibene{}, eng_noun:Antiochene{}, eng_noun:fielden{}, eng_noun:Ruritanian{}, eng_noun:Muscatian{}, eng_noun:nonelitist{}, eng_noun:thalline{}, eng_noun:sternocleidomastoid{}, eng_noun:Catalanophile{}, eng_noun:blinky{}, eng_noun:nontime{}, eng_noun:cubital{}, eng_noun:specky{}, eng_noun:Raelian{}, eng_noun:antistrange{}, eng_noun:selenodont{}, eng_noun:dropside{}, eng_noun:lapidarian{}, eng_noun:antisexist{}, eng_noun:anticonsumer{}, eng_noun:antiluetic{}, eng_noun:Seljuq{}, eng_noun:cheapie{}, eng_noun:Maxwellian{}, eng_noun:ecbolic{}, eng_noun:Kamchatkan{}, eng_noun:Amerasian{}, eng_noun:Hoisanese{}, eng_noun:Judaica{}, eng_noun:antifebrile{}, eng_noun:Flavian{}, eng_noun:Julio - claudian{}, eng_noun:offscum{}, eng_noun:mensk{}, eng_noun:coterminal{}, eng_noun:nonobservable{}, eng_noun:twissel{}, eng_noun:amenorrheic{}, eng_noun:ivorine{}, eng_noun:antialarmist{}, eng_noun:superiour{}, eng_noun:questuary{}, eng_noun:pneumoniac{}, eng_noun:antiegalitarian{}, eng_noun:Bloomfieldian{}, eng_noun:Kiriwinan{}, eng_noun:qued{}, eng_noun:asthmatick{}, eng_noun:diagnostick{}, eng_noun:ethick{}, eng_noun:cathartick{}, eng_noun:epispastick{}, eng_noun:vinny{}, eng_noun:sweetkin{}, eng_noun:roddy{}, eng_noun:podunk{}, eng_noun:Havanese{}, eng_noun:nasoturbinate{}, eng_noun:giaunt{}, eng_noun:lithotriptic{}, eng_noun:bodyswap{}, eng_noun:periotic{}, eng_noun:roughtail{}, eng_noun:experimentarian{}, eng_noun:Chaldaic{}, eng_noun:Transoxianan{}, eng_noun:postobservation{}, eng_noun:sphingine{}, eng_noun:frolick{}, eng_noun:ascetick{}, eng_noun:relaxative{}, eng_noun:anticriticism{}, eng_noun:antidotary{}, eng_noun:polystyle{}, eng_noun:antemetic{}, eng_noun:festucine{}, eng_noun:spring{}, eng_noun:fast{}, eng_noun:light{}, eng_noun:goose{}, eng_noun:broadloom{}, eng_noun:clamour{}, eng_noun:cleric{}, eng_noun:corollary{}, eng_noun:continuant{}, eng_noun:cranny{}, eng_noun:compound{}, eng_noun:durative{}, eng_noun:earthenware{}, eng_noun:exponent{}, eng_noun:emigrant{}, eng_noun:flagellant{}, eng_noun:folio{}, eng_noun:holograph{}, eng_noun:javanese{}, eng_noun:intermediary{}, eng_noun:interrogative{}, eng_noun:lakeside{}, eng_noun:livery{}, eng_noun:manifold{}, eng_noun:mongrel{}, eng_noun:monitory{}, eng_noun:monomial{}, eng_noun:matey{}, eng_noun:oolite{}, eng_noun:netherlander{}, eng_noun:myriapod{}, eng_noun:parnassian{}, eng_noun:prismoid{}, eng_noun:precious{}, eng_noun:quatercentenary{}, eng_noun:preservative{}, eng_noun:reflexive{}, eng_noun:refrigerant{}, eng_noun:slub{}, eng_noun:superintendent{}, eng_noun:surd{}, eng_noun:squab{}, eng_noun:swash{}, eng_noun:statuary{}, eng_noun:tylopod{}, eng_noun:unison{}, eng_noun:ultramarine{}, eng_noun:tunicate{}, eng_noun:transmigrant{}, eng_noun:albanian{}, eng_noun:blu - ray{}, eng_noun:gullah{}, eng_noun:samogitian{}, eng_noun:hedge{}, eng_noun:savory{}, eng_noun:indie{}, eng_noun:ortho{}, eng_noun:affine{}, eng_noun:probit{}, eng_noun:minute{}, eng_noun:presto{}, eng_noun:rawhide{}, eng_noun:retinal{}, eng_noun:earnest{}, eng_noun:maltose{}, eng_noun:kibbutz{}, eng_noun:emeritus{}, eng_noun:hatchback{}, eng_noun:preseason{}, eng_noun:greenfield{}, eng_noun:multiethnic{}, eng_noun:suppressant{}, eng_noun:quadriplegic{}, eng_noun:hypertensive{}, eng_noun:ornithischian{}, eng_noun:regal{}, eng_noun:missionary{}, eng_noun:endomorph{}, eng_noun:pendentive{}, eng_noun:comforter{}, eng_noun:fulness{}, eng_noun:legato{}, eng_noun:existent{}, eng_noun:longing{}, eng_noun:inebriate{}, eng_noun:yugoslavian{}, eng_noun:mean{}, eng_noun:highbrow{}, eng_noun:tarnation{}, eng_noun:beautification{}, eng_noun:sooth{}, eng_noun:Broadway{}, eng_noun:Aspergerian{}, eng_noun:recce{}, eng_noun:doppio{}, eng_noun:Chicano{}, eng_noun:Teflon{}, eng_noun:unreachable{}, eng_noun:quant{}, eng_noun:Avar{}, eng_noun:inspissant{}, eng_noun:Hurrian{}, eng_noun:Mestee{}, eng_noun:incombustible{}, eng_noun:stainless{}, eng_noun:secessionist{}, eng_noun:jacquard{}, eng_noun:reformatory{}, eng_noun:unaffected{}, eng_noun:Socratic{}, eng_noun:completist{}, eng_noun:antifeminist{}, eng_noun:complimentary{}, eng_noun:subtropical{}, eng_noun:Michigander{}, eng_noun:non - profit{}, eng_noun:whistle - stop{}, eng_noun:fairyland{}, eng_noun:uncommunicative{}, eng_noun:newlywed{}, eng_noun:jerkwater{}, eng_noun:phytochemical{}, eng_noun:teratoid{}, eng_noun:hysteric{}, eng_noun:flagellate{}, eng_noun:futanari{}, eng_noun:sympathizer{}, eng_noun:one - shot{}, eng_noun:polypod{}, eng_noun:Westphalian{}, eng_noun:bimetallist{}, eng_noun:deterrent{}, eng_noun:hair - trigger{}, eng_noun:uninjured{}, eng_noun:expressionist{}, eng_noun:neuroleptic{}, eng_noun:sandgrounder{}, eng_noun:dropdown{}, eng_noun:commemorative{}, eng_noun:comestible{}, eng_noun:delphine{}, eng_noun:somatroph{}, eng_noun:agentive{}, eng_noun:usufructuary{}, eng_noun:briny{}, eng_noun:opaline{}, eng_noun:recreant{}, eng_noun:cartooney{}, eng_noun:protectionist{}, eng_noun:objectivist{}, eng_noun:Circassian{}, eng_noun:unresponsive{}, eng_noun:nutzoid{}, eng_noun:invitational{}, eng_noun:tetradecimal{}, eng_noun:cosignatory{}, eng_noun:hexapod{}, eng_noun:instakill{}, eng_noun:streetcorner{}, eng_noun:polyfluoro{}, eng_noun:unprintable{}, eng_noun:classist{}, eng_noun:Rexist{}, eng_noun:tricorn{}, eng_noun:Laestrygonian{}, eng_noun:federalist{}, eng_noun:singalong{}, eng_noun:pachycaul{}, eng_noun:foldout{}, eng_noun:polyplacophore{}, eng_noun:Genevan{}, eng_noun:nonsectarian{}, eng_noun:hegemonist{}, eng_noun:declaratory{}, eng_noun:prelim{}, eng_noun:nutbar{}, eng_noun:drip - dry{}, eng_noun:Rhodian{}, eng_noun:Czechoslovakian{}, eng_noun:maxillary{}, eng_noun:Lapp{}, eng_noun:Anglo - american{}, eng_noun:roan{}, eng_noun:immunosuppressant{}, eng_noun:hermeneutic{}, eng_noun:quadral{}, eng_noun:metapodial{}, eng_noun:protoctistan{}, eng_noun:penitant{}, eng_noun:bandpass{}, eng_noun:Kantean{}, eng_noun:dirigist{}, eng_noun:incuse{}, eng_noun:liberticide{}, eng_noun:Zapotec{}, eng_noun:Kievan{}, eng_noun:Missourian{}, eng_noun:intercity{}, eng_noun:underfloor{}, eng_noun:antient{}, eng_noun:trimotor{}, eng_noun:intervenient{}, eng_noun:Anatolian{}, eng_noun:cestode{}, eng_noun:antitranspirant{}, eng_noun:alleviative{}, eng_noun:fav{}, eng_noun:pooer{}, eng_noun:aminomethyl{}, eng_noun:Jacobean{}, eng_noun:extinguishant{}, eng_noun:Mesopotamian{}, eng_noun:Lancastrian{}, eng_noun:nonchemical{}, eng_noun:antimuscarinic{}, eng_noun:biquadratic{}, eng_noun:sudorific{}, eng_noun:Euro - skeptic{}, eng_noun:prog{}, eng_noun:bowery{}, eng_noun:topgallant{}, eng_noun:coralline{}, eng_noun:bivariate{}, eng_noun:camelback{}, eng_noun:decrescent{}, eng_noun:excitant{}, eng_noun:Brayon{}, eng_noun:white - shoe{}, eng_noun:Ephesian{}, eng_noun:sheepy{}, eng_noun:Swati{}, eng_noun:oppugnant{}, eng_noun:Louisianian{}, eng_noun:nonterminal{}, eng_noun:Sacramentarian{}, eng_noun:glomalean{}, eng_noun:plathelminth{}, eng_noun:siboglinid{}, eng_noun:lissamphibian{}, eng_noun:sulphoaluminate{}, eng_noun:fastigiate{}, eng_noun:determinist{}, eng_noun:quincentenary{}, eng_noun:quadratojugal{}, eng_noun:Pitcairner{}, eng_noun:wah - wah{}, eng_noun:permeant{}, eng_noun:Istrian{}, eng_noun:prediagnosis{}, eng_noun:ingressive{}, eng_noun:patientive{}, eng_noun:anarcho - syndicalist{}, eng_noun:bayfront{}, eng_noun:wackadoo{}, eng_noun:superspecial{}, eng_noun:midrise{}, eng_noun:nonsecret{}, eng_noun:spectralist{}, eng_noun:nonsenior{}, eng_noun:communitarian{}, eng_noun:nonlocal{}, eng_noun:Maduran{}, eng_noun:ultraliberal{}, eng_noun:multidisciplinarian{}, eng_noun:nonstudent{}, eng_noun:parachordal{}, eng_noun:Sartrean{}, eng_noun:mainstage{}, eng_noun:eliminativist{}, eng_noun:bicoastal{}, eng_noun:nongame{}, eng_noun:biconditional{}, eng_noun:nonhistone{}, eng_noun:multistorey{}, eng_noun:sandbelt{}, eng_noun:interdune{}, eng_noun:antiracism{}, eng_noun:expressivist{}, eng_noun:immunoabsorbent{}, eng_noun:anticipant{}, eng_noun:postintegration{}, eng_noun:reductivist{}, eng_noun:midcalf{}, eng_noun:subadult{}, eng_noun:bolshy{}, eng_noun:antispasmatic{}, eng_noun:Manhattanite{}, eng_noun:lobstery{}, eng_noun:Springfieldian{}, eng_noun:betamimetic{}, eng_noun:Cincinnatian{}, eng_noun:Mascarene{}, eng_noun:assessorial{}, eng_noun:antigalactic{}, eng_noun:precapitalist{}, eng_noun:prestudy{}, eng_noun:nondepressive{}, eng_noun:antihelminthic{}, eng_noun:surform{}, eng_noun:Bratislavan{}, eng_noun:Delhian{}, eng_noun:nonmale{}, eng_noun:multitheist{}, eng_noun:Turkoman{}, eng_noun:Tajikistani{}, eng_noun:speciesist{}, eng_noun:Balaamite{}, eng_noun:nonanesthetic{}, eng_noun:anticestodal{}, eng_noun:hydrocholeretic{}, eng_noun:catastrophist{}, eng_noun:Antwerpian{}, eng_noun:post - apocalyptic{}, eng_noun:carryon{}, eng_noun:pracademic{}, eng_noun:jabberwocky{}, eng_noun:nonsedative{}, eng_noun:nonpollen{}, eng_noun:preinflation{}, eng_noun:anthro{}, eng_noun:selenomethionyl{}, eng_noun:nonceramic{}, eng_noun:ersatzist{}, eng_noun:nontangible{}, eng_noun:nonrevolutionary{}, eng_noun:nonvisionary{}, eng_noun:nonwestern{}, eng_noun:nonequalitarian{}, eng_noun:multigrade{}, eng_noun:nondrug{}, eng_noun:preprofessional{}, eng_noun:nonantique{}, eng_noun:nonedible{}, eng_noun:semiclassic{}, eng_noun:syrphian{}, eng_noun:palaeoconservative{}, eng_noun:macrorealist{}, eng_noun:rakehell{}, eng_noun:triggery{}, eng_noun:hepatotoxicant{}, eng_noun:Keresan{}, eng_noun:nontaxation{}, eng_noun:biflagellate{}, eng_noun:nonphobic{}, eng_noun:Hellenophile{}, eng_noun:Hibernophile{}, eng_noun:ghosty{}, eng_noun:viverrine{}, eng_noun:tipulid{}, eng_noun:Urartean{}, eng_noun:nonlabial{}, eng_noun:specieist{}, eng_noun:antimicrobic{}, eng_noun:multi - touch{}, eng_noun:megapolitan{}, eng_noun:Blackpudlian{}, eng_noun:Aostan{}, eng_noun:abortient{}, eng_noun:salmonoid{}, eng_noun:nongoal{}, eng_noun:winky{}, eng_noun:Nestorian{}, eng_noun:circumbendibus{}, eng_noun:nonrevisionist{}, eng_noun:mornay{}, eng_noun:serotine{}, eng_noun:interester{}, eng_noun:disestablishmentarian{}, eng_noun:exessive{}, eng_noun:antirevolutionary{}, eng_noun:unshrinkable{}, eng_noun:bardie{}, eng_noun:pure - bred{}, eng_noun:strippy{}, eng_noun:Azorean{}, eng_noun:Erasmian{}, eng_noun:oorie{}, eng_noun:Cappadocian{}, eng_noun:Saragossan{}, eng_noun:Malagan{}, eng_noun:Volscian{}, eng_noun:Callistan{}, eng_noun:lunary{}, eng_noun:pedosexual{}, eng_noun:Montessorian{}, eng_noun:non - paper{}, eng_noun:Tatarian{}, eng_noun:deltoideus{}, eng_noun:anticollectivist{}, eng_noun:deconstructivist{}, eng_noun:creekside{}, eng_noun:nonevangelical{}, eng_noun:cestoid{}, eng_noun:Rothbardian{}, eng_noun:Monrovian{}, eng_noun:Danubian{}, eng_noun:naticoid{}, eng_noun:labrish{}, eng_noun:quintate{}, eng_noun:sextate{}, eng_noun:miscome{}, eng_noun:antiallergenic{}, eng_noun:schizophreniac{}, eng_noun:productivist{}, eng_noun:academick{}, eng_noun:multicycle{}, eng_noun:specifick{}, eng_noun:prognostick{}, eng_noun:cynick{}, eng_noun:hypochondriack{}, eng_noun:macaronick{}, eng_noun:narcotick{}, eng_noun:nephritick{}, eng_noun:optick{}, eng_noun:patronymick{}, eng_noun:schismatick{}, eng_noun:Armorican{}, eng_noun:telepsychic{}, eng_noun:antizymotic{}, eng_noun:gremial{}, eng_noun:tingid{}, eng_noun:appurtenaunt{}, eng_noun:attendaunt{}, eng_noun:Ceylonese{}, eng_noun:mightand{}, eng_noun:Limenean{}, eng_noun:haustellate{}, eng_noun:deodourant{}, eng_noun:armourial{}, eng_noun:subterrany{}, eng_noun:interopercular{}, eng_noun:craftable{}, eng_noun:non - op{}, eng_noun:ctenoidean{}, eng_noun:evenold{}, eng_noun:left{}, eng_noun:stern{}, eng_noun:bicentenary{}, eng_noun:catoptric{}, eng_noun:caucasian{}, eng_noun:discontent{}, eng_noun:downhill{}, eng_noun:desert{}, eng_noun:decongestant{}, eng_noun:devonian{}, eng_noun:dialectic{}, eng_noun:ferroconcrete{}, eng_noun:fibroid{}, eng_noun:hardback{}, eng_noun:hotshot{}, eng_noun:jain{}, eng_noun:litigant{}, eng_noun:mod{}, eng_noun:patent{}, eng_noun:pet{}, eng_noun:paramilitary{}, eng_noun:pongid{}, eng_noun:pyknic{}, eng_noun:pyroelectric{}, eng_noun:ratite{}, eng_noun:recessional{}, eng_noun:roughcast{}, eng_noun:savoyard{}, eng_noun:sceptic{}, eng_noun:still{}, eng_noun:tantivy{}, eng_noun:terry{}, eng_noun:tetrastyle{}, eng_noun:thermophile{}, eng_noun:transgenic{}, eng_noun:auvergnese{}, eng_noun:koepanger{}, eng_noun:xian{}, eng_noun:nappy{}, eng_noun:armorial{}, eng_noun:excrescent{}, eng_noun:ware{}, eng_noun:sitfast{}, eng_noun:seater{}, eng_noun:uphill{}, eng_noun:upward{}, eng_noun:lookup{}, eng_noun:alumina{}, eng_noun:poverty{}, eng_noun:homebrew{}, eng_noun:disjunct{}, eng_noun:tailwheel{}, eng_noun:centennial{}, eng_noun:subordinate{}, eng_noun:buttery{}, eng_noun:afghani{}, eng_noun:round{}, eng_noun:cursive{}, eng_noun:pro{}, eng_noun:tender{}, eng_noun:rundown{}, eng_noun:ringworm{}, eng_noun:chiffon{}, eng_noun:malapert{}, eng_noun:brow{}, eng_noun:ruby{}, eng_noun:pizzicato{}, eng_noun:blanc{}, eng_noun:low{}, eng_noun:wikipedian{}, eng_noun:usonian{}, eng_noun:midterm{}, eng_noun:interlock{}, eng_noun:arachnid{}, eng_noun:auditory{}, eng_noun:gilt{}, eng_noun:closing{}, eng_noun:binding{}, eng_noun:cutting{}, eng_noun:filling{}, eng_noun:flowering{}, eng_noun:wandering{}, eng_noun:backing{}, eng_noun:walking{}, eng_noun:sightseeing{}, eng_noun:exhilarating{}, eng_noun:watering{}, eng_noun:raving{}, eng_noun:conjugate{}, eng_noun:content{}, eng_noun:overcast{}, eng_noun:standardbred{}, eng_noun:substantive{}, eng_noun:abirritant{}, eng_noun:abrasive{}, eng_noun:abrogate{}, eng_noun:birth{}, eng_noun:secret{}, eng_noun:standard{}, eng_noun:Catalan{}, eng_noun:banana{}, eng_noun:beige{}, eng_noun:violet{}, eng_noun:young{}, eng_noun:dative{}, eng_noun:superlative{}, eng_noun:southwest{}, eng_noun:quaint{}, eng_noun:female{}, eng_noun:tin{}, eng_noun:slate{}, eng_noun:vermilion{}, eng_noun:strawberry{}, eng_noun:lemon{}, eng_noun:safe{}, eng_noun:vernacular{}, eng_noun:gibberish{}, eng_noun:Canadian{}, eng_noun:Bulgarian{}, eng_noun:ilk{}, eng_noun:funeral{}, eng_noun:interior{}, eng_noun:bourgeois{}, eng_noun:vertebrate{}, eng_noun:sovereign{}, eng_noun:solid{}, eng_noun:smooth{}, eng_noun:celestial{}, eng_noun:ebb{}, eng_noun:Anguillan{}, eng_noun:Corsican{}, eng_noun:queer{}, eng_noun:nazi{}, eng_noun:void{}, eng_noun:Ashkenazi{}, eng_noun:arsenic{}, eng_noun:terminal{}, eng_noun:Persian{}, eng_noun:Philistine{}, eng_noun:laureate{}, eng_noun:laudative{}, eng_noun:acescent{}, eng_noun:wholesale{}, eng_noun:nice{}, eng_noun:primary{}, eng_noun:Aragonese{}, eng_noun:Belarusian{}, eng_noun:Sudanese{}, eng_noun:Palestinian{}, eng_noun:Kazakh{}, eng_noun:Burundian{}, eng_noun:Uruguayan{}, eng_noun:Vanuatuan{}, eng_noun:Malian{}, eng_noun:Turkmen{}, eng_noun:Namibian{}, eng_noun:Comorian{}, eng_noun:Viennese{}, eng_noun:Ghanaian{}, eng_noun:Laotian{}, eng_noun:Omani{}, eng_noun:Constantinopolitan{}, eng_noun:signal{}, eng_noun:ambisexual{}, eng_noun:Friulian{}, eng_noun:front{}, eng_noun:pirate{}, eng_noun:tricentennial{}, eng_noun:Bengali{}, eng_noun:Marathi{}, eng_noun:Sinhalese{}, eng_noun:trunk{}, eng_noun:series{}, eng_noun:anal{}, eng_noun:vain{}, eng_noun:marine{}, eng_noun:socialist{}, eng_noun:biannual{}, eng_noun:glottal{}, eng_noun:visionary{}, eng_noun:Polynesian{}, eng_noun:eutectic{}, eng_noun:alpine{}, eng_noun:amateur{}, eng_noun:private{}, eng_noun:Malay{}, eng_noun:heretic{}, eng_noun:choice{}, eng_noun:flatbed{}, eng_noun:Arminian{}, eng_noun:elastic{}, eng_noun:lieutenant{}, eng_noun:bottom{}, eng_noun:feral{}, eng_noun:shotgun{}, eng_noun:moderato{}, eng_noun:diminuendo{}, eng_noun:quicksilver{}, eng_noun:tenor{}, eng_noun:chivalrous{}, eng_noun:albino{}, eng_noun:boilerplate{}, eng_noun:Bosnian{}, eng_noun:elect{}, eng_noun:exclusive{}, eng_noun:gentile{}, eng_noun:octic{}, eng_noun:picayune{}, eng_noun:aculeate{}, eng_noun:agglutinant{}, eng_noun:Aventine{}, eng_noun:Paki{}, eng_noun:jammy{}, eng_noun:necessary{}, eng_noun:proof{}, eng_noun:halcyon{}, eng_noun:integral{}, eng_noun:mundane{}, eng_noun:fuzzy{}, eng_noun:floppy{}, eng_noun:immutable{}, eng_noun:Aryan{}, eng_noun:terrorist{}, eng_noun:mordant{}, eng_noun:straw{}, eng_noun:stereo{}, eng_noun:tattletale{}, eng_noun:Aramaic{}, eng_noun:Nepali{}, eng_noun:export{}, eng_noun:sport{}, eng_noun:insurgent{}, eng_noun:coronary{}, eng_noun:inflatable{}, eng_noun:damask{}, eng_noun:prodigal{}, eng_noun:passionate{}, eng_noun:amino{}, eng_noun:bawdy{}, eng_noun:chic{}, eng_noun:chuff{}, eng_noun:nubile{}, eng_noun:berserk{}, eng_noun:blithe{}, eng_noun:brute{}, eng_noun:canny{}, eng_noun:compulsory{}, eng_noun:elite{}, eng_noun:official{}, eng_noun:punk{}, eng_noun:scrimp{}, eng_noun:sleek{}, eng_noun:sleigh{}, eng_noun:solitary{}, eng_noun:stuffy{}, eng_noun:tentative{}, eng_noun:ingrate{}, eng_noun:bacchanal{}, eng_noun:Mancunian{}, eng_noun:suede{}, eng_noun:mid - september{}, eng_noun:mid - january{}, eng_noun:terrestrial{}, eng_noun:negative{}, eng_noun:invariant{}, eng_noun:equivalent{}, eng_noun:antitussive{}, eng_noun:charter{}, eng_noun:rum{}, eng_noun:skim{}, eng_noun:ungulate{}, eng_noun:octogenarian{}, eng_noun:zigzag{}, eng_noun:filk{}, eng_noun:premium{}, eng_noun:miscreant{}, eng_noun:subarctic{}, eng_noun:pansy{}, eng_noun:tertiary{}, eng_noun:pissant{}, eng_noun:randy{}, eng_noun:twin{}, eng_noun:pre - adamite{}, eng_noun:unconventional{}, eng_noun:maverick{}, eng_noun:acrocephalic{}, eng_noun:voluntary{}, eng_noun:Zionist{}, eng_noun:junky{}, eng_noun:ecstatic{}, eng_noun:polyester{}, eng_noun:oneirocritic{}, eng_noun:anodyne{}, eng_noun:inorganic{}, eng_noun:merry{}, eng_noun:prat{}, eng_noun:oxyacetylene{}, eng_noun:Chuvash{}, eng_noun:cactus{}, eng_noun:ascetic{}, eng_noun:Whovian{}, eng_noun:decubitis{}, eng_noun:varietal{}, eng_noun:tawny{}, eng_noun:backup{}, eng_noun:laxative{}, eng_noun:consistent{}, eng_noun:stopgap{}, eng_noun:veggie{}, eng_noun:incoherent{}, eng_noun:dependant{}, eng_noun:nightly{}, eng_noun:polyzoic{}, eng_noun:transitionist{}, eng_noun:profane{}, eng_noun:primo{}, eng_noun:identikit{}, eng_noun:legislative{}, eng_noun:crummy{}, eng_noun:creo{}, eng_noun:columnar{}, eng_noun:straightedge{}, eng_noun:hallucinogenic{}, eng_noun:deponent{}, eng_noun:danophone{}, eng_noun:convertible{}, eng_noun:budget{}, eng_noun:Guadalupian{}, eng_noun:Furongian{}, eng_noun:durable{}, eng_noun:slick{}, eng_noun:burgundy{}, eng_noun:eggshell{}, eng_noun:Herzegovinian{}, eng_noun:sociolinguistic{}, eng_noun:attendant{}, eng_noun:cupreous{}, eng_noun:trim{}, eng_noun:antibacterial{}, eng_noun:idyllic{}, eng_noun:ginge{}, eng_noun:Croat{}, eng_noun:sorrel{}, eng_noun:nitro{}, eng_noun:Democrat{}, eng_noun:Latino{}, eng_noun:Tuscan{}, eng_noun:tarsal{}, eng_noun:didactyl{}, eng_noun:constituent{}, eng_noun:Mesolithic{}, eng_noun:duodecimal{}, eng_noun:abram{}, eng_noun:tercentenary{}, eng_noun:symbiotic{}, eng_noun:semidocumentary{}, eng_noun:scurvy{}, eng_noun:anticoagulant{}, eng_noun:bioterrorist{}, eng_noun:antarthritic{}, eng_noun:loony{}, eng_noun:Arabian{}, eng_noun:diploid{}, eng_noun:cardioid{}, eng_noun:tubby{}, eng_noun:Zoroastrian{}, eng_noun:interrogatory{}, eng_noun:annelid{}, eng_noun:parasitic{}, eng_noun:conglomerate{}, eng_noun:directive{}, eng_noun:antiperiodic{}, eng_noun:rapier{}, eng_noun:diazo{}, eng_noun:crisscross{}, eng_noun:all - american{}, eng_noun:bake - off{}, eng_noun:ungenerous{}, eng_noun:Extremaduran{}, eng_noun:empyrean{}, eng_noun:uncopyrightable{}, eng_noun:gorgon{}, eng_noun:purebred{}, eng_noun:preventive{}, eng_noun:polyploid{}, eng_noun:lippy{}, eng_noun:deltoid{}, eng_noun:saline{}, eng_noun:antasthmatic{}, eng_noun:prerogative{}, eng_noun:stormy{}, eng_noun:vulcanoid{}, eng_noun:inessive{}, eng_noun:bipartisan{}, eng_noun:spotty{}, eng_noun:three - quarter{}, eng_noun:fire - retardant{}, eng_noun:psychedelic{}, eng_noun:bellicist{}, eng_noun:Minorcan{}, eng_noun:trumpery{}, eng_noun:revanchist{}, eng_noun:triennial{}, eng_noun:manipulative{}, eng_noun:throw - away{}, eng_noun:Tchaikovskian{}, eng_noun:top - up{}, eng_noun:niggard{}, eng_noun:wind - up{}, eng_noun:chemic{}, eng_noun:radial{}, eng_noun:biologic{}, eng_noun:macaronic{}, eng_noun:voyeurist{}, eng_noun:Molossian{}, eng_noun:polemical{}, eng_noun:schizophrenic{}, eng_noun:preteen{}, eng_noun:upfront{}, eng_noun:putty{}, eng_noun:nosey{}, eng_noun:cretic{}, eng_noun:imperialist{}, eng_noun:Kampuchean{}, eng_noun:leftist{}, eng_noun:toxophilite{}, eng_noun:rollercoaster{}, eng_noun:teratogenic{}, eng_noun:prepositive{}, eng_noun:retromingent{}, eng_noun:longhair{}, eng_noun:roadside{}, eng_noun:duotrigintillionth{}, eng_noun:elegiack{}, eng_noun:phthisick{}, eng_noun:preconsent{}, eng_noun:Etrurian{}, eng_noun:loppard{}, eng_noun:Eusebian{}, eng_noun:falwe{}, eng_noun:Deweyan{}, eng_noun:methylic{}, eng_noun:multinumber{}, eng_noun:predelinquent{}, eng_noun:dentilabial{}, eng_noun:minour{}, eng_noun:supraoccipital{}, eng_noun:peripatetick{}, eng_noun:honourific{}, eng_noun:antidysenteric{}, eng_noun:scholastical{}, eng_noun:return{}, eng_noun:anuran{}, eng_noun:convulsant{}, eng_noun:detective{}, eng_noun:determinant{}, eng_noun:duff{}, eng_noun:fairy{}, eng_noun:farrago{}, eng_noun:fugitive{}, eng_noun:fun{}, eng_noun:forfeit{}, eng_noun:fustian{}, eng_noun:husky{}, eng_noun:inexperience{}, eng_noun:morisco{}, eng_noun:moline{}, eng_noun:monoacid{}, eng_noun:orthopteran{}, eng_noun:muzzy{}, eng_noun:nomad{}, eng_noun:nancy{}, eng_noun:olympian{}, eng_noun:pasty{}, eng_noun:proponent{}, eng_noun:rebel{}, eng_noun:rosy{}, eng_noun:rubato{}, eng_noun:schismatic{}, eng_noun:schizo{}, eng_noun:sound{}, eng_noun:siccative{}, eng_noun:substitute{}, eng_noun:unitary{}, eng_noun:typhoid{}, eng_noun:topical{}, eng_noun:windy{}, eng_noun:abstract{}, eng_noun:augustinian{}, eng_noun:calymmian{}, eng_noun:indo - aryan{}, eng_noun:patavine{}, eng_noun:hawk{}, eng_noun:mole{}, eng_noun:pixy{}, eng_noun:callow{}, eng_noun:scholar{}, eng_noun:counterfactual{}, eng_noun:gay{}, eng_noun:max{}, eng_noun:bound{}, eng_noun:frost{}, eng_noun:clitic{}, eng_noun:oolong{}, eng_noun:raster{}, eng_noun:colonic{}, eng_noun:coronal{}, eng_noun:proline{}, eng_noun:wearable{}, eng_noun:parkland{}, eng_noun:crosshead{}, eng_noun:screwball{}, eng_noun:sublimate{}, eng_noun:nearshore{}, eng_noun:hydrolase{}, eng_noun:portugese{}, eng_noun:harbourside{}, eng_noun:preproduction{}, eng_noun:wan{}, eng_noun:triceps{}, eng_noun:deface{}, eng_noun:ginger{}, eng_noun:august{}, eng_noun:hotfoot{}, eng_noun:notable{}, eng_noun:bass{}, eng_noun:kong{}, eng_noun:sonorant{}, eng_noun:candy{}, eng_noun:mute{}, eng_noun:base{}, eng_noun:fat{}, eng_noun:underwater{}, eng_noun:adjuvant{}, eng_noun:hyperbole{}, eng_noun:baritone{}, eng_noun:proclitic{}, eng_noun:airspace{}, eng_noun:chiropractic{}, eng_noun:crossing{}, eng_noun:something{}, eng_noun:heating{}, eng_noun:fledgling{}, eng_noun:understanding{}, eng_noun:serving{}, eng_noun:burning{}, eng_noun:vaulting{}, eng_noun:facing{}, eng_noun:sitting{}, eng_noun:unwitting{}, eng_noun:spanking{}, eng_noun:heaving{}, eng_noun:present{}, eng_noun:abdominal{}, eng_noun:aberrant{}, eng_noun:aboriginal{}, eng_noun:acanthopterygian{}, eng_noun:accidental{}, eng_noun:accordion{}, eng_noun:acid{}, eng_noun:quality{}, eng_noun:qualitative{}, eng_noun:woodwind{}, eng_noun:epizootic{}, eng_noun:now{}, eng_noun:Portuguese{}, eng_noun:accountant{}, eng_noun:grey{}, eng_noun:Saxon{}, eng_noun:Turkish{}, eng_noun:Slovak{}, eng_noun:Hungarian{}, eng_noun:Czech{}, eng_noun:Thai{}, eng_noun:Afrikaans{}, eng_noun:chartreuse{}, eng_noun:monthly{}, eng_noun:navy{}, eng_noun:bronze{}, eng_noun:tangerine{}, eng_noun:sapphire{}, eng_noun:chestnut{}, eng_noun:capital{}, eng_noun:Basque{}, eng_noun:comic{}, eng_noun:aesthetic{}, eng_noun:fluid{}, eng_noun:American{}, eng_noun:Andorran{}, eng_noun:adult{}, eng_noun:Hispanic{}, eng_noun:additive{}, eng_noun:classic{}, eng_noun:null{}, eng_noun:daily{}, eng_noun:cubic{}, eng_noun:argentine{}, eng_noun:manifest{}, eng_noun:android{}, eng_noun:almond{}, eng_noun:Latvian{}, eng_noun:Bhutanese{}, eng_noun:Paraguayan{}, eng_noun:Kenyan{}, eng_noun:Gambian{}, eng_noun:Zambian{}, eng_noun:Bruneian{}, eng_noun:Tongan{}, eng_noun:Euboean{}, eng_noun:Guadeloupean{}, eng_noun:Salvadorian{}, eng_noun:Martinican{}, eng_noun:Reunionese{}, eng_noun:Rwandese{}, eng_noun:Somali{}, eng_noun:Bermudian{}, eng_noun:sabbatical{}, eng_noun:knockout{}, eng_noun:shiny{}, eng_noun:ape{}, eng_noun:Achaian{}, eng_noun:Anglophone{}, eng_noun:trust{}, eng_noun:ghetto{}, eng_noun:millennial{}, eng_noun:Tamil{}, eng_noun:Panjabi{}, eng_noun:aerial{}, eng_noun:hippie{}, eng_noun:ethnic{}, eng_noun:Aberdonian{}, eng_noun:ultracrepidarian{}, eng_noun:advance{}, eng_noun:chattel{}, eng_noun:tangible{}, eng_noun:overall{}, eng_noun:alterative{}, eng_noun:ugly{}, eng_noun:antic{}, eng_noun:binary{}, eng_noun:quadriliteral{}, eng_noun:xenophobic{}, eng_noun:alcoholic{}, eng_noun:wanton{}, eng_noun:augmentative{}, eng_noun:flexitarian{}, eng_noun:cognate{}, eng_noun:spruce{}, eng_noun:duplex{}, eng_noun:transversal{}, eng_noun:fade{}, eng_noun:noir{}, eng_noun:hippy{}, eng_noun:discriminant{}, eng_noun:fancy{}, eng_noun:marsupial{}, eng_noun:Arab{}, eng_noun:intestate{}, eng_noun:intramural{}, eng_noun:underground{}, eng_noun:latest{}, eng_noun:collectible{}, eng_noun:statist{}, eng_noun:velopharyngeal{}, eng_noun:flexible{}, eng_noun:master{}, eng_noun:enzootic{}, eng_noun:nippy{}, eng_noun:TWOC{}, eng_noun:cutaway{}, eng_noun:Scouse{}, eng_noun:hebrephrenic{}, eng_noun:fanatic{}, eng_noun:gala{}, eng_noun:medial{}, eng_noun:tensor{}, eng_noun:unary{}, eng_noun:contingent{}, eng_noun:fundamental{}, eng_noun:intellectual{}, eng_noun:peripatetic{}, eng_noun:potential{}, eng_noun:primitive{}, eng_noun:starch{}, eng_noun:stout{}, eng_noun:caustic{}, eng_noun:udal{}, eng_noun:phony{}, eng_noun:concordant{}, eng_noun:mid - july{}, eng_noun:midsummer{}, eng_noun:negroid{}, eng_noun:Mohammedan{}, eng_noun:chameleon{}, eng_noun:transient{}, eng_noun:broody{}, eng_noun:rookie{}, eng_noun:consanguineous{}, eng_noun:daredevil{}, eng_noun:brunette{}, eng_noun:indigent{}, eng_noun:inert{}, eng_noun:posterior{}, eng_noun:culinary{}, eng_noun:clamshell{}, eng_noun:columbine{}, eng_noun:plush{}, eng_noun:petunia{}, eng_noun:silent{}, eng_noun:demographic{}, eng_noun:previous{}, eng_noun:collaborative{}, eng_noun:journal{}, eng_noun:gossamer{}, eng_noun:snub{}, eng_noun:armchair{}, eng_noun:upright{}, eng_noun:monotone{}, eng_noun:insectoid{}, eng_noun:nonagenarian{}, eng_noun:federal{}, eng_noun:chill{}, eng_noun:diabetic{}, eng_noun:projectile{}, eng_noun:synthetic{}, eng_noun:one - to - one{}, eng_noun:Glaswegian{}, eng_noun:heterodyne{}, eng_noun:visual{}, eng_noun:heteropod{}, eng_noun:Whitsun{}, eng_noun:Samian{}, eng_noun:apolitical{}, eng_noun:flannel{}, eng_noun:taboo{}, eng_noun:pally{}, eng_noun:multiplex{}, eng_noun:guilty{}, eng_noun:outpatient{}, eng_noun:ith{}, eng_noun:erratic{}, eng_noun:crystalline{}, eng_noun:impromptu{}, eng_noun:haywire{}, eng_noun:crusty{}, eng_noun:vintage{}, eng_noun:airborne{}, eng_noun:brahmin{}, eng_noun:contraceptive{}, eng_noun:backhand{}, eng_noun:whiff{}, eng_noun:mainstream{}, eng_noun:bravura{}, eng_noun:adipose{}, eng_noun:overnight{}, eng_noun:inanimate{}, eng_noun:ultra{}, eng_noun:parental{}, eng_noun:flush{}, eng_noun:coo{}, eng_noun:yogi{}, eng_noun:deliverable{}, eng_noun:ballpark{}, eng_noun:scenic{}, eng_noun:pavonine{}, eng_noun:Eocene{}, eng_noun:dainty{}, eng_noun:cellular{}, eng_noun:cuttie{}, eng_noun:libertine{}, eng_noun:residual{}, eng_noun:singulative{}, eng_noun:back - up{}, eng_noun:oxblood{}, eng_noun:Guinean{}, eng_noun:hamate{}, eng_noun:Himalayan{}, eng_noun:Proctor{}, eng_noun:Wiccan{}, eng_noun:collegiate{}, eng_noun:vertebral{}, eng_noun:chemotherapeutic{}, eng_noun:pituitary{}, eng_noun:Gurkha{}, eng_noun:Sunni{}, eng_noun:go - ahead{}, eng_noun:kalua{}, eng_noun:semi - automatic{}, eng_noun:microcephalic{}, eng_noun:taxable{}, eng_noun:palliative{}, eng_noun:anticorrosive{}, eng_noun:antimodernist{}, eng_noun:elliptical{}, eng_noun:coeliac{}, eng_noun:endocrine{}, eng_noun:plump{}, eng_noun:chelate{}, eng_noun:centenary{}, eng_noun:Zwinglian{}, eng_noun:deadbeat{}, eng_noun:sentient{}, eng_noun:antimicrobial{}, eng_noun:antipsychotic{}, eng_noun:correlative{}, eng_noun:passerine{}, eng_noun:didactic{}, eng_noun:alkaline{}, eng_noun:no - name{}, eng_noun:saccharine{}, eng_noun:fraught{}, eng_noun:letterbox{}, eng_noun:windup{}, eng_noun:matte{}, eng_noun:Nazarene{}, eng_noun:aspirant{}, eng_noun:oceanfront{}, eng_noun:resistant{}, eng_noun:dernier{}, eng_noun:chemopreventive{}, eng_noun:depressant{}, eng_noun:bantam{}, eng_noun:immigrant{}, eng_noun:masticatory{}, eng_noun:redwood{}, eng_noun:Delphic{}, eng_noun:Silesian{}, eng_noun:Pomeranian{}, eng_noun:anticatholic{}, eng_noun:Damocloid{}, eng_noun:propaedeutic{}, eng_noun:militant{}, eng_noun:scapular{}, eng_noun:flame - retardant{}, eng_noun:seesaw{}, eng_noun:Madrilenian{}, eng_noun:suzerain{}, eng_noun:unsalable{}, eng_noun:subaltern{}, eng_noun:rowdy{}, eng_noun:hoyden{}, eng_noun:propre{}, eng_noun:tortoiseshell{}, eng_noun:Shinto{}, eng_noun:Grecophone{}, eng_noun:harmonic{}, eng_noun:esthetic{}, eng_noun:irritant{}, eng_noun:Malayan{}, eng_noun:clathrate{}, eng_noun:diocesan{}, eng_noun:phenolic{}, eng_noun:Irani{}, eng_noun:cataleptic{}, eng_noun:titular{}, eng_noun:hectic{}, eng_noun:organoid{}, eng_noun:xiphosuran{}, eng_noun:proparoxytone{}, eng_noun:Minoan{}, eng_noun:curly{}, eng_noun:southeasterly{}, eng_noun:vesicant{}, eng_noun:midlife{}, eng_noun:workaholic{}, eng_noun:interactive{}, eng_noun:quintillionth{}, eng_noun:noetic{}, eng_noun:misty{}, eng_noun:styptic{}, eng_noun:chippy{}, eng_noun:upslope{}, eng_noun:plumbous{}, eng_noun:otalgic{}, eng_noun:minimalist{}, eng_noun:executable{}, eng_noun:duodecillionth{}, eng_noun:alterable{}, eng_noun:carbenoid{}, eng_noun:pictorial{}, eng_noun:locomotive{}, eng_noun:advisory{}, eng_noun:ashcan{}, eng_noun:telephoto{}, eng_noun:neorealist{}, eng_noun:Sumerian{}, eng_noun:mountaintop{}, eng_noun:jingoist{}, eng_noun:suffragan{}, eng_noun:Milanese{}, eng_noun:lachrymatory{}, eng_noun:pre - game{}, eng_noun:middlebrow{}, eng_noun:co - dependent{}, eng_noun:reverential{}, eng_noun:omnitheist{}, eng_noun:masculinist{}, eng_noun:anionic{}, eng_noun:eutrophic{}, eng_noun:trine{}, eng_noun:courtly{}, eng_noun:polysomic{}, eng_noun:anorectic{}, eng_noun:aphasic{}, eng_noun:bigeminal{}, eng_noun:biomedical{}, eng_noun:tetrapod{}, eng_noun:Belarusan{}, eng_noun:sexagenary{}, eng_noun:Benedictine{}, eng_noun:interstadial{}, eng_noun:Cestrian{}, eng_noun:triplex{}, eng_noun:raglan{}, eng_noun:univalve{}, eng_noun:subteen{}, eng_noun:subhuman{}, eng_noun:dilly{}, eng_noun:postern{}, eng_noun:inessential{}, eng_noun:Coptic{}, eng_noun:copyrightable{}, eng_noun:nymphomanic{}, eng_noun:congregationalist{}, eng_noun:pentadecimal{}, eng_noun:Mensan{}, eng_noun:triumphalist{}, eng_noun:hardline{}, eng_noun:performative{}, eng_noun:ever - present{}, eng_noun:Skinnerian{}, eng_noun:Manitoban{}, eng_noun:grandioso{}, eng_noun:percipient{}, eng_noun:appellative{}, eng_noun:ceratopsian{}, eng_noun:close - up{}, eng_noun:Miwokan{}, eng_noun:retardant{}, eng_noun:aversive{}, eng_noun:nonnegotiable{}, eng_noun:cash - flow{}, eng_noun:drystone{}, eng_noun:metamict{}, eng_noun:platinoid{}, eng_noun:indigene{}, eng_noun:three - ply{}, eng_noun:minikin{}, eng_noun:Formosan{}, eng_noun:indiscernible{}, eng_noun:crypto - fascist{}, eng_noun:Kantian{}, eng_noun:Tocharian{}, eng_noun:mentalist{}, eng_noun:Pahari{}, eng_noun:ready - made{}, eng_noun:mesoscale{}, eng_noun:innumerate{}, eng_noun:internationalist{}, eng_noun:adjunctive{}, eng_noun:volitive{}, eng_noun:transmembrane{}, eng_noun:odorant{}, eng_noun:allelochemical{}, eng_noun:cubozoan{}, eng_noun:intershell{}, eng_noun:nonrenewable{}, eng_noun:constat{}, eng_noun:antifeedant{}, eng_noun:revisionist{}, eng_noun:nonbelligerent{}, eng_noun:injectable{}, eng_noun:frontline{}, eng_noun:goodwife{}, eng_noun:nonhuman{}, eng_noun:Arizonan{}, eng_noun:nonmilitant{}, eng_noun:gazillionth{}, eng_noun:shadowless{}, eng_noun:abortogenic{}, eng_noun:fireward{}, eng_noun:quadrinomial{}, eng_noun:placeable{}, eng_noun:amoeboid{}, eng_noun:analeptic{}, eng_noun:Kosovar{}, eng_noun:antipain{}, eng_noun:Almain{}, eng_noun:multichannel{}, eng_noun:coorse{}, eng_noun:Manzonian{}, eng_noun:penetrant{}, eng_noun:bdelloid{}, eng_noun:antinicotinic{}, eng_noun:lew{}, eng_noun:saluretic{}, eng_noun:antifolate{}, eng_noun:renunciant{}, eng_noun:halfwidth{}, eng_noun:hawse{}, eng_noun:febricitant{}, eng_noun:Kyivan{}, eng_noun:interlayer{}, eng_noun:noninteger{}, eng_noun:organomercurial{}, eng_noun:smoothbore{}, eng_noun:superrich{}, eng_noun:Muhammadan{}, eng_noun:coacervate{}, eng_noun:multienzyme{}, eng_noun:trinary{}, eng_noun:macroeconomic{}, eng_noun:scopophiliac{}, eng_noun:Buriat{}, eng_noun:calefacient{}, eng_noun:Kazakhstani{}, eng_noun:Colossian{}, eng_noun:Salesian{}, eng_noun:nonstaple{}, eng_noun:Astroturf{}, eng_noun:consequentialist{}, eng_noun:Vincentian{}, eng_noun:non - terminal{}, eng_noun:descriptivist{}, eng_noun:Capricornian{}, eng_noun:Virgoan{}, eng_noun:Taurean{}, eng_noun:Leonian{}, eng_noun:saurischian{}, eng_noun:notoungulate{}, eng_noun:hench{}, eng_noun:unquantifiable{}, eng_noun:hysteroid{}, eng_noun:Hispanian{}, eng_noun:septothecal{}, eng_noun:eevn{}, eng_noun:half - width{}, eng_noun:cyberfeminist{}, eng_noun:tusky{}, eng_noun:ecumenist{}, eng_noun:salmonid{}, eng_noun:postsectarian{}, eng_noun:prediabetic{}, eng_noun:antiphase{}, eng_noun:subliterate{}, eng_noun:errhine{}, eng_noun:orangey{}, eng_noun:Balzacian{}, eng_noun:high - pass{}, eng_noun:maximalist{}, eng_noun:enate{}, eng_noun:CFNM{}, eng_noun:Gascon{}, eng_noun:eventualist{}, eng_noun:pseudovirgin{}, eng_noun:basisphenoid{}, eng_noun:dinosaurian{}, eng_noun:cytoprotective{}, eng_noun:noncompete{}, eng_noun:myelosuppressive{}, eng_noun:subjectivist{}, eng_noun:centralist{}, eng_noun:noncognate{}, eng_noun:nonanimal{}, eng_noun:inegalitarian{}, eng_noun:nonmarried{}, eng_noun:symptomless{}, eng_noun:multiculturalist{}, eng_noun:midcap{}, eng_noun:nonrival{}, eng_noun:whirly{}, eng_noun:protohuman{}, eng_noun:Paulian{}, eng_noun:realis{}, eng_noun:nonepileptic{}, eng_noun:cidery{}, eng_noun:nerdcore{}, eng_noun:nonfriable{}, eng_noun:ejectile{}, eng_noun:no - doc{}, eng_noun:Mariavite{}, eng_noun:acmeist{}, eng_noun:shell - like{}, eng_noun:Masurian{}, eng_noun:Lewesian{}, eng_noun:bysen{}, eng_noun:Pyrrhonian{}, eng_noun:Praguian{}, eng_noun:Ljubljanan{}, eng_noun:Tiranan{}, eng_noun:Brusselian{}, eng_noun:Copenhagener{}, eng_noun:Stockholmer{}, eng_noun:intensivist{}, eng_noun:Burnsian{}, eng_noun:Brabantian{}, eng_noun:precative{}, eng_noun:Crowleyan{}, eng_noun:Helvetian{}, eng_noun:Byronian{}, eng_noun:hyperreal{}, eng_noun:Campbellite{}, eng_noun:nonparanoid{}, eng_noun:alexipharmic{}, eng_noun:nonwar{}, eng_noun:precancer{}, eng_noun:Adjarian{}, eng_noun:anticar{}, eng_noun:nonminor{}, eng_noun:nonbisexual{}, eng_noun:chemoprophylactic{}, eng_noun:counterfeminist{}, eng_noun:non - dance{}, eng_noun:nonproperty{}, eng_noun:nonegalitarian{}, eng_noun:Lockean{}, eng_noun:Pompeian{}, eng_noun:Australopith{}, eng_noun:nonindigent{}, eng_noun:vetitive{}, eng_noun:wholewheat{}, eng_noun:nonvariant{}, eng_noun:Gagauz{}, eng_noun:nonmonetarist{}, eng_noun:stupefacient{}, eng_noun:preop{}, eng_noun:mousseux{}, eng_noun:monofractal{}, eng_noun:unfavorite{}, eng_noun:nonhorse{}, eng_noun:nondrama{}, eng_noun:Cyprian{}, eng_noun:multiquark{}, eng_noun:capitulationist{}, eng_noun:pteropine{}, eng_noun:Pichileminian{}, eng_noun:Afro - indian{}, eng_noun:Sassanid{}, eng_noun:Abkhasian{}, eng_noun:Cameronite{}, eng_noun:Antiochian{}, eng_noun:heartcut{}, eng_noun:Aramaean{}, eng_noun:Aramean{}, eng_noun:Medician{}, eng_noun:gorgonian{}, eng_noun:ichthyoid{}, eng_noun:pro - abort{}, eng_noun:balductum{}, eng_noun:reactionist{}, eng_noun:predicant{}, eng_noun:settleable{}, eng_noun:asbuilt{}, eng_noun:Chattanoogan{}, eng_noun:Sevillan{}, eng_noun:anti - rust{}, eng_noun:Tripolitanian{}, eng_noun:push - through{}, eng_noun:drudgy{}, eng_noun:Ossete{}, eng_noun:scatheless{}, eng_noun:exhortative{}, eng_noun:Gallo - roman{}, eng_noun:hokie{}, eng_noun:bellywark{}, eng_noun:megadollar{}, eng_noun:multialgorithm{}, eng_noun:cooperant{}, eng_noun:twissell{}, eng_noun:italophone{}, eng_noun:antipluralist{}, eng_noun:antinaturalist{}, eng_noun:mithridatic{}, eng_noun:Seljuqian{}, eng_noun:meshugenah{}, eng_noun:sixgill{}, eng_noun:rustick{}, eng_noun:braveheart{}, eng_noun:advaunce{}, eng_noun:Hebrean{}, eng_noun:interiour{}, eng_noun:Columbian{}, eng_noun:Pamplonan{}, eng_noun:vorticist{}, eng_noun:antiliberal{}, eng_noun:antilibertarian{}, eng_noun:antidesiccant{}, eng_noun:nonsubject{}, eng_noun:antimask{}, eng_noun:antiquitarian{}, eng_noun:majour{}, eng_noun:nonprotest{}, eng_noun:characteristick{}, eng_noun:tonick{}, eng_noun:ethnick{}, eng_noun:paralytick{}, eng_noun:novenary{}, eng_noun:opercular{}, eng_noun:rory{}, eng_noun:Haytian{}, eng_noun:bumfuck{}, eng_noun:Afric{}, eng_noun:nasoturbinal{}, eng_noun:miscreaunt{}, eng_noun:tauromachian{}, eng_noun:hypohyal{}, eng_noun:refrigerative{}, eng_noun:antipodagric{}, eng_noun:Tripolitan{}, eng_noun:crossopterygian{}, eng_noun:Achaemenian{}, eng_noun:antihypnotic{}, eng_noun:Utahan{}, eng_noun:implacental{}, eng_noun:counter - revolutionary{}, eng_noun:interparietal{}, eng_noun:clinodiagonal{}, eng_noun:world{}, eng_noun:work{}, eng_noun:pale{}, eng_noun:close{}, eng_noun:evil{}, eng_noun:old{}, eng_noun:summer{}, eng_noun:spare{}, eng_noun:anglophile{}, eng_noun:attractant{}, eng_noun:biscuit{}, eng_noun:carrion{}, eng_noun:caesarean{}, eng_noun:cree{}, eng_noun:darn{}, eng_noun:decrescendo{}, eng_noun:disinfectant{}, eng_noun:dusk{}, eng_noun:factoid{}, eng_noun:fake{}, eng_noun:glam{}, eng_noun:ganoid{}, eng_noun:frank{}, eng_noun:hydrozoan{}, eng_noun:infidel{}, eng_noun:isoseismal{}, eng_noun:journalist{}, eng_noun:julienne{}, eng_noun:lowland{}, eng_noun:monocular{}, eng_noun:neuralgia{}, eng_noun:overenthusiasm{}, eng_noun:naught{}, eng_noun:placoid{}, eng_noun:pianissimo{}, eng_noun:polymorphism{}, eng_noun:partisan{}, eng_noun:recusant{}, eng_noun:purgative{}, eng_noun:predestinarian{}, eng_noun:sib{}, eng_noun:territorial{}, eng_noun:superscript{}, eng_noun:teen{}, eng_noun:stationary{}, eng_noun:tonic{}, eng_noun:trusty{}, eng_noun:volute{}, eng_noun:vegetable{}, eng_noun:republicrat{}, eng_noun:mope{}, eng_noun:hump{}, eng_noun:secant{}, eng_noun:parti{}, eng_noun:hind{}, eng_noun:rigorist{}, eng_noun:courtier{}, eng_noun:romanesque{}, eng_noun:shy{}, eng_noun:boon{}, eng_noun:umber{}, eng_noun:forte{}, eng_noun:swell{}, eng_noun:techno{}, eng_noun:outback{}, eng_noun:electro{}, eng_noun:haulage{}, eng_noun:shipboard{}, eng_noun:pastorate{}, eng_noun:monocoque{}, eng_noun:allegretto{}, eng_noun:sabbatarian{}, eng_noun:fit{}, eng_noun:aloetic{}, eng_noun:flat{}, eng_noun:bivalve{}, eng_noun:extrovert{}, eng_noun:video{}, eng_noun:hairline{}, eng_noun:softcore{}, eng_noun:ultraviolet{}, eng_noun:paralegal{}, eng_noun:problematic{}, eng_noun:friendly{}, eng_noun:factorial{}, eng_noun:airplay{}, eng_noun:necessarian{}, eng_noun:autofocus{}, eng_noun:hale{}, eng_noun:paraboloid{}, eng_noun:lophobranch{}, eng_noun:viridian{}, eng_noun:lagging{}, eng_noun:speaking{}, eng_noun:beginning{}, eng_noun:happening{}, eng_noun:killing{}, eng_noun:pressing{}, eng_noun:spinning{}, eng_noun:tickling{}, eng_noun:sporting{}, eng_noun:sterling{}, eng_noun:unreflecting{}, eng_noun:unsuspecting{}, eng_noun:childbearing{}, eng_noun:shareholding{}, eng_noun:trending{}, eng_noun:inbound{}, eng_noun:inbred{}, eng_noun:abdicant{}, eng_noun:ablative{}, eng_noun:abnormal{}, eng_noun:abolitionist{}, eng_noun:absolvent{}, eng_noun:abstersive{}, eng_noun:abstinent{}, eng_noun:Abyssinian{}, eng_noun:pseudo{}, eng_noun:quotidian{}, eng_noun:uncountable{}, eng_noun:Netherlands{}, eng_noun:ace{}, eng_noun:silver{}, eng_noun:imperfect{}, eng_noun:irrational{}, eng_noun:infinitive{}, eng_noun:future{}, eng_noun:comparative{}, eng_noun:leather{}, eng_noun:east{}, eng_noun:crimson{}, eng_noun:azure{}, eng_noun:aquamarine{}, eng_noun:chocolate{}, eng_noun:orchid{}, eng_noun:salmon{}, eng_noun:turquoise{}, eng_noun:russet{}, eng_noun:scarlet{}, eng_noun:sepia{}, eng_noun:amethyst{}, eng_noun:pyramidal{}, eng_noun:Canberran{}, eng_noun:Hobartian{}, eng_noun:Perthian{}, eng_noun:chamois{}, eng_noun:Zulu{}, eng_noun:liberal{}, eng_noun:aforementioned{}, eng_noun:maiden{}, eng_noun:Moslem{}, eng_noun:criminal{}, eng_noun:exterior{}, eng_noun:Cornish{}, eng_noun:by{}, eng_noun:chicken{}, eng_noun:liquid{}, eng_noun:federation{}, eng_noun:freshwater{}, eng_noun:Armenian{}, eng_noun:quiet{}, eng_noun:penultimate{}, eng_noun:cardinal{}, eng_noun:hypocoristic{}, eng_noun:Sardinian{}, eng_noun:Floridian{}, eng_noun:Neapolitan{}, eng_noun:Venetian{}, eng_noun:supernatural{}, eng_noun:acephalan{}, eng_noun:epicurean{}, eng_noun:coefficient{}, eng_noun:economy{}, eng_noun:Bahamian{}, eng_noun:Barbadian{}, eng_noun:Swiss{}, eng_noun:Pakistani{}, eng_noun:Egyptian{}, eng_noun:Lebanese{}, eng_noun:Tunisian{}, eng_noun:Ivorian{}, eng_noun:Togolese{}, eng_noun:Saudi{}, eng_noun:foible{}, eng_noun:hybrid{}, eng_noun:dynamic{}, eng_noun:apricot{}, eng_noun:Punjabi{}, eng_noun:Eskimo{}, eng_noun:exotic{}, eng_noun:aery{}, eng_noun:rouge{}, eng_noun:chief{}, eng_noun:up{}, eng_noun:affluent{}, eng_noun:superficial{}, eng_noun:valuable{}, eng_noun:kam{}, eng_noun:intent{}, eng_noun:variable{}, eng_noun:Manx{}, eng_noun:Tahitian{}, eng_noun:inside{}, eng_noun:constructivist{}, eng_noun:equal{}, eng_noun:descriptive{}, eng_noun:median{}, eng_noun:possible{}, eng_noun:passive{}, eng_noun:triliteral{}, eng_noun:defective{}, eng_noun:nonalcoholic{}, eng_noun:staccato{}, eng_noun:fortis{}, eng_noun:adverbial{}, eng_noun:Trinitarian{}, eng_noun:universist{}, eng_noun:lab{}, eng_noun:faux{}, eng_noun:brand{}, eng_noun:globular{}, eng_noun:horsy{}, eng_noun:capillary{}, eng_noun:normal{}, eng_noun:citron{}, eng_noun:pagan{}, eng_noun:mulberry{}, eng_noun:apposite{}, eng_noun:hermaphrodite{}, eng_noun:centigrade{}, eng_noun:fetid{}, eng_noun:LEGO{}, eng_noun:recalcitrant{}, eng_noun:salient{}, eng_noun:prior{}, eng_noun:triple{}, eng_noun:religious{}, eng_noun:spiritual{}, eng_noun:unrestrained{}, eng_noun:captive{}, eng_noun:emo{}, eng_noun:compulsive{}, eng_noun:sandy{}, eng_noun:basal{}, eng_noun:dickey{}, eng_noun:hymnal{}, eng_noun:patina{}, eng_noun:withy{}, eng_noun:antinomian{}, eng_noun:dandelion{}, eng_noun:immune{}, eng_noun:indubitable{}, eng_noun:ripe{}, eng_noun:splay{}, eng_noun:recluse{}, eng_noun:thumby{}, eng_noun:sunny{}, eng_noun:explosive{}, eng_noun:paranoid{}, eng_noun:Bacchanalian{}, eng_noun:gyratory{}, eng_noun:savvy{}, eng_noun:crunk{}, eng_noun:mid - december{}, eng_noun:state - of - the - art{}, eng_noun:candid{}, eng_noun:avant - garde{}, eng_noun:fungible{}, eng_noun:Dickensian{}, eng_noun:manuscript{}, eng_noun:Iberian{}, eng_noun:aromatic{}, eng_noun:prescriptivist{}, eng_noun:sickle{}, eng_noun:batshit{}, eng_noun:blackleg{}, eng_noun:conic{}, eng_noun:associate{}, eng_noun:telltale{}, eng_noun:lily{}, eng_noun:Remulakian{}, eng_noun:starvation{}, eng_noun:profound{}, eng_noun:megapixel{}, eng_noun:fringe{}, eng_noun:antepenultimate{}, eng_noun:paprika{}, eng_noun:pluperfect{}, eng_noun:routine{}, eng_noun:undercover{}, eng_noun:metropolitan{}, eng_noun:polemic{}, eng_noun:xenobiotic{}, eng_noun:hypnotic{}, eng_noun:hypochondriac{}, eng_noun:frolic{}, eng_noun:badass{}, eng_noun:epicene{}, eng_noun:crematory{}, eng_noun:emergency{}, eng_noun:pisiform{}, eng_noun:fashionable{}, eng_noun:heterodont{}, eng_noun:comedolytic{}, eng_noun:stretto{}, eng_noun:meliorist{}, eng_noun:covert{}, eng_noun:pompous{}, eng_noun:metallic{}, eng_noun:broadband{}, eng_noun:girly{}, eng_noun:tough{}, eng_noun:outsize{}, eng_noun:dop{}, eng_noun:picaresque{}, eng_noun:infrared{}, eng_noun:conjunctive{}, eng_noun:coprophiliac{}, eng_noun:schoolboy{}, eng_noun:chubby{}, eng_noun:tutelary{}, eng_noun:astringent{}, eng_noun:inedible{}, eng_noun:undergraduate{}, eng_noun:undesirable{}, eng_noun:pedigree{}, eng_noun:rascal{}, eng_noun:malcontent{}, eng_noun:legendary{}, eng_noun:Lusophone{}, eng_noun:transformist{}, eng_noun:Cockney{}, eng_noun:elitist{}, eng_noun:transnational{}, eng_noun:transactinide{}, eng_noun:Ediacaran{}, eng_noun:Mississippian{}, eng_noun:antioxidant{}, eng_noun:dumbshit{}, eng_noun:downtown{}, eng_noun:cloverleaf{}, eng_noun:gamboge{}, eng_noun:reseda{}, eng_noun:Aristotelian{}, eng_noun:burlywood{}, eng_noun:lovat{}, eng_noun:florentine{}, eng_noun:dissentient{}, eng_noun:scaphoid{}, eng_noun:poltroon{}, eng_noun:co - ed{}, eng_noun:sphenoid{}, eng_noun:grass - green{}, eng_noun:monorchid{}, eng_noun:lacy{}, eng_noun:dioptric{}, eng_noun:fey{}, eng_noun:retrospective{}, eng_noun:takeaway{}, eng_noun:Disney{}, eng_noun:literate{}, eng_noun:repellant{}, eng_noun:alluvial{}, eng_noun:hylic{}, eng_noun:reptilian{}, eng_noun:terpsichorean{}, eng_noun:ignostic{}, eng_noun:heathen{}, eng_noun:murk{}, eng_noun:Albertan{}, eng_noun:sublime{}, eng_noun:hearty{}, eng_noun:motley{}, eng_noun:proximate{}, eng_noun:corrival{}, eng_noun:lonesome{}, eng_noun:indispensable{}, eng_noun:organometallic{}, eng_noun:brunet{}, eng_noun:parastatal{}, eng_noun:psychotropic{}, eng_noun:flambe{}, eng_noun:technosexual{}, eng_noun:zygodactyl{}, eng_noun:exhibitionist{}, eng_noun:invasive{}, eng_noun:Pentecostal{}, eng_noun:stunod{}, eng_noun:textbook{}, eng_noun:thematic{}, eng_noun:terracotta{}, eng_noun:bloodshot{}, eng_noun:Israelite{}, eng_noun:postgrad{}, eng_noun:exemplary{}, eng_noun:adessive{}, eng_noun:esculent{}, eng_noun:succulent{}, eng_noun:supplemental{}, eng_noun:satin{}, eng_noun:backwoods{}, eng_noun:separatist{}, eng_noun:payable{}, eng_noun:eastward{}, eng_noun:madcap{}, eng_noun:pococurante{}, eng_noun:psychoanalytic{}, eng_noun:Caesarian{}, eng_noun:caitiff{}, eng_noun:ferly{}, eng_noun:diuretic{}, eng_noun:Tlingit{}, eng_noun:Torontonian{}, eng_noun:traducian{}, eng_noun:analgesic{}, eng_noun:Riojan{}, eng_noun:reformist{}, eng_noun:hydro{}, eng_noun:rotary{}, eng_noun:Arian{}, eng_noun:immunological{}, eng_noun:namby - pamby{}, eng_noun:rah{}, eng_noun:crinoid{}, eng_noun:irredentist{}, eng_noun:xiphioid{}, eng_noun:preschool{}, eng_noun:intermetallic{}, eng_noun:untimely{}, eng_noun:parietal{}, eng_noun:folkie{}, eng_noun:bulimic{}, eng_noun:rattletrap{}, eng_noun:prerequisite{}, eng_noun:rodomontade{}, eng_noun:Stakhanovite{}, eng_noun:polyphenolic{}, eng_noun:champaign{}, eng_noun:enceinte{}, eng_noun:jussive{}, eng_noun:ooid{}, eng_noun:grizzly{}, eng_noun:confectionary{}, eng_noun:ascendant{}, eng_noun:carefree{}, eng_noun:squiggly{}, eng_noun:sesquiterpenoid{}, eng_noun:clatty{}, eng_noun:Grecian{}, eng_noun:legionary{}, eng_noun:Zanzibari{}, eng_noun:causative{}, eng_noun:imponderable{}, eng_noun:paquebot{}, eng_noun:Pastafarian{}, eng_noun:agoraphobic{}, eng_noun:attaint{}, eng_noun:docetist{}, eng_noun:rhinestone{}, eng_noun:standover{}, eng_noun:girlie{}, eng_noun:Beltway{}, eng_noun:unrestricted{}, eng_noun:sulpha{}, eng_noun:fae{}, eng_noun:nonessential{}, eng_noun:parasympathomimetic{}, eng_noun:liveaboard{}, eng_noun:eyeful{}, eng_noun:walk - up{}, eng_noun:castiron{}, eng_noun:escapist{}, eng_noun:waterside{}, eng_noun:polytene{}, eng_noun:arthritic{}, eng_noun:trisyllabic{}, eng_noun:biodegradable{}, eng_noun:Moldavian{}, eng_noun:Byelorussian{}, eng_noun:frictionless{}, eng_noun:salutatory{}, eng_noun:Acheulean{}, eng_noun:pluvial{}, eng_noun:poopy{}, eng_noun:poopie{}, eng_noun:semblable{}, eng_noun:climacteric{}, eng_noun:spalt{}, eng_noun:negotiable{}, eng_noun:sciurine{}, eng_noun:sooky{}, eng_noun:glassful{}, eng_noun:long - haul{}, eng_noun:work - to - rule{}, eng_noun:centrist{}, eng_noun:Canaanite{}, eng_noun:careerist{}, eng_noun:concubinary{}, eng_noun:microelectronic{}, eng_noun:split - level{}, eng_noun:domiciliary{}, eng_noun:slip - on{}, eng_noun:semiprofessional{}, eng_noun:ding - dong{}, eng_noun:preventative{}, eng_noun:ovibovine{}, eng_noun:billable{}, eng_noun:Pascha{}, eng_noun:antimycotic{}, eng_noun:antifungal{}, eng_noun:polyacrylic{}, eng_noun:polyunsaturate{}, eng_noun:approbative{}, eng_noun:essentialist{}, eng_noun:boffo{}, eng_noun:Maxonian{}, eng_noun:octonary{}, eng_noun:eruptive{}, eng_noun:ternary{}, eng_noun:mandibulate{}, eng_noun:Mannerist{}, eng_noun:decretal{}, eng_noun:Jerusalemite{}, eng_noun:Ottawan{}, eng_noun:Peronist{}, eng_noun:freezable{}, eng_noun:Aquarian{}, eng_noun:depilatory{}, eng_noun:mure{}, eng_noun:dinkum{}, eng_noun:Finnic{}, eng_noun:vallecular{}, eng_noun:Aluredian{}, eng_noun:microsurgery{}, eng_noun:hearthside{}, eng_noun:hookup{}, eng_noun:indeterminable{}, eng_noun:bamboo{}, eng_noun:heptapeptide{}, eng_noun:nonpartisan{}, eng_noun:vespid{}, eng_noun:diglot{}, eng_noun:organobromine{}, eng_noun:proforma{}, eng_noun:sawtooth{}, eng_noun:Tenochcan{}, eng_noun:remiped{}, eng_noun:paediatric{}, eng_noun:nihilarian{}, eng_noun:quadrate{}, eng_noun:Nebraskan{}, eng_noun:Nabatean{}, eng_noun:pansexual{}, eng_noun:parotid{}, eng_noun:Dorian{}, eng_noun:Zarathustrian{}, eng_noun:nonparticipant{}, eng_noun:nonrecognition{}, eng_noun:nonsexist{}, eng_noun:nonspecialist{}, eng_noun:Emirati{}, eng_noun:serpentry{}, eng_noun:geru{}, eng_noun:bichord{}, eng_noun:roundhead{}, eng_noun:Jamerican{}, eng_noun:epical{}, eng_noun:antiprotozoal{}, eng_noun:cotemporary{}, eng_noun:alkenyl{}, eng_noun:preseed{}, eng_noun:aminopropyl{}, eng_noun:Rusyn{}, eng_noun:brookside{}, eng_noun:screwtop{}, eng_noun:Indo - germanic{}, eng_noun:biaryl{}, eng_noun:quartan{}, eng_noun:nanophase{}, eng_noun:nonwoven{}, eng_noun:Ukie{}, eng_noun:choleretic{}, eng_noun:structuralist{}, eng_noun:obviative{}, eng_noun:A - line{}, eng_noun:Bostonite{}, eng_noun:antitumor{}, eng_noun:fattist{}, eng_noun:cathartical{}, eng_noun:scoptophiliac{}, eng_noun:Bashkortostani{}, eng_noun:anacreontic{}, eng_noun:neofascist{}, eng_noun:germinant{}, eng_noun:occurrent{}, eng_noun:imponent{}, eng_noun:sphingid{}, eng_noun:turbellarian{}, eng_noun:vesicomyid{}, eng_noun:kutcha{}, eng_noun:elapid{}, eng_noun:hypothecary{}, eng_noun:Manchurian{}, eng_noun:speccy{}, eng_noun:delphinine{}, eng_noun:callable{}, eng_noun:ultramontane{}, eng_noun:Tadzhik{}, eng_noun:Tennessean{}, eng_noun:antifibrinolytic{}, eng_noun:nonemergency{}, eng_noun:anticonsumerist{}, eng_noun:prehypertensive{}, eng_noun:ultranationalist{}, eng_noun:Cromwellian{}, eng_noun:reliabilist{}, eng_noun:fictionalist{}, eng_noun:coherentist{}, eng_noun:semi - vegetarian{}, eng_noun:apiarian{}, eng_noun:nonbusiness{}, eng_noun:ultraportable{}, eng_noun:nonsolvent{}, eng_noun:make - out{}, eng_noun:nonrecombinant{}, eng_noun:paranuchal{}, eng_noun:midconcert{}, eng_noun:nonruminant{}, eng_noun:nondaily{}, eng_noun:lacertilian{}, eng_noun:Mangaian{}, eng_noun:Oblomovist{}, eng_noun:Mantinean{}, eng_noun:Mantuan{}, eng_noun:nonscalar{}, eng_noun:medusoid{}, eng_noun:Shanghainese{}, eng_noun:Benthamite{}, eng_noun:nonmineral{}, eng_noun:Sarajevan{}, eng_noun:Skopjan{}, eng_noun:Rigan{}, eng_noun:Hanoian{}, eng_noun:nonlife{}, eng_noun:bayard{}, eng_noun:malaprop{}, eng_noun:anarcho - capitalist{}, eng_noun:nonfeline{}, eng_noun:Adjaran{}, eng_noun:antiart{}, eng_noun:nonaromatic{}, eng_noun:multilateralist{}, eng_noun:tetanuran{}, eng_noun:obv.{}, eng_noun:winne{}, eng_noun:nonlibertarian{}, eng_noun:nonneurotic{}, eng_noun:afrotherian{}, eng_noun:pappyshow{}, eng_noun:postop{}, eng_noun:inspiral{}, eng_noun:subgrid{}, eng_noun:multipath{}, eng_noun:intermonsoon{}, eng_noun:screw - off{}, eng_noun:Timonist{}, eng_noun:multiport{}, eng_noun:nonevidence{}, eng_noun:schooly{}, eng_noun:antidiarrhoeal{}, eng_noun:aperitive{}, eng_noun:acrodont{}, eng_noun:Narnian{}, eng_noun:Lacedaemonian{}, eng_noun:firster{}, eng_noun:Warsovian{}, eng_noun:Batavian{}, eng_noun:nonsubordinate{}, eng_noun:Sasanian{}, eng_noun:Teucrian{}, eng_noun:neuroprotectant{}, eng_noun:procoagulant{}, eng_noun:antidiarrheic{}, eng_noun:Wesleyan{}, eng_noun:nondiscipline{}, eng_noun:intercommunity{}, eng_noun:Roumanian{}, eng_noun:varioloid{}, eng_noun:vomitory{}, eng_noun:lacunar{}, eng_noun:catarrhine{}, eng_noun:noninterview{}, eng_noun:multivalve{}, eng_noun:scabious{}, eng_noun:extrinsical{}, eng_noun:bicolour{}, eng_noun:antiherpetic{}, eng_noun:Wordsworthian{}, eng_noun:sweetmeal{}, eng_noun:Canadarian{}, eng_noun:Salvatorian{}, eng_noun:Baghdadian{}, eng_noun:lameo{}, eng_noun:Eskimoan{}, eng_noun:witherward{}, eng_noun:Zaragozan{}, eng_noun:miscellanist{}, eng_noun:pretrigger{}, eng_noun:nonsurvival{}, eng_noun:Spenserian{}, eng_noun:Trifluvian{}, eng_noun:dearn{}, eng_noun:Oxfordian{}, eng_noun:verbile{}, eng_noun:lame - o{}, eng_noun:Lamarckian{}, eng_noun:Ostrobothnian{}, eng_noun:read - through{}, eng_noun:Cushitic{}, eng_noun:Neopythagorean{}, eng_noun:pictorialist{}, eng_noun:foldover{}, eng_noun:ridgeside{}, eng_noun:primatal{}, eng_noun:antigonorrhoeic{}, eng_noun:superciliary{}, eng_noun:inferiour{}, eng_noun:Nepaulese{} }
Exponential growth
eng_noun:Exponential{},
7,304,882
[ 1, 17972, 649, 13334, 451, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 24691, 67, 82, 465, 30, 17972, 649, 2916, 16, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Sources flattened with hardhat v2.3.0 https://hardhat.org // File @openzeppelin/contracts-upgradeable/token/ERC777/[email protected] // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send( address recipient, uint256 amount, bytes calldata data ) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // File @openzeppelin/contracts-upgradeable/token/ERC777/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Recipient.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777RecipientUpgradeable { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // File @openzeppelin/contracts-upgradeable/token/ERC777/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Sender.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777SenderUpgradeable { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected] // 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 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 `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-upgradeable/utils/[email protected] // 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 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 * ==== * * [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 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-upgradeable/proxy/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since 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 !AddressUpgradeable.isContract(address(this)); } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // 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 ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } 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; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC1820Registry.sol) pragma solidity ^0.8.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820RegistryUpgradeable { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer( address account, bytes32 _interfaceHash, address implementer ) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } // File @openzeppelin/contracts-upgradeable/token/ERC777/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC777/ERC777.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC777} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradeable, IERC20Upgradeable { using AddressUpgradeable for address; IERC1820RegistryUpgradeable internal constant _ERC1820_REGISTRY = IERC1820RegistryUpgradeable(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; bytes32 private constant _TOKENS_SENDER_INTERFACE_HASH = keccak256("ERC777TokensSender"); bytes32 private constant _TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient"); // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping(address => mapping(address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ function __ERC777_init( string memory name_, string memory symbol_, address[] memory defaultOperators_ ) internal onlyInitializing { __ERC777_init_unchained(name_, symbol_, defaultOperators_); } function __ERC777_init_unchained( string memory name_, string memory symbol_, address[] memory defaultOperators_ ) internal onlyInitializing { _name = name_; _symbol = symbol_; _defaultOperatorsArray = defaultOperators_; for (uint256 i = 0; i < defaultOperators_.length; i++) { _defaultOperators[defaultOperators_[i]] = true; } // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure virtual returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view virtual override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view virtual override(IERC20Upgradeable, IERC777Upgradeable) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view virtual override(IERC20Upgradeable, IERC777Upgradeable) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send( address recipient, uint256 amount, bytes memory data ) public virtual override { _send(_msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public virtual override { _burn(_msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor(address operator, address tokenHolder) public view virtual override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public virtual override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public virtual override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view virtual override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public virtual override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn( address account, uint256 amount, bytes memory data, bytes memory operatorData ) public virtual override { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view virtual override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public virtual override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom( address holder, address recipient, uint256 amount ) public virtual override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _spendAllowance(holder, spender, amount); _move(spender, holder, recipient, amount, "", ""); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { _mint(account, amount, userData, operatorData, true); } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If `requireReceptionAck` is set to true, and if a send hook is * registered for `account`, the corresponding function will be called with * `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply += amount; _balances[account] += amount; _callTokensReceived(operator, address(0), account, amount, userData, operatorData, requireReceptionAck); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal virtual { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _beforeTokenTransfer(operator, from, address(0), amount); // Update state variables uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC777: burn amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _totalSupply -= amount; emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC777: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * @dev See {ERC20-_approve}. * * Note that accounts cannot have allowance issued by their operators. */ function _approve( address holder, address spender, uint256 value ) internal virtual { require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777SenderUpgradeable(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777RecipientUpgradeable(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } /** * @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, "ERC777: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `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 operator, address from, address to, uint256 amount ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[41] private __gap; } // File @openzeppelin/contracts-upgradeable/access/[email protected] // 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 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 { __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); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/interfaces/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822ProxiableUpgradeable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // File @openzeppelin/contracts-upgradeable/proxy/beacon/[email protected] // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) 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 StorageSlotUpgradeable { 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 } } } // File @openzeppelin/contracts-upgradeable/proxy/ERC1967/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal onlyInitializing { } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @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) private returns (bytes memory) { require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal onlyInitializing { } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Check that the execution is not being performed through a delegate call. This allows a function to be * callable on the implementing contract but not through proxies. */ modifier notDelegated() { require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall"); _; } /** * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the * implementation. It is used to validate that the this implementation remains valid after an upgrade. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier. */ function proxiableUUID() external view virtual override notDelegated returns (bytes32) { return _IMPLEMENTATION_SLOT; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File contracts/konnect-kct-v1.sol // contracts/Token.sol pragma solidity ^0.8.11; contract KonnectKCT_V1 is Initializable, OwnableUpgradeable, ERC777Upgradeable, UUPSUpgradeable { mapping (address => bool) lockedAccounts; function initialize( string memory name, string memory symbol, uint256 initialSupply ) public initializer { __Ownable_init(); __UUPSUpgradeable_init(); __ERC777_init(name, symbol, new address[](0)); _mint(_msgSender(), initialSupply, "", ""); } function setAccountLock(address account, bool isLock) public onlyOwner { lockedAccounts[account] = isLock; } function getAccountLock(address account) public view returns (bool isLock) { return lockedAccounts[account]; } function _beforeTokenTransfer(address operator, address from, address to, uint256 amount) internal virtual override { require(!lockedAccounts[from], 'locked account send prohibited'); require(!lockedAccounts[to], 'locked account receive prohibited'); super._beforeTokenTransfer(operator, from, to, amount); } function _authorizeUpgrade(address newImplementation) internal override onlyOwner {} }
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by {upgradeTo} and {upgradeToAndCall}. Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. ```solidity function _authorizeUpgrade(address) internal override onlyOwner {} ```/* @dev This empty reserved space is put in place to allow future versions to add new variables without shifting down storage in the inheritance chain./ File contracts/konnect-kct-v1.sol contracts/Token.sol
{ mapping (address => bool) lockedAccounts; function initialize( string memory name, string memory symbol, uint256 initialSupply function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } pragma solidity ^0.8.11; contract KonnectKCT_V1 is Initializable, OwnableUpgradeable, ERC777Upgradeable, UUPSUpgradeable ) public initializer { __Ownable_init(); __UUPSUpgradeable_init(); __ERC777_init(name, symbol, new address[](0)); _mint(_msgSender(), initialSupply, "", ""); } function setAccountLock(address account, bool isLock) public onlyOwner { lockedAccounts[account] = isLock; } function getAccountLock(address account) public view returns (bool isLock) { return lockedAccounts[account]; } function _beforeTokenTransfer(address operator, address from, address to, uint256 amount) internal virtual override { require(!lockedAccounts[from], 'locked account send prohibited'); require(!lockedAccounts[to], 'locked account receive prohibited'); super._beforeTokenTransfer(operator, from, to, amount); } {} }
14,750,908
[ 1, 2083, 716, 1410, 15226, 1347, 1375, 3576, 18, 15330, 68, 353, 486, 10799, 358, 8400, 326, 6835, 18, 11782, 635, 288, 15097, 774, 97, 471, 288, 15097, 774, 1876, 1477, 5496, 24773, 1230, 16, 333, 445, 903, 999, 392, 15187, 30, 3860, 18, 4539, 63, 3860, 3325, 65, 9606, 4123, 487, 288, 5460, 429, 17, 3700, 5541, 5496, 31621, 30205, 560, 445, 389, 22488, 10784, 12, 2867, 13, 2713, 3849, 1338, 5541, 2618, 31621, 19, 225, 1220, 1008, 8735, 3476, 353, 1378, 316, 3166, 358, 1699, 3563, 5244, 358, 527, 394, 3152, 2887, 699, 430, 1787, 2588, 2502, 316, 326, 16334, 2687, 18, 19, 1387, 20092, 19, 79, 265, 2517, 17, 79, 299, 17, 90, 21, 18, 18281, 20092, 19, 1345, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 95, 203, 565, 2874, 261, 2867, 516, 1426, 13, 8586, 13971, 31, 203, 203, 565, 445, 4046, 12, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 3273, 16, 203, 3639, 2254, 5034, 2172, 3088, 1283, 203, 565, 445, 389, 22488, 10784, 12, 2867, 394, 13621, 13, 2713, 5024, 31, 203, 203, 565, 2254, 5034, 63, 3361, 65, 3238, 1001, 14048, 31, 203, 97, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 2499, 31, 203, 16351, 1475, 265, 2517, 47, 1268, 67, 58, 21, 353, 7010, 565, 10188, 6934, 16, 203, 565, 14223, 6914, 10784, 429, 16, 203, 565, 4232, 39, 14509, 10784, 429, 16, 203, 565, 587, 3079, 55, 10784, 429, 203, 565, 262, 1071, 12562, 288, 203, 3639, 1001, 5460, 429, 67, 2738, 5621, 203, 3639, 1001, 57, 3079, 55, 10784, 429, 67, 2738, 5621, 203, 3639, 1001, 654, 39, 14509, 67, 2738, 12, 529, 16, 3273, 16, 394, 1758, 8526, 12, 20, 10019, 203, 3639, 389, 81, 474, 24899, 3576, 12021, 9334, 2172, 3088, 1283, 16, 23453, 1408, 1769, 203, 565, 289, 203, 203, 565, 445, 444, 3032, 2531, 12, 2867, 2236, 16, 1426, 353, 2531, 13, 1071, 1338, 5541, 288, 203, 3639, 8586, 13971, 63, 4631, 65, 273, 353, 2531, 31, 203, 565, 289, 203, 203, 565, 445, 23393, 2531, 12, 2867, 2236, 13, 1071, 1476, 1135, 261, 6430, 353, 2531, 13, 288, 203, 3639, 327, 8586, 13971, 63, 4631, 15533, 203, 565, 289, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 2867, 2 ]
./full_match/4/0x76b9a51dae71282EeAbB5F2C9A0365F1b2c707cf/sources/browser/github/tokens/IERC20.sol
* @dev Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address 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); import {SafeERC20} from './SafeERC20.sol'; }
13,309,855
[ 1, 1358, 434, 326, 4232, 39, 3462, 4529, 487, 2553, 316, 326, 512, 2579, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 3462, 288, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 7412, 1265, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 203, 5666, 288, 9890, 654, 39, 3462, 97, 628, 12871, 9890, 654, 39, 3462, 18, 18281, 13506, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.6; pragma experimental ABIEncoderV2; import "./Address.sol"; import "./IACOPool2.sol"; /** * @title ACOPoolFactory * @dev The contract is the implementation for the ACOProxy. */ contract ACOPoolFactory2 { /** * @dev Struct to store the ACO pool basic data. */ struct ACOPoolBasicData { /** * @dev Address of the underlying asset (0x0 for Ethereum). */ address underlying; /** * @dev Address of the strike asset (0x0 for Ethereum). */ address strikeAsset; /** * @dev True if the type is CALL, false for PUT. */ bool isCall; } /** * @dev Emitted when the factory admin address has been changed. * @param previousFactoryAdmin Address of the previous factory admin. * @param newFactoryAdmin Address of the new factory admin. */ event SetFactoryAdmin(address indexed previousFactoryAdmin, address indexed newFactoryAdmin); /** * @dev Emitted when the ACO pool implementation has been changed. * @param previousAcoPoolImplementation Address of the previous ACO pool implementation. * @param previousAcoPoolImplementation Address of the new ACO pool implementation. */ event SetAcoPoolImplementation(address indexed previousAcoPoolImplementation, address indexed newAcoPoolImplementation); /** * @dev Emitted when the ACO factory has been changed. * @param previousAcoFactory Address of the previous ACO factory. * @param newAcoFactory Address of the new ACO factory. */ event SetAcoFactory(address indexed previousAcoFactory, address indexed newAcoFactory); /** * @dev Emitted when the Chi Token has been changed. * @param previousChiToken Address of the previous Chi Token. * @param newChiToken Address of the new Chi Token. */ event SetChiToken(address indexed previousChiToken, address indexed newChiToken); /** * @dev Emitted when the asset converter helper has been changed. * @param previousAssetConverterHelper Address of the previous asset converter helper. * @param newAssetConverterHelper Address of the new asset converter helper. */ event SetAssetConverterHelper(address indexed previousAssetConverterHelper, address indexed newAssetConverterHelper); /** * @dev Emitted when the ACO Pool fee has been changed. * @param previousAcoFee Value of the previous ACO Pool fee. * @param newAcoFee Value of the new ACO Pool fee. */ event SetAcoPoolFee(uint256 indexed previousAcoFee, uint256 indexed newAcoFee); /** * @dev Emitted when the ACO Pool fee destination address has been changed. * @param previousAcoPoolFeeDestination Address of the previous ACO Pool fee destination. * @param newAcoPoolFeeDestination Address of the new ACO Pool fee destination. */ event SetAcoPoolFeeDestination(address indexed previousAcoPoolFeeDestination, address indexed newAcoPoolFeeDestination); /** * @dev Emitted when the ACO Pool penalty percentage on withdrawing open positions has been changed. * @param previousWithdrawOpenPositionPenalty Value of the previous penalty percentage on withdrawing open positions. * @param newWithdrawOpenPositionPenalty Value of the new penalty percentage on withdrawing open positions. */ event SetAcoPoolWithdrawOpenPositionPenalty(uint256 indexed previousWithdrawOpenPositionPenalty, uint256 indexed newWithdrawOpenPositionPenalty); /** * @dev Emitted when the ACO Pool underlying price percentage adjust has been changed. * @param previousUnderlyingPriceAdjustPercentage Value of the previous ACO Pool underlying price percentage adjust. * @param newUnderlyingPriceAdjustPercentage Value of the new ACO Pool underlying price percentage adjust. */ event SetAcoPoolUnderlyingPriceAdjustPercentage(uint256 indexed previousUnderlyingPriceAdjustPercentage, uint256 indexed newUnderlyingPriceAdjustPercentage); /** * @dev Emitted when the ACO Pool maximum number of open ACOs allowed has been changed. * @param previousMaximumOpenAco Value of the previous ACO Pool maximum number of open ACOs allowed. * @param newMaximumOpenAco Value of the new ACO Pool maximum number of open ACOs allowed. */ event SetAcoPoolMaximumOpenAco(uint256 indexed previousMaximumOpenAco, uint256 indexed newMaximumOpenAco); /** * @dev Emitted when permission for an ACO pool admin has been changed. * @param poolAdmin Address of the ACO pool admin. * @param previousPermission The previous permission situation. * @param newPermission The new permission situation. */ event SetAcoPoolPermission(address indexed poolAdmin, bool indexed previousPermission, bool indexed newPermission); /** * @dev Emitted when a strategy permission has been changed. * @param strategy Address of the strategy. * @param previousPermission The previous strategy permission. * @param newPermission The new strategy permission. */ event SetStrategyPermission(address indexed strategy, bool indexed previousPermission, bool newPermission); /** * @dev Emitted when a new ACO pool has been created. * @param underlying Address of the underlying asset (0x0 for Ethereum). * @param strikeAsset Address of the strike asset (0x0 for Ethereum). * @param isCall True if the type is CALL, false for PUT. * @param acoPool Address of the new ACO pool created. * @param acoPoolImplementation Address of the ACO pool implementation used on creation. */ event NewAcoPool(address indexed underlying, address indexed strikeAsset, bool indexed isCall, address acoPool, address acoPoolImplementation); /** * @dev The factory admin address. */ address public factoryAdmin; /** * @dev The ACO pool implementation address. */ address public acoPoolImplementation; /** * @dev The ACO factory address. */ address public acoFactory; /** * @dev The ACO asset converter helper. */ address public assetConverterHelper; /** * @dev The Chi Token address. */ address public chiToken; /** * @dev The ACO Pool fee value. * It is a percentage value (100000 is 100%). */ uint256 public acoPoolFee; /** * @dev The ACO Pool fee destination address. */ address public acoPoolFeeDestination; /** * @dev The ACO Pool penalty percentage on withdrawing open positions. */ uint256 public acoPoolWithdrawOpenPositionPenalty; /** * @dev The ACO Pool underlying price percentage adjust. */ uint256 public acoPoolUnderlyingPriceAdjustPercentage; /** * @dev The ACO Pool maximum number of open ACOs allowed. */ uint256 public acoPoolMaximumOpenAco; /** * @dev The ACO pool admin permissions. */ mapping(address => bool) public poolAdminPermission; /** * @dev The strategies permitted. */ mapping(address => bool) public strategyPermitted; /** * @dev The ACO pool basic data. */ mapping(address => ACOPoolBasicData) public acoPoolBasicData; /** * @dev Modifier to check if the `msg.sender` is the factory admin. * Only factory admin address can execute. */ modifier onlyFactoryAdmin() { require(msg.sender == factoryAdmin, "ACOPoolFactory::onlyFactoryAdmin"); _; } /** * @dev Modifier to check if the `msg.sender` is a pool admin. * Only a pool admin address can execute. */ modifier onlyPoolAdmin() { require(poolAdminPermission[msg.sender], "ACOPoolFactory::onlyPoolAdmin"); _; } /** * @dev Function to initialize the contract. * It should be called through the `data` argument when creating the proxy. * It must be called only once. The first `require` is to guarantee that behavior. * @param _factoryAdmin Address of the factory admin. * @param _acoPoolImplementation Address of the ACO pool implementation. * @param _acoFactory Address of the ACO token factory. * @param _assetConverterHelper Address of the asset converter helper. * @param _chiToken Address of the Chi token. * @param _acoPoolFee ACO pool fee percentage. * @param _acoPoolFeeDestination ACO pool fee destination. * @param _acoPoolWithdrawOpenPositionPenalty ACO pool penalty percentage on withdrawing open positions. * @param _acoPoolUnderlyingPriceAdjustPercentage ACO pool underlying price percentage adjust. * @param _acoPoolMaximumOpenAco ACO pool maximum number of open ACOs allowed. */ function init( address _factoryAdmin, address _acoPoolImplementation, address _acoFactory, address _assetConverterHelper, address _chiToken, uint256 _acoPoolFee, address _acoPoolFeeDestination, uint256 _acoPoolWithdrawOpenPositionPenalty, uint256 _acoPoolUnderlyingPriceAdjustPercentage, uint256 _acoPoolMaximumOpenAco ) public { require(factoryAdmin == address(0) && acoPoolImplementation == address(0), "ACOPoolFactory::init: Contract already initialized."); _setFactoryAdmin(_factoryAdmin); _setAcoPoolImplementation(_acoPoolImplementation); _setAcoFactory(_acoFactory); _setAssetConverterHelper(_assetConverterHelper); _setChiToken(_chiToken); _setAcoPoolFee(_acoPoolFee); _setAcoPoolFeeDestination(_acoPoolFeeDestination); _setAcoPoolWithdrawOpenPositionPenalty(_acoPoolWithdrawOpenPositionPenalty); _setAcoPoolUnderlyingPriceAdjustPercentage(_acoPoolUnderlyingPriceAdjustPercentage); _setAcoPoolMaximumOpenAco(_acoPoolMaximumOpenAco); _setAcoPoolPermission(_factoryAdmin, true); } /** * @dev Function to guarantee that the contract will not receive ether. */ receive() external payable virtual { revert(); } /** * @dev Function to create a new ACO pool. * It deploys a minimal proxy for the ACO pool implementation address. * @param underlying Address of the underlying asset (0x0 for Ethereum). * @param strikeAsset Address of the strike asset (0x0 for Ethereum). * @param isCall True if the type is CALL, false for PUT. * @param tolerancePriceBelow The below tolerance price percentage for ACO tokens. * @param tolerancePriceAbove The above tolerance price percentage for ACO tokens. * @param minExpiration The minimum expiration seconds after the current time for ACO tokens. * @param maxExpiration The maximum expiration seconds after the current time for ACO tokens. * @param strategy Address of the pool strategy to be used. * @param baseVolatility The base volatility for the pool starts. It is a percentage value (100000 is 100%). * @return The created ACO pool address. */ function createAcoPool( address underlying, address strikeAsset, bool isCall, uint256 tolerancePriceBelow, uint256 tolerancePriceAbove, uint256 minExpiration, uint256 maxExpiration, address strategy, uint256 baseVolatility ) onlyFactoryAdmin external virtual returns(address) { _validateStrategy(strategy); return _createAcoPool(IACOPool2.InitData( acoFactory, chiToken, underlying, strikeAsset, isCall, assetConverterHelper, acoPoolFee, acoPoolFeeDestination, acoPoolWithdrawOpenPositionPenalty, acoPoolUnderlyingPriceAdjustPercentage, acoPoolMaximumOpenAco, tolerancePriceBelow, tolerancePriceAbove, minExpiration, maxExpiration, strategy, baseVolatility )); } /** * @dev Function to set the factory admin address. * Only can be called by the factory admin. * @param newFactoryAdmin Address of the new factory admin. */ function setFactoryAdmin(address newFactoryAdmin) onlyFactoryAdmin external virtual { _setFactoryAdmin(newFactoryAdmin); } /** * @dev Function to set the ACO pool implementation address. * Only can be called by the factory admin. * @param newAcoPoolImplementation Address of the new ACO pool implementation. */ function setAcoPoolImplementation(address newAcoPoolImplementation) onlyFactoryAdmin external virtual { _setAcoPoolImplementation(newAcoPoolImplementation); } /** * @dev Function to set the ACO factory address. * Only can be called by the factory admin. * @param newAcoFactory Address of the ACO token factory. */ function setAcoFactory(address newAcoFactory) onlyFactoryAdmin external virtual { _setAcoFactory(newAcoFactory); } /** * @dev Function to set the Chi Token address. * Only can be called by the factory admin. * @param newChiToken Address of the new Chi Token. */ function setChiToken(address newChiToken) onlyFactoryAdmin external virtual { _setChiToken(newChiToken); } /** * @dev Function to set the asset converter helper address. * Only can be called by the factory admin. * @param newAssetConverterHelper Address of the new asset converter helper. */ function setAssetConverterHelper(address newAssetConverterHelper) onlyFactoryAdmin external virtual { _setAssetConverterHelper(newAssetConverterHelper); } /** * @dev Function to set the ACO Pool fee. * Only can be called by the factory admin. * @param newAcoPoolFee Value of the new ACO Pool fee. It is a percentage value (100000 is 100%). */ function setAcoPoolFee(uint256 newAcoPoolFee) onlyFactoryAdmin external virtual { _setAcoPoolFee(newAcoPoolFee); } /** * @dev Function to set the ACO Pool destination address. * Only can be called by the factory admin. * @param newAcoPoolFeeDestination Address of the new ACO Pool destination. */ function setAcoPoolFeeDestination(address newAcoPoolFeeDestination) onlyFactoryAdmin external virtual { _setAcoPoolFeeDestination(newAcoPoolFeeDestination); } /** * @dev Function to set the ACO Pool penalty percentage on withdrawing open positions. * Only can be called by the factory admin. * @param newWithdrawOpenPositionPenalty Value of the new ACO Pool penalty percentage on withdrawing open positions. It is a percentage value (100000 is 100%). */ function setAcoPoolWithdrawOpenPositionPenalty(uint256 newWithdrawOpenPositionPenalty) onlyFactoryAdmin external virtual { _setAcoPoolWithdrawOpenPositionPenalty(newWithdrawOpenPositionPenalty); } /** * @dev Function to set the ACO Pool underlying price percentage adjust. * Only can be called by the factory admin. * @param newUnderlyingPriceAdjustPercentage Value of the new ACO Pool underlying price percentage adjust. It is a percentage value (100000 is 100%). */ function setAcoPoolUnderlyingPriceAdjustPercentage(uint256 newUnderlyingPriceAdjustPercentage) onlyFactoryAdmin external virtual { _setAcoPoolUnderlyingPriceAdjustPercentage(newUnderlyingPriceAdjustPercentage); } /** * @dev Function to set the ACO Pool maximum number of open ACOs allowed. * Only can be called by the factory admin. * @param newMaximumOpenAco Value of the new ACO Pool maximum number of open ACOs allowed. */ function setAcoPoolMaximumOpenAco(uint256 newMaximumOpenAco) onlyFactoryAdmin external virtual { _setAcoPoolMaximumOpenAco(newMaximumOpenAco); } /** * @dev Function to set the ACO pool permission. * Only can be called by the factory admin. * @param poolAdmin Address of the pool admin. * @param newPermission The permission to be set. */ function setAcoPoolPermission(address poolAdmin, bool newPermission) onlyFactoryAdmin external virtual { _setAcoPoolPermission(poolAdmin, newPermission); } /** * @dev Function to set the ACO pool strategies permitted. * Only can be called by the factory admin. * @param strategy Address of the strategy. * @param newPermission The permission to be set. */ function setAcoPoolStrategyPermission(address strategy, bool newPermission) onlyFactoryAdmin external virtual { _setAcoPoolStrategyPermission(strategy, newPermission); } /** * @dev Function to change the ACO pools strategy. * Only can be called by a pool admin. * @param strategy Address of the strategy to be set. * @param acoPools Array of ACO pools addresses. */ function setStrategyOnAcoPool(address strategy, address[] calldata acoPools) onlyPoolAdmin external virtual { _setStrategyOnAcoPool(strategy, acoPools); } /** * @dev Function to change the ACO pools base volatilities. * Only can be called by a pool admin. * @param baseVolatilities Array of the base volatilities to be set. * @param acoPools Array of ACO pools addresses. */ function setBaseVolatilityOnAcoPool(uint256[] calldata baseVolatilities, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolUint256Data(IACOPool2.setBaseVolatility.selector, baseVolatilities, acoPools); } /** * @dev Function to change the ACO pools penalties percentages on withdrawing open positions. * Only can be called by a pool admin. * @param withdrawOpenPositionPenalties Array of the penalties percentages on withdrawing open positions to be set. * @param acoPools Array of ACO pools addresses. */ function setWithdrawOpenPositionPenaltyOnAcoPool(uint256[] calldata withdrawOpenPositionPenalties, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolUint256Data(IACOPool2.setWithdrawOpenPositionPenalty.selector, withdrawOpenPositionPenalties, acoPools); } /** * @dev Function to change the ACO pools underlying prices percentages adjust. * Only can be called by a pool admin. * @param underlyingPriceAdjustPercentages Array of the underlying prices percentages to be set. * @param acoPools Array of ACO pools addresses. */ function setUnderlyingPriceAdjustPercentageOnAcoPool(uint256[] calldata underlyingPriceAdjustPercentages, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolUint256Data(IACOPool2.setUnderlyingPriceAdjustPercentage.selector, underlyingPriceAdjustPercentages, acoPools); } /** * @dev Function to change the ACO pools maximum number of open ACOs allowed. * Only can be called by a pool admin. * @param maximumOpenAcos Array of the maximum number of open ACOs allowed. * @param acoPools Array of ACO pools addresses. */ function setMaximumOpenAcoOnAcoPool(uint256[] calldata maximumOpenAcos, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolUint256Data(IACOPool2.setMaximumOpenAco.selector, maximumOpenAcos, acoPools); } /** * @dev Function to change the ACO pools below tolerance prices percentages. * Only can be called by a pool admin. * @param tolerancePricesBelow Array of the below tolerance prices percentages to be set. * @param acoPools Array of ACO pools addresses. */ function setTolerancePriceBelowOnAcoPool(uint256[] calldata tolerancePricesBelow, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolUint256Data(IACOPool2.setTolerancePriceBelow.selector, tolerancePricesBelow, acoPools); } /** * @dev Function to change the ACO pools above tolerance prices percentages. * Only can be called by a pool admin. * @param tolerancePricesAbove Array of the above tolerance prices percentages to be set. * @param acoPools Array of ACO pools addresses. */ function setTolerancePriceAboveOnAcoPool(uint256[] calldata tolerancePricesAbove, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolUint256Data(IACOPool2.setTolerancePriceAbove.selector, tolerancePricesAbove, acoPools); } /** * @dev Function to change the ACO pools minimum expirations. * Only can be called by a pool admin. * @param minExpirations Array of the minimum expirations. * @param acoPools Array of ACO pools addresses. */ function setMinExpirationOnAcoPool(uint256[] calldata minExpirations, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolUint256Data(IACOPool2.setMinExpiration.selector, minExpirations, acoPools); } /** * @dev Function to change the ACO pools maximum expirations. * Only can be called by a pool admin. * @param maxExpirations Array of the maximum expirations to be set. * @param acoPools Array of ACO pools addresses. */ function setMaxExpirationOnAcoPool(uint256[] calldata maxExpirations, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolUint256Data(IACOPool2.setMaxExpiration.selector, maxExpirations, acoPools); } /** * @dev Function to change the ACO pools fee. * Only can be called by a pool admin. * @param fees Array of the fees. * @param acoPools Array of ACO pools addresses. */ function setFeeOnAcoPool(uint256[] calldata fees, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolUint256Data(IACOPool2.setFee.selector, fees, acoPools); } /** * @dev Function to change the ACO pools fee destinations. * Only can be called by a pool admin. * @param feeDestinations Array of the fee destinations. * @param acoPools Array of ACO pools addresses. */ function setFeeDestinationOnAcoPool(address[] calldata feeDestinations, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolAddressData(IACOPool2.setFeeDestination.selector, feeDestinations, acoPools); } /** * @dev Function to change the ACO pools asset converters. * Only can be called by a pool admin. * @param assetConverters Array of the asset converters. * @param acoPools Array of ACO pools addresses. */ function setAssetConverterOnAcoPool(address[] calldata assetConverters, address[] calldata acoPools) onlyPoolAdmin external virtual { _setAcoPoolAddressData(IACOPool2.setAssetConverter.selector, assetConverters, acoPools); } /** * @dev Function to change the ACO pools ACO creator permission. * Only can be called by a pool admin. * @param acoCreator Address of the ACO creator. * @param permission Permission situation. * @param acoPools Array of ACO pools addresses. */ function setValidAcoCreatorOnAcoPool(address acoCreator, bool permission, address[] calldata acoPools) onlyPoolAdmin external virtual { _setValidAcoCreatorOnAcoPool(acoCreator, permission, acoPools); } /** * @dev Function to withdraw the ACO pools stucked asset. * @param asset Address of the asset. * @param destination Address of the destination. * @param acoPools Array of ACO pools addresses. */ function withdrawStuckAssetOnAcoPool(address asset, address destination, address[] calldata acoPools) onlyPoolAdmin external virtual { _withdrawStuckAssetOnAcoPool(asset, destination, acoPools); } /** * @dev Internal function to set the factory admin address. * @param newFactoryAdmin Address of the new factory admin. */ function _setFactoryAdmin(address newFactoryAdmin) internal virtual { require(newFactoryAdmin != address(0), "ACOPoolFactory::_setFactoryAdmin: Invalid factory admin"); emit SetFactoryAdmin(factoryAdmin, newFactoryAdmin); factoryAdmin = newFactoryAdmin; } /** * @dev Internal function to set the ACO pool implementation address. * @param newAcoPoolImplementation Address of the new ACO pool implementation. */ function _setAcoPoolImplementation(address newAcoPoolImplementation) internal virtual { require(Address.isContract(newAcoPoolImplementation), "ACOPoolFactory::_setAcoPoolImplementation: Invalid ACO pool implementation"); emit SetAcoPoolImplementation(acoPoolImplementation, newAcoPoolImplementation); acoPoolImplementation = newAcoPoolImplementation; } /** * @dev Internal function to set the ACO factory address. * @param newAcoFactory Address of the new ACO token factory. */ function _setAcoFactory(address newAcoFactory) internal virtual { require(Address.isContract(newAcoFactory), "ACOPoolFactory::_setAcoFactory: Invalid ACO factory"); emit SetAcoFactory(acoFactory, newAcoFactory); acoFactory = newAcoFactory; } /** * @dev Internal function to set the asset converter helper address. * @param newAssetConverterHelper Address of the new asset converter helper. */ function _setAssetConverterHelper(address newAssetConverterHelper) internal virtual { require(Address.isContract(newAssetConverterHelper), "ACOPoolFactory::_setAssetConverterHelper: Invalid asset converter helper"); emit SetAssetConverterHelper(assetConverterHelper, newAssetConverterHelper); assetConverterHelper = newAssetConverterHelper; } /** * @dev Internal function to set the Chi Token address. * @param newChiToken Address of the new Chi Token. */ function _setChiToken(address newChiToken) internal virtual { require(Address.isContract(newChiToken), "ACOPoolFactory::_setChiToken: Invalid Chi Token"); emit SetChiToken(chiToken, newChiToken); chiToken = newChiToken; } /** * @dev Internal function to set the ACO Pool fee. * @param newAcoPoolFee Value of the new ACO Pool fee. It is a percentage value (100000 is 100%). */ function _setAcoPoolFee(uint256 newAcoPoolFee) internal virtual { emit SetAcoPoolFee(acoPoolFee, newAcoPoolFee); acoPoolFee = newAcoPoolFee; } /** * @dev Internal function to set the ACO Pool destination address. * @param newAcoPoolFeeDestination Address of the new ACO Pool destination. */ function _setAcoPoolFeeDestination(address newAcoPoolFeeDestination) internal virtual { require(newAcoPoolFeeDestination != address(0), "ACOFactory::_setAcoPoolFeeDestination: Invalid ACO Pool fee destination"); emit SetAcoPoolFeeDestination(acoPoolFeeDestination, newAcoPoolFeeDestination); acoPoolFeeDestination = newAcoPoolFeeDestination; } /** * @dev Internal function to set the ACO Pool penalty percentage on withdrawing open positions. * @param newWithdrawOpenPositionPenalty Value of the new ACO Pool penalty percentage on withdrawing open positions. It is a percentage value (100000 is 100%). */ function _setAcoPoolWithdrawOpenPositionPenalty(uint256 newWithdrawOpenPositionPenalty) internal virtual { emit SetAcoPoolWithdrawOpenPositionPenalty(acoPoolWithdrawOpenPositionPenalty, newWithdrawOpenPositionPenalty); acoPoolWithdrawOpenPositionPenalty = newWithdrawOpenPositionPenalty; } /** * @dev Internal function to set the ACO Pool underlying price percentage adjust. * @param newUnderlyingPriceAdjustPercentage Value of the new ACO Pool underlying price percentage adjust. It is a percentage value (100000 is 100%). */ function _setAcoPoolUnderlyingPriceAdjustPercentage(uint256 newUnderlyingPriceAdjustPercentage) internal virtual { emit SetAcoPoolUnderlyingPriceAdjustPercentage(acoPoolUnderlyingPriceAdjustPercentage, newUnderlyingPriceAdjustPercentage); acoPoolUnderlyingPriceAdjustPercentage = newUnderlyingPriceAdjustPercentage; } /** * @dev Internal function to set the ACO Pool maximum number of open ACOs allowed. * @param newMaximumOpenAco Value of the new ACO Pool maximum number of open ACOs allowed. */ function _setAcoPoolMaximumOpenAco(uint256 newMaximumOpenAco) internal virtual { emit SetAcoPoolMaximumOpenAco(acoPoolMaximumOpenAco, newMaximumOpenAco); acoPoolMaximumOpenAco = newMaximumOpenAco; } /** * @dev Internal function to set the ACO pool permission. * @param poolAdmin Address of the pool admin. * @param newPermission The permission to be set. */ function _setAcoPoolPermission(address poolAdmin, bool newPermission) internal virtual { emit SetAcoPoolPermission(poolAdmin, poolAdminPermission[poolAdmin], newPermission); poolAdminPermission[poolAdmin] = newPermission; } /** * @dev Internal function to set the ACO pool strategies permitted. * @param strategy Address of the strategy. * @param newPermission The permission to be set. */ function _setAcoPoolStrategyPermission(address strategy, bool newPermission) internal virtual { require(Address.isContract(strategy), "ACOPoolFactory::_setAcoPoolStrategy: Invalid strategy"); emit SetStrategyPermission(strategy, strategyPermitted[strategy], newPermission); strategyPermitted[strategy] = newPermission; } /** * @dev Internal function to validate strategy. * @param strategy Address of the strategy. */ function _validateStrategy(address strategy) view internal virtual { require(strategyPermitted[strategy], "ACOPoolFactory::_validateStrategy: Invalid strategy"); } /** * @dev Internal function to change the ACO pools strategy. * @param strategy Address of the strategy to be set. * @param acoPools Array of ACO pools addresses. */ function _setStrategyOnAcoPool(address strategy, address[] memory acoPools) internal virtual { _validateStrategy(strategy); for (uint256 i = 0; i < acoPools.length; ++i) { IACOPool2(acoPools[i]).setStrategy(strategy); } } /** * @dev Internal function to change the ACO pools ACO creator permission. * @param acoCreator Address of the ACO creator. * @param permission Permission situation. * @param acoPools Array of ACO pools addresses. */ function _setValidAcoCreatorOnAcoPool(address acoCreator, bool permission, address[] memory acoPools) internal virtual { for (uint256 i = 0; i < acoPools.length; ++i) { IACOPool2(acoPools[i]).setValidAcoCreator(acoCreator, permission); } } /** * @dev Internal function to withdraw the ACO pools stucked asset. * @param asset Address of the asset. * @param destination Address of the destination. * @param acoPools Array of ACO pools addresses. */ function _withdrawStuckAssetOnAcoPool(address asset, address destination, address[] memory acoPools) internal virtual { for (uint256 i = 0; i < acoPools.length; ++i) { IACOPool2(acoPools[i]).withdrawStuckToken(asset, destination); } } /** * @dev Internal function to change the ACO pools an uint256 data. * @param selector Function selector to be called on the ACO pool. * @param numbers Array of the numbers to be set. * @param acoPools Array of ACO pools addresses. */ function _setAcoPoolUint256Data(bytes4 selector, uint256[] memory numbers, address[] memory acoPools) internal virtual { require(numbers.length == acoPools.length, "ACOPoolFactory::_setAcoPoolUint256Data: Invalid arguments"); for (uint256 i = 0; i < acoPools.length; ++i) { (bool success,) = acoPools[i].call(abi.encodeWithSelector(selector, numbers[i])); require(success, "ACOPoolFactory::_setAcoPoolUint256Data"); } } /** * @dev Internal function to change the ACO pools an address data. * @param selector Function selector to be called on the ACO pool. * @param addresses Array of the addresses to be set. * @param acoPools Array of ACO pools addresses. */ function _setAcoPoolAddressData(bytes4 selector, address[] memory addresses, address[] memory acoPools) internal virtual { require(addresses.length == acoPools.length, "ACOPoolFactory::_setAcoPoolAddressData: Invalid arguments"); for (uint256 i = 0; i < acoPools.length; ++i) { (bool success,) = acoPools[i].call(abi.encodeWithSelector(selector, addresses[i])); require(success, "ACOPoolFactory::_setAcoPoolAddressData"); } } /** * @dev Internal function to create a new ACO pool. * @param initData Data to initialize o ACO Pool. * @return Address of the new minimal proxy deployed for the ACO pool. */ function _createAcoPool(IACOPool2.InitData memory initData) internal virtual returns(address) { address acoPool = _deployAcoPool(initData); acoPoolBasicData[acoPool] = ACOPoolBasicData(initData.underlying, initData.strikeAsset, initData.isCall); emit NewAcoPool( initData.underlying, initData.strikeAsset, initData.isCall, acoPool, acoPoolImplementation ); return acoPool; } /** * @dev Internal function to deploy a minimal proxy using ACO pool implementation. * @param initData Data to initialize o ACO Pool. * @return Address of the new minimal proxy deployed for the ACO pool. */ function _deployAcoPool(IACOPool2.InitData memory initData) internal virtual returns(address) { bytes20 implentationBytes = bytes20(acoPoolImplementation); address proxy; assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), implentationBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) proxy := create(0, clone, 0x37) } IACOPool2(proxy).init(initData); return proxy; } }
* @dev Internal function to validate strategy. @param strategy Address of the strategy./
function _validateStrategy(address strategy) view internal virtual { require(strategyPermitted[strategy], "ACOPoolFactory::_validateStrategy: Invalid strategy"); }
128,897
[ 1, 3061, 445, 358, 1954, 6252, 18, 225, 6252, 5267, 434, 326, 6252, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5662, 4525, 12, 2867, 6252, 13, 1476, 2713, 5024, 288, 203, 3639, 2583, 12, 14914, 31465, 63, 14914, 6487, 315, 2226, 51, 2864, 1733, 2866, 67, 5662, 4525, 30, 1962, 6252, 8863, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x35c556d2700CE48fC3D3C1736B28bd15dC5cFC59/sources/TrueRatingAgency.sol
* @dev Only loans that have been funded/
modifier onlyFundedLoans(address id) { require(status(id) >= LoanStatus.Running, "TrueRatingAgency: Loan was not funded"); _; }
3,990,263
[ 1, 3386, 437, 634, 716, 1240, 2118, 9831, 785, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 42, 12254, 1504, 634, 12, 2867, 612, 13, 288, 203, 3639, 2583, 12, 2327, 12, 350, 13, 1545, 3176, 304, 1482, 18, 7051, 16, 315, 5510, 20388, 2577, 2075, 30, 3176, 304, 1703, 486, 9831, 785, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.16; import "../base/Managed.sol"; import "./state/AuthereumEnsResolverState.sol"; /** * @title AuthereumEnsResolver * @author Authereum Labs, Inc. * @dev Authereum implementation of a Resolver. */ contract AuthereumEnsResolver is Managed, AuthereumEnsResolverState { string constant public authereumEnsResolverVersion = "2019111500"; bytes4 constant private INTERFACE_META_ID = 0x01ffc9a7; bytes4 constant private ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant private NAME_INTERFACE_ID = 0x691f3431; bytes4 constant private TEXT_INTERFACE_ID = 0x59d1d43c; bytes4 constant private CONTENT_HASH_INTERFACE_ID = 0xbc1c58d1; event AddrChanged(bytes32 indexed node, address a); event NameChanged(bytes32 indexed node, string name); event TextChanged(bytes32 indexed node, string indexed indexedKey, string key, string value); event ContenthashChanged(bytes32 indexed node, bytes hash); /// @dev Constructor /// @param _ensAddr The ENS registrar contract /// @param _timelockContract Authereum timelock contract address constructor(EnsRegistry _ensAddr, address _timelockContract) public { ens = _ensAddr; timelockContract = _timelockContract; } /** * Setters */ /// @dev Sets the address associated with an ENS node /// @notice May only be called by the owner of that node in the ENS registry /// @param _node The node to update /// @param _addr The address to set function setAddr(bytes32 _node, address _addr) public onlyManager { addrs[_node]= _addr; emit AddrChanged(_node, _addr); } /// @dev Sets the name associated with an ENS node, for reverse records /// @notice May only be called by the owner of that node in the ENS registry /// @param _node The node to update /// @param _name The name to set function setName(bytes32 _node, string memory _name) public onlyManager { names[_node] = _name; emit NameChanged(_node, _name); } /// @dev Sets the text data associated with an ENS node and key /// @notice May only be called by the owner of that node in the ENS registry /// @param node The node to update /// @param key The key to set /// @param value The text data value to set function setText(bytes32 node, string memory key, string memory value) public onlyManager { texts[node][key] = value; emit TextChanged(node, key, key, value); } /// @dev Sets the contenthash associated with an ENS node /// @notice May only be called by the owner of that node in the ENS registry /// @param node The node to update /// @param hash The contenthash to set function setContenthash(bytes32 node, bytes memory hash) public onlyManager { hashes[node] = hash; emit ContenthashChanged(node, hash); } /** * Getters */ /// @dev Returns the address associated with an ENS node /// @param _node The ENS node to query /// @return The associated address function addr(bytes32 _node) public view returns (address) { return addrs[_node]; } /// @dev Returns the name associated with an ENS node, for reverse records /// @notice Defined in EIP181 /// @param _node The ENS node to query /// @return The associated name function name(bytes32 _node) public view returns (string memory) { return names[_node]; } /// @dev Returns the text data associated with an ENS node and key /// @param node The ENS node to query /// @param key The text data key to query ///@return The associated text data function text(bytes32 node, string memory key) public view returns (string memory) { return texts[node][key]; } /// @dev Returns the contenthash associated with an ENS node /// @param node The ENS node to query /// @return The associated contenthash function contenthash(bytes32 node) public view returns (bytes memory) { return hashes[node]; } /// @dev Returns true if the resolver implements the interface specified by the provided hash /// @param _interfaceID The ID of the interface to check for /// @return True if the contract implements the requested interface function supportsInterface(bytes4 _interfaceID) public pure returns (bool) { return _interfaceID == INTERFACE_META_ID || _interfaceID == ADDR_INTERFACE_ID || _interfaceID == NAME_INTERFACE_ID || _interfaceID == TEXT_INTERFACE_ID || _interfaceID == CONTENT_HASH_INTERFACE_ID; } }
@dev Returns the text data associated with an ENS node and key @param node The ENS node to query @param key The text data key to query@return The associated text data
function text(bytes32 node, string memory key) public view returns (string memory) { return texts[node][key]; }
7,241,286
[ 1, 1356, 326, 977, 501, 3627, 598, 392, 512, 3156, 756, 471, 498, 225, 756, 1021, 512, 3156, 756, 358, 843, 225, 498, 1021, 977, 501, 498, 358, 843, 2463, 1021, 3627, 977, 501, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 977, 12, 3890, 1578, 756, 16, 533, 3778, 498, 13, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 15219, 63, 2159, 6362, 856, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4 <0.6.0; import "./Managed.sol"; import "./IMarketPlace.sol"; // TODO: limit the number of offers to 256 contract MarketPlace is IMarketPlace, Managed { modifier inLimits(address _componentAddress) { require(_componentToOffers[_componentAddress].length < 256, "Exceded offers size"); _; } modifier isNotSubmited(address _componentAddress) { require(!_addressToIndex[_componentAddress].isSubmited, "Component was already submited"); _; } modifier validOfferIndex(address _componentAddress, uint256 _index) { require(_componentToOffers[_componentAddress].length > _index, "Not a valid Offer index!"); _; } modifier amountBiggerThen(uint256 _amount, uint256 _threshold) { require(_amount >= _threshold, "Amount is smaller then the threshold"); _; } constructor(address _manager) Managed(_manager) public {} address[] private _components; mapping(address => IndexStorage) private _addressToIndex; mapping(address => address[]) private _ownerToComponents; mapping(address => Offer[]) _componentToOffers; function submitForSale(address _owner, address _componentAddress) external onlyManager isNotSubmited(_componentAddress) returns (bool) { uint256 _indexInComponents = _components.push(_componentAddress) - 1; uint256 _indexInOwnerComponents = _ownerToComponents[_owner].push(_componentAddress) - 1; _addressToIndex[_componentAddress] = IndexStorage({ indexInOwnerComponents: _indexInOwnerComponents, indexInComponents: _indexInComponents, isSubmited: true }); emit ComponentWasSubmitedForSale(_componentAddress); return true; } function removeFromSale( address _owner, address _componentAddress ) external onlyManager returns (bool) { require(_performStorageCleanup(_owner, _componentAddress), "Storage cleanup failed!"); emit ComponentWasRemovedFromSale(_componentAddress); return true; } function addOffer( address _sender, address _componentAddress, uint256 _amount ) external onlyManager inLimits(_componentAddress) amountBiggerThen(_amount, 0) // can be changed to bigger then price { _componentToOffers[_componentAddress].push(Offer({ amountOfTokens: _amount, senderAddress: _sender })); emit NewOffer(_sender, _componentAddress, _amount); } function removeOffer( address _sender, address _componentAddress, uint256 _offerIndex ) external onlyManager returns(bool) { Offer memory offer = _componentToOffers[_componentAddress][_offerIndex]; require(_sender == offer.senderAddress, "Not the offer owner."); uint256 _last = _componentToOffers[_componentAddress].length - 1; _componentToOffers[_componentAddress][_offerIndex] = _componentToOffers[_componentAddress][_last]; delete _componentToOffers[_componentAddress][_last]; _componentToOffers[_componentAddress].length--; emit OfferRemoved( offer.senderAddress, _componentAddress, offer.amountOfTokens ); return true; } function acceptOffer( address _owner, address _componentAddress, uint256 _offerIndex ) external onlyManager validOfferIndex(_componentAddress, _offerIndex) returns (address, uint256) { Offer memory offer = _componentToOffers[_componentAddress][_offerIndex]; require(_performStorageCleanup(_owner, _componentAddress), "Storage cleanup failed!"); emit OfferAccepted( offer.senderAddress, _componentAddress, offer.amountOfTokens ); return (offer.senderAddress, offer.amountOfTokens); } function rejectOffer( address _componentAddress, uint256 _offerIndex ) external onlyManager validOfferIndex(_componentAddress, _offerIndex) returns (bool) { uint256 _indexOfLastOffer = _componentToOffers[_componentAddress].length - 1; Offer memory offer = _componentToOffers[_componentAddress][_offerIndex]; _componentToOffers[_componentAddress][_offerIndex] = _componentToOffers[_componentAddress][_indexOfLastOffer]; delete _componentToOffers[_componentAddress][_indexOfLastOffer]; _componentToOffers[_componentAddress].length--; emit OfferRejected( offer.senderAddress, _componentAddress, offer.amountOfTokens ); return true; } function _performStorageCleanup( address _owner, address _componentAddress ) private returns(bool) { uint256 _indexInComponents = _addressToIndex[_componentAddress].indexInComponents; uint256 _lastIndexInComponents = _components.length - 1; uint256 _indexInOwnerComponents = _addressToIndex[_componentAddress].indexInOwnerComponents; uint256 _lastIndexInOwnerComponents = _ownerToComponents[_owner].length - 1; address _lastComponentAddress = _components[_lastIndexInComponents]; _components[_indexInComponents] = _components[_lastIndexInComponents]; delete _components[_lastIndexInComponents]; _components.length--; _ownerToComponents[_owner][_indexInOwnerComponents] = _ownerToComponents[_owner][_lastIndexInOwnerComponents]; delete _ownerToComponents[_owner][_lastIndexInOwnerComponents]; _ownerToComponents[_owner].length--; delete _addressToIndex[_componentAddress]; if (_lastComponentAddress != _componentAddress) { _addressToIndex[_lastComponentAddress] = IndexStorage({ indexInOwnerComponents: _indexInOwnerComponents, indexInComponents: _indexInComponents, isSubmited: true }); } if (_componentToOffers[_componentAddress].length > 0) { delete _componentToOffers[_componentAddress]; } return true; } function getComponentsSubmitedForSale() external view returns (address[] memory) { return _components; } function getOwnerComonentsSubmitedForSale( address _owner ) external view returns(address[] memory) { return _ownerToComponents[_owner]; } function getComponentOfferByIndex( address _componentAddress, uint256 _index ) external view validOfferIndex(_componentAddress, _index) returns (uint256, address) { return ( _componentToOffers[_componentAddress][_index].amountOfTokens, _componentToOffers[_componentAddress][_index].senderAddress ); } function getComponentOfferSize( address _componentAddress ) external view returns(uint256) { return _componentToOffers[_componentAddress].length; } function getIndexByAddress(address _contractAddress) external view returns (uint256, uint256, bool) { return ( _addressToIndex[_contractAddress].indexInComponents, _addressToIndex[_contractAddress].indexInOwnerComponents, _addressToIndex[_contractAddress].isSubmited ); } }
TODO: limit the number of offers to 256
contract MarketPlace is IMarketPlace, Managed { modifier inLimits(address _componentAddress) { require(_componentToOffers[_componentAddress].length < 256, "Exceded offers size"); _; } modifier isNotSubmited(address _componentAddress) { require(!_addressToIndex[_componentAddress].isSubmited, "Component was already submited"); _; } modifier validOfferIndex(address _componentAddress, uint256 _index) { require(_componentToOffers[_componentAddress].length > _index, "Not a valid Offer index!"); _; } modifier amountBiggerThen(uint256 _amount, uint256 _threshold) { require(_amount >= _threshold, "Amount is smaller then the threshold"); _; } address[] private _components; mapping(address => IndexStorage) private _addressToIndex; mapping(address => address[]) private _ownerToComponents; mapping(address => Offer[]) _componentToOffers; constructor(address _manager) Managed(_manager) public {} function submitForSale(address _owner, address _componentAddress) external onlyManager isNotSubmited(_componentAddress) returns (bool) { uint256 _indexInComponents = _components.push(_componentAddress) - 1; uint256 _indexInOwnerComponents = _ownerToComponents[_owner].push(_componentAddress) - 1; _addressToIndex[_componentAddress] = IndexStorage({ indexInOwnerComponents: _indexInOwnerComponents, indexInComponents: _indexInComponents, isSubmited: true }); emit ComponentWasSubmitedForSale(_componentAddress); return true; } function submitForSale(address _owner, address _componentAddress) external onlyManager isNotSubmited(_componentAddress) returns (bool) { uint256 _indexInComponents = _components.push(_componentAddress) - 1; uint256 _indexInOwnerComponents = _ownerToComponents[_owner].push(_componentAddress) - 1; _addressToIndex[_componentAddress] = IndexStorage({ indexInOwnerComponents: _indexInOwnerComponents, indexInComponents: _indexInComponents, isSubmited: true }); emit ComponentWasSubmitedForSale(_componentAddress); return true; } function removeFromSale( address _owner, address _componentAddress ) external onlyManager returns (bool) { require(_performStorageCleanup(_owner, _componentAddress), "Storage cleanup failed!"); emit ComponentWasRemovedFromSale(_componentAddress); return true; } function addOffer( address _sender, address _componentAddress, uint256 _amount ) external onlyManager inLimits(_componentAddress) { _componentToOffers[_componentAddress].push(Offer({ amountOfTokens: _amount, senderAddress: _sender })); emit NewOffer(_sender, _componentAddress, _amount); } function addOffer( address _sender, address _componentAddress, uint256 _amount ) external onlyManager inLimits(_componentAddress) { _componentToOffers[_componentAddress].push(Offer({ amountOfTokens: _amount, senderAddress: _sender })); emit NewOffer(_sender, _componentAddress, _amount); } function removeOffer( address _sender, address _componentAddress, uint256 _offerIndex ) external onlyManager returns(bool) { Offer memory offer = _componentToOffers[_componentAddress][_offerIndex]; require(_sender == offer.senderAddress, "Not the offer owner."); uint256 _last = _componentToOffers[_componentAddress].length - 1; _componentToOffers[_componentAddress][_offerIndex] = _componentToOffers[_componentAddress][_last]; delete _componentToOffers[_componentAddress][_last]; _componentToOffers[_componentAddress].length--; emit OfferRemoved( offer.senderAddress, _componentAddress, offer.amountOfTokens ); return true; } function acceptOffer( address _owner, address _componentAddress, uint256 _offerIndex ) external onlyManager validOfferIndex(_componentAddress, _offerIndex) returns (address, uint256) { Offer memory offer = _componentToOffers[_componentAddress][_offerIndex]; require(_performStorageCleanup(_owner, _componentAddress), "Storage cleanup failed!"); emit OfferAccepted( offer.senderAddress, _componentAddress, offer.amountOfTokens ); return (offer.senderAddress, offer.amountOfTokens); } function rejectOffer( address _componentAddress, uint256 _offerIndex ) external onlyManager validOfferIndex(_componentAddress, _offerIndex) returns (bool) { uint256 _indexOfLastOffer = _componentToOffers[_componentAddress].length - 1; Offer memory offer = _componentToOffers[_componentAddress][_offerIndex]; _componentToOffers[_componentAddress][_offerIndex] = _componentToOffers[_componentAddress][_indexOfLastOffer]; delete _componentToOffers[_componentAddress][_indexOfLastOffer]; _componentToOffers[_componentAddress].length--; emit OfferRejected( offer.senderAddress, _componentAddress, offer.amountOfTokens ); return true; } function _performStorageCleanup( address _owner, address _componentAddress ) private returns(bool) { uint256 _indexInComponents = _addressToIndex[_componentAddress].indexInComponents; uint256 _lastIndexInComponents = _components.length - 1; uint256 _indexInOwnerComponents = _addressToIndex[_componentAddress].indexInOwnerComponents; uint256 _lastIndexInOwnerComponents = _ownerToComponents[_owner].length - 1; address _lastComponentAddress = _components[_lastIndexInComponents]; _components[_indexInComponents] = _components[_lastIndexInComponents]; delete _components[_lastIndexInComponents]; _components.length--; _ownerToComponents[_owner][_indexInOwnerComponents] = _ownerToComponents[_owner][_lastIndexInOwnerComponents]; delete _ownerToComponents[_owner][_lastIndexInOwnerComponents]; _ownerToComponents[_owner].length--; delete _addressToIndex[_componentAddress]; if (_lastComponentAddress != _componentAddress) { _addressToIndex[_lastComponentAddress] = IndexStorage({ indexInOwnerComponents: _indexInOwnerComponents, indexInComponents: _indexInComponents, isSubmited: true }); } if (_componentToOffers[_componentAddress].length > 0) { delete _componentToOffers[_componentAddress]; } return true; } function _performStorageCleanup( address _owner, address _componentAddress ) private returns(bool) { uint256 _indexInComponents = _addressToIndex[_componentAddress].indexInComponents; uint256 _lastIndexInComponents = _components.length - 1; uint256 _indexInOwnerComponents = _addressToIndex[_componentAddress].indexInOwnerComponents; uint256 _lastIndexInOwnerComponents = _ownerToComponents[_owner].length - 1; address _lastComponentAddress = _components[_lastIndexInComponents]; _components[_indexInComponents] = _components[_lastIndexInComponents]; delete _components[_lastIndexInComponents]; _components.length--; _ownerToComponents[_owner][_indexInOwnerComponents] = _ownerToComponents[_owner][_lastIndexInOwnerComponents]; delete _ownerToComponents[_owner][_lastIndexInOwnerComponents]; _ownerToComponents[_owner].length--; delete _addressToIndex[_componentAddress]; if (_lastComponentAddress != _componentAddress) { _addressToIndex[_lastComponentAddress] = IndexStorage({ indexInOwnerComponents: _indexInOwnerComponents, indexInComponents: _indexInComponents, isSubmited: true }); } if (_componentToOffers[_componentAddress].length > 0) { delete _componentToOffers[_componentAddress]; } return true; } function _performStorageCleanup( address _owner, address _componentAddress ) private returns(bool) { uint256 _indexInComponents = _addressToIndex[_componentAddress].indexInComponents; uint256 _lastIndexInComponents = _components.length - 1; uint256 _indexInOwnerComponents = _addressToIndex[_componentAddress].indexInOwnerComponents; uint256 _lastIndexInOwnerComponents = _ownerToComponents[_owner].length - 1; address _lastComponentAddress = _components[_lastIndexInComponents]; _components[_indexInComponents] = _components[_lastIndexInComponents]; delete _components[_lastIndexInComponents]; _components.length--; _ownerToComponents[_owner][_indexInOwnerComponents] = _ownerToComponents[_owner][_lastIndexInOwnerComponents]; delete _ownerToComponents[_owner][_lastIndexInOwnerComponents]; _ownerToComponents[_owner].length--; delete _addressToIndex[_componentAddress]; if (_lastComponentAddress != _componentAddress) { _addressToIndex[_lastComponentAddress] = IndexStorage({ indexInOwnerComponents: _indexInOwnerComponents, indexInComponents: _indexInComponents, isSubmited: true }); } if (_componentToOffers[_componentAddress].length > 0) { delete _componentToOffers[_componentAddress]; } return true; } function _performStorageCleanup( address _owner, address _componentAddress ) private returns(bool) { uint256 _indexInComponents = _addressToIndex[_componentAddress].indexInComponents; uint256 _lastIndexInComponents = _components.length - 1; uint256 _indexInOwnerComponents = _addressToIndex[_componentAddress].indexInOwnerComponents; uint256 _lastIndexInOwnerComponents = _ownerToComponents[_owner].length - 1; address _lastComponentAddress = _components[_lastIndexInComponents]; _components[_indexInComponents] = _components[_lastIndexInComponents]; delete _components[_lastIndexInComponents]; _components.length--; _ownerToComponents[_owner][_indexInOwnerComponents] = _ownerToComponents[_owner][_lastIndexInOwnerComponents]; delete _ownerToComponents[_owner][_lastIndexInOwnerComponents]; _ownerToComponents[_owner].length--; delete _addressToIndex[_componentAddress]; if (_lastComponentAddress != _componentAddress) { _addressToIndex[_lastComponentAddress] = IndexStorage({ indexInOwnerComponents: _indexInOwnerComponents, indexInComponents: _indexInComponents, isSubmited: true }); } if (_componentToOffers[_componentAddress].length > 0) { delete _componentToOffers[_componentAddress]; } return true; } function getComponentsSubmitedForSale() external view returns (address[] memory) { return _components; } function getOwnerComonentsSubmitedForSale( address _owner ) external view returns(address[] memory) { return _ownerToComponents[_owner]; } function getComponentOfferByIndex( address _componentAddress, uint256 _index ) external view validOfferIndex(_componentAddress, _index) returns (uint256, address) { return ( _componentToOffers[_componentAddress][_index].amountOfTokens, _componentToOffers[_componentAddress][_index].senderAddress ); } function getComponentOfferSize( address _componentAddress ) external view returns(uint256) { return _componentToOffers[_componentAddress].length; } function getIndexByAddress(address _contractAddress) external view returns (uint256, uint256, bool) { return ( _addressToIndex[_contractAddress].indexInComponents, _addressToIndex[_contractAddress].indexInOwnerComponents, _addressToIndex[_contractAddress].isSubmited ); } }
1,765,445
[ 1, 6241, 30, 1800, 326, 1300, 434, 28641, 358, 8303, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6622, 278, 6029, 353, 467, 3882, 278, 6029, 16, 10024, 288, 203, 203, 565, 9606, 316, 12768, 12, 2867, 389, 4652, 1887, 13, 288, 203, 3639, 2583, 24899, 4652, 774, 7210, 414, 63, 67, 4652, 1887, 8009, 2469, 411, 8303, 16, 315, 424, 311, 785, 28641, 963, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 8827, 11620, 329, 12, 2867, 389, 4652, 1887, 13, 288, 203, 3639, 2583, 12, 5, 67, 2867, 19418, 63, 67, 4652, 1887, 8009, 291, 11620, 329, 16, 315, 1841, 1703, 1818, 4879, 329, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 923, 10513, 1016, 12, 2867, 389, 4652, 1887, 16, 2254, 5034, 389, 1615, 13, 288, 203, 3639, 2583, 24899, 4652, 774, 7210, 414, 63, 67, 4652, 1887, 8009, 2469, 405, 389, 1615, 16, 315, 1248, 279, 923, 25753, 770, 4442, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 3844, 38, 2318, 20112, 12, 11890, 5034, 389, 8949, 16, 2254, 5034, 389, 8699, 13, 288, 203, 3639, 2583, 24899, 8949, 1545, 389, 8699, 16, 315, 6275, 353, 10648, 1508, 326, 5573, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 203, 565, 1758, 8526, 3238, 389, 8119, 31, 203, 565, 2874, 12, 2867, 516, 3340, 3245, 13, 3238, 389, 2867, 19418, 31, 203, 565, 2874, 12, 2867, 516, 1758, 63, 5717, 3238, 389, 8443, 774, 7171, 31, 203, 203, 565, 2874, 12, 2867, 516, 25753, 63, 5717, 389, 4652, 774, 7210, 414, 31, 203, 203, 2 ]
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; contract AccessControl { event GrantRole(bytes32 indexed role, address indexed addr); event RevokeRole(bytes32 indexed role, address indexed addr); mapping(bytes32 => mapping(address => bool)) public hasRole; modifier onlyAuthorized(bytes32 _role) { require(hasRole[_role][msg.sender], "!authorized"); _; } function _grantRole(bytes32 _role, address _addr) internal { require(_addr != address(0), "address = zero"); hasRole[_role][_addr] = true; emit GrantRole(_role, _addr); } function _revokeRole(bytes32 _role, address _addr) internal { require(_addr != address(0), "address = zero"); hasRole[_role][_addr] = false; emit RevokeRole(_role, _addr); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "@openzeppelin/contracts/math/Math.sol"; import "./interfaces/GasToken.sol"; import "./AccessControl.sol"; contract GasRelayer is AccessControl { bytes32 public constant GAS_TOKEN_USER_ROLE = keccak256(abi.encodePacked("GAS_TOKEN_USER")); address public admin; address public gasToken; constructor(address _gasToken) public { require(_gasToken != address(0), "gas token = zero address"); admin = msg.sender; gasToken = _gasToken; _grantRole(GAS_TOKEN_USER_ROLE, admin); } modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } // @dev use CHI token from 1inch to burn gas token // https://medium.com/@1inch.exchange/1inch-introduces-chi-gastoken-d0bd5bb0f92b modifier useChi(uint _max) { uint gasStart = gasleft(); _; uint gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length; if (_max > 0) { GasToken(gasToken).freeUpTo(Math.min(_max, (gasSpent + 14154) / 41947)); } } function setAdmin(address _admin) external onlyAdmin { require(_admin != address(0), "admin = zero address"); admin = _admin; } function authorized(address _addr) external view returns (bool) { return hasRole[GAS_TOKEN_USER_ROLE][_addr]; } function authorize(address _addr) external onlyAdmin { _grantRole(GAS_TOKEN_USER_ROLE, _addr); } function unauthorize(address _addr) external onlyAdmin { _revokeRole(GAS_TOKEN_USER_ROLE, _addr); } function setGasToken(address _gasToken) external onlyAdmin { require(_gasToken != address(0), "gas token = zero address"); gasToken = _gasToken; } function mintGasToken(uint _amount) external { GasToken(gasToken).mint(_amount); } function transferGasToken(address _to, uint _amount) external onlyAdmin { GasToken(gasToken).transfer(_to, _amount); } function relayTx( address _to, bytes calldata _data, uint _maxGasToken ) external onlyAuthorized(GAS_TOKEN_USER_ROLE) useChi(_maxGasToken) { (bool success, ) = _to.call(_data); require(success, "relay failed"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface GasToken { function mint(uint amount) external; function free(uint amount) external returns (bool); function freeUpTo(uint amount) external returns (uint); // ERC20 function transfer(address _to, uint _amount) external returns (bool); function balanceOf(address account) external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../interfaces/GasToken.sol"; /* solium-disable */ contract MockGasToken is GasToken { // test helpers uint public _mintAmount_; uint public _freeAmount_; uint public _freeUpToAmount_; address public _transferTo_; uint public _transferAmount_; function mint(uint _amount) external override { _mintAmount_ = _amount; } function free(uint _amount) external override returns (bool) { _freeAmount_ = _amount; return true; } function freeUpTo(uint _amount) external override returns (uint) { _freeUpToAmount_ = _amount; return 0; } function transfer(address _to, uint _amount) external override returns (bool) { _transferTo_ = _to; _transferAmount_ = _amount; return true; } function balanceOf(address) external view override returns (uint) { return 0; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./protocol/IController.sol"; import "./protocol/IVault.sol"; import "./protocol/IStrategy.sol"; import "./AccessControl.sol"; contract Controller is IController, AccessControl { using SafeMath for uint; bytes32 public constant override ADMIN_ROLE = keccak256(abi.encodePacked("ADMIN")); bytes32 public constant override HARVESTER_ROLE = keccak256(abi.encodePacked("HARVESTER")); address public override admin; address public override treasury; constructor(address _treasury) public { require(_treasury != address(0), "treasury = zero address"); admin = msg.sender; treasury = _treasury; _grantRole(ADMIN_ROLE, admin); _grantRole(HARVESTER_ROLE, admin); } modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } modifier isCurrentStrategy(address _strategy) { address vault = IStrategy(_strategy).vault(); /* Check that _strategy is the current strategy used by the vault. */ require(IVault(vault).strategy() == _strategy, "!strategy"); _; } function setAdmin(address _admin) external override onlyAdmin { require(_admin != address(0), "admin = zero address"); _revokeRole(ADMIN_ROLE, admin); _revokeRole(HARVESTER_ROLE, admin); _grantRole(ADMIN_ROLE, _admin); _grantRole(HARVESTER_ROLE, _admin); admin = _admin; } function setTreasury(address _treasury) external override onlyAdmin { require(_treasury != address(0), "treasury = zero address"); treasury = _treasury; } function grantRole(bytes32 _role, address _addr) external override onlyAdmin { require(_role == ADMIN_ROLE || _role == HARVESTER_ROLE, "invalid role"); _grantRole(_role, _addr); } function revokeRole(bytes32 _role, address _addr) external override onlyAdmin { require(_role == ADMIN_ROLE || _role == HARVESTER_ROLE, "invalid role"); _revokeRole(_role, _addr); } function setStrategy( address _vault, address _strategy, uint _min ) external override onlyAuthorized(ADMIN_ROLE) { IVault(_vault).setStrategy(_strategy, _min); } function invest(address _vault) external override onlyAuthorized(HARVESTER_ROLE) { IVault(_vault).invest(); } function harvest(address _strategy) external override isCurrentStrategy(_strategy) onlyAuthorized(HARVESTER_ROLE) { IStrategy(_strategy).harvest(); } function skim(address _strategy) external override isCurrentStrategy(_strategy) onlyAuthorized(HARVESTER_ROLE) { IStrategy(_strategy).skim(); } modifier checkWithdraw(address _strategy, uint _min) { address vault = IStrategy(_strategy).vault(); address token = IVault(vault).token(); uint balBefore = IERC20(token).balanceOf(vault); _; uint balAfter = IERC20(token).balanceOf(vault); require(balAfter.sub(balBefore) >= _min, "withdraw < min"); } function withdraw( address _strategy, uint _amount, uint _min ) external override isCurrentStrategy(_strategy) onlyAuthorized(HARVESTER_ROLE) checkWithdraw(_strategy, _min) { IStrategy(_strategy).withdraw(_amount); } function withdrawAll(address _strategy, uint _min) external override isCurrentStrategy(_strategy) onlyAuthorized(HARVESTER_ROLE) checkWithdraw(_strategy, _min) { IStrategy(_strategy).withdrawAll(); } function exit(address _strategy, uint _min) external override isCurrentStrategy(_strategy) onlyAuthorized(ADMIN_ROLE) checkWithdraw(_strategy, _min) { IStrategy(_strategy).exit(); } } // 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface IController { function ADMIN_ROLE() external view returns (bytes32); function HARVESTER_ROLE() external view returns (bytes32); function admin() external view returns (address); function treasury() external view returns (address); function setAdmin(address _admin) external; function setTreasury(address _treasury) external; function grantRole(bytes32 _role, address _addr) external; function revokeRole(bytes32 _role, address _addr) external; /* @notice Set strategy for vault @param _vault Address of vault @param _strategy Address of strategy @param _min Minimum undelying token current strategy must return. Prevents slippage */ function setStrategy( address _vault, address _strategy, uint _min ) external; // calls to strategy /* @notice Invest token in vault into strategy @param _vault Address of vault */ function invest(address _vault) external; function harvest(address _strategy) external; function skim(address _strategy) external; /* @notice Withdraw from strategy to vault @param _strategy Address of strategy @param _amount Amount of underlying token to withdraw @param _min Minimum amount of underlying token to withdraw */ function withdraw( address _strategy, uint _amount, uint _min ) external; /* @notice Withdraw all from strategy to vault @param _strategy Address of strategy @param _min Minimum amount of underlying token to withdraw */ function withdrawAll(address _strategy, uint _min) external; /* @notice Exit from strategy @param _strategy Address of strategy @param _min Minimum amount of underlying token to withdraw */ function exit(address _strategy, uint _min) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface IVault { function admin() external view returns (address); function controller() external view returns (address); function timeLock() external view returns (address); function token() external view returns (address); function strategy() external view returns (address); function strategies(address _strategy) external view returns (bool); function reserveMin() external view returns (uint); function withdrawFee() external view returns (uint); function paused() external view returns (bool); function whitelist(address _addr) external view returns (bool); function setWhitelist(address _addr, bool _approve) external; function setAdmin(address _admin) external; function setController(address _controller) external; function setTimeLock(address _timeLock) external; function setPause(bool _paused) external; function setReserveMin(uint _reserveMin) external; function setWithdrawFee(uint _fee) external; /* @notice Returns the amount of token in the vault */ function balanceInVault() external view returns (uint); /* @notice Returns the estimate amount of token in strategy @dev Output may vary depending on price of liquidity provider token where the underlying token is invested */ function balanceInStrategy() external view returns (uint); /* @notice Returns amount of tokens invested strategy */ function totalDebtInStrategy() external view returns (uint); /* @notice Returns the total amount of token in vault + total debt */ function totalAssets() external view returns (uint); /* @notice Returns minimum amount of tokens that should be kept in vault for cheap withdraw @return Reserve amount */ function minReserve() external view returns (uint); /* @notice Returns the amount of tokens available to be invested */ function availableToInvest() external view returns (uint); /* @notice Approve strategy @param _strategy Address of strategy */ function approveStrategy(address _strategy) external; /* @notice Revoke strategy @param _strategy Address of strategy */ function revokeStrategy(address _strategy) external; /* @notice Set strategy @param _min Minimum undelying token current strategy must return. Prevents slippage */ function setStrategy(address _strategy, uint _min) external; /* @notice Transfers token in vault to strategy */ function invest() external; /* @notice Deposit undelying token into this vault @param _amount Amount of token to deposit */ function deposit(uint _amount) external; /* @notice Calculate amount of token that can be withdrawn @param _shares Amount of shares @return Amount of token that can be withdrawn */ function getExpectedReturn(uint _shares) external view returns (uint); /* @notice Withdraw token @param _shares Amount of shares to burn @param _min Minimum amount of token expected to return */ function withdraw(uint _shares, uint _min) external; /* @notice Transfer token in vault to admin @param _token Address of token to transfer @dev _token must not be equal to vault token */ function sweep(address _token) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface IStrategy { function admin() external view returns (address); function controller() external view returns (address); function vault() external view returns (address); /* @notice Returns address of underlying token */ function underlying() external view returns (address); /* @notice Returns total amount of underlying transferred from vault */ function totalDebt() external view returns (uint); function performanceFee() external view returns (uint); /* @notice Returns true if token cannot be swept */ function assets(address _token) external view returns (bool); function setAdmin(address _admin) external; function setController(address _controller) external; function setPerformanceFee(uint _fee) external; /* @notice Returns amount of underlying stable coin locked in this contract @dev Output may vary depending on price of liquidity provider token where the underlying token is invested */ function totalAssets() external view returns (uint); /* @notice Deposit `amount` underlying token for yield token @param amount Amount of underlying token to deposit */ function deposit(uint _amount) external; /* @notice Withdraw `amount` yield token to withdraw @param amount Amount of yield token to withdraw */ function withdraw(uint _amount) external; /* @notice Withdraw all underlying token from strategy */ function withdrawAll() external; function harvest() external; /* @notice Exit from strategy @dev Must transfer all underlying tokens back to vault */ function exit() external; /* @notice Transfer profit over total debt to vault */ function skim() external; /* @notice Transfer token in strategy to admin @param _token Address of token to transfer @dev Must transfer token to admin @dev _token must not be equal to underlying token @dev Used to transfer token that was accidentally sent or claim dust created from this strategy */ function sweep(address _token) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./protocol/IStrategy.sol"; import "./protocol/IVault.sol"; import "./protocol/IController.sol"; /* potential hacks? - directly send underlying token to this vault or strategy - flash loan - flashloan make undelying token less valuable - vault deposit - flashloan make underlying token more valuable - vault withdraw - return loan - front running? */ contract Vault is IVault, ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint; event SetStrategy(address strategy); event ApproveStrategy(address strategy); event RevokeStrategy(address strategy); event SetWhitelist(address addr, bool approved); address public override admin; address public override controller; address public override timeLock; address public immutable override token; address public override strategy; // mapping of approved strategies mapping(address => bool) public override strategies; // percentange of token reserved in vault for cheap withdraw uint public override reserveMin = 500; uint private constant RESERVE_MAX = 10000; // Denominator used to calculate fees uint private constant FEE_MAX = 10000; uint public override withdrawFee; uint private constant WITHDRAW_FEE_CAP = 500; // upper limit to withdrawFee bool public override paused; // whitelisted addresses // used to prevent flash loah attacks mapping(address => bool) public override whitelist; /* @dev vault decimals must be equal to token decimals */ constructor( address _controller, address _timeLock, address _token ) public ERC20( string(abi.encodePacked("unagii_", ERC20(_token).name())), string(abi.encodePacked("u", ERC20(_token).symbol())) ) { require(_controller != address(0), "controller = zero address"); require(_timeLock != address(0), "time lock = zero address"); _setupDecimals(ERC20(_token).decimals()); admin = msg.sender; controller = _controller; token = _token; timeLock = _timeLock; } modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } modifier onlyTimeLock() { require(msg.sender == timeLock, "!time lock"); _; } modifier onlyAdminOrController() { require(msg.sender == admin || msg.sender == controller, "!authorized"); _; } modifier whenStrategyDefined() { require(strategy != address(0), "strategy = zero address"); _; } modifier whenNotPaused() { require(!paused, "paused"); _; } /* @dev modifier to prevent flash loan @dev caller is restricted to EOA or whitelisted contract @dev Warning: Users can have their funds stuck if shares is transferred to a contract */ modifier guard() { require((msg.sender == tx.origin) || whitelist[msg.sender], "!whitelist"); _; } function setAdmin(address _admin) external override onlyAdmin { require(_admin != address(0), "admin = zero address"); admin = _admin; } function setController(address _controller) external override onlyAdmin { require(_controller != address(0), "controller = zero address"); controller = _controller; } function setTimeLock(address _timeLock) external override onlyTimeLock { require(_timeLock != address(0), "time lock = zero address"); timeLock = _timeLock; } function setPause(bool _paused) external override onlyAdmin { paused = _paused; } function setWhitelist(address _addr, bool _approve) external override onlyAdmin { whitelist[_addr] = _approve; emit SetWhitelist(_addr, _approve); } function setReserveMin(uint _reserveMin) external override onlyAdmin { require(_reserveMin <= RESERVE_MAX, "reserve min > max"); reserveMin = _reserveMin; } function setWithdrawFee(uint _fee) external override onlyAdmin { require(_fee <= WITHDRAW_FEE_CAP, "withdraw fee > cap"); withdrawFee = _fee; } function _balanceInVault() private view returns (uint) { return IERC20(token).balanceOf(address(this)); } /* @notice Returns balance of tokens in vault @return Amount of token in vault */ function balanceInVault() external view override returns (uint) { return _balanceInVault(); } function _balanceInStrategy() private view returns (uint) { if (strategy == address(0)) { return 0; } return IStrategy(strategy).totalAssets(); } /* @notice Returns the estimate amount of token in strategy @dev Output may vary depending on price of liquidity provider token where the underlying token is invested */ function balanceInStrategy() external view override returns (uint) { return _balanceInStrategy(); } function _totalDebtInStrategy() private view returns (uint) { if (strategy == address(0)) { return 0; } return IStrategy(strategy).totalDebt(); } /* @notice Returns amount of tokens invested strategy */ function totalDebtInStrategy() external view override returns (uint) { return _totalDebtInStrategy(); } function _totalAssets() private view returns (uint) { return _balanceInVault().add(_totalDebtInStrategy()); } /* @notice Returns the total amount of tokens in vault + total debt @return Total amount of tokens in vault + total debt */ function totalAssets() external view override returns (uint) { return _totalAssets(); } function _minReserve() private view returns (uint) { return _totalAssets().mul(reserveMin) / RESERVE_MAX; } /* @notice Returns minimum amount of tokens that should be kept in vault for cheap withdraw @return Reserve amount */ function minReserve() external view override returns (uint) { return _minReserve(); } function _availableToInvest() private view returns (uint) { if (strategy == address(0)) { return 0; } uint balInVault = _balanceInVault(); uint reserve = _minReserve(); if (balInVault <= reserve) { return 0; } return balInVault - reserve; } /* @notice Returns amount of token available to be invested into strategy @return Amount of token available to be invested into strategy */ function availableToInvest() external view override returns (uint) { return _availableToInvest(); } /* @notice Approve strategy @param _strategy Address of strategy to revoke */ function approveStrategy(address _strategy) external override onlyTimeLock { require(_strategy != address(0), "strategy = zero address"); strategies[_strategy] = true; emit ApproveStrategy(_strategy); } /* @notice Revoke strategy @param _strategy Address of strategy to revoke */ function revokeStrategy(address _strategy) external override onlyAdmin { require(_strategy != address(0), "strategy = zero address"); strategies[_strategy] = false; emit RevokeStrategy(_strategy); } /* @notice Set strategy to approved strategy @param _strategy Address of strategy used @param _min Minimum undelying token current strategy must return. Prevents slippage */ function setStrategy(address _strategy, uint _min) external override onlyAdminOrController { require(strategies[_strategy], "!approved"); require(_strategy != strategy, "new strategy = current strategy"); require( IStrategy(_strategy).underlying() == token, "strategy.token != vault.token" ); require( IStrategy(_strategy).vault() == address(this), "strategy.vault != vault" ); // withdraw from current strategy if (strategy != address(0)) { IERC20(token).safeApprove(strategy, 0); uint balBefore = _balanceInVault(); IStrategy(strategy).exit(); uint balAfter = _balanceInVault(); require(balAfter.sub(balBefore) >= _min, "withdraw < min"); } strategy = _strategy; emit SetStrategy(strategy); } /* @notice Invest token from vault into strategy. Some token are kept in vault for cheap withdraw. */ function invest() external override whenStrategyDefined whenNotPaused onlyAdminOrController { uint amount = _availableToInvest(); require(amount > 0, "available = 0"); IERC20(token).safeApprove(strategy, 0); IERC20(token).safeApprove(strategy, amount); IStrategy(strategy).deposit(amount); IERC20(token).safeApprove(strategy, 0); } /* @notice Deposit token into vault @param _amount Amount of token to transfer from `msg.sender` */ function deposit(uint _amount) external override whenNotPaused nonReentrant guard { require(_amount > 0, "amount = 0"); uint totalUnderlying = _totalAssets(); uint totalShares = totalSupply(); /* s = shares to mint T = total shares before mint d = deposit amount A = total assets in vault + strategy before deposit s / (T + s) = d / (A + d) s = d / A * T */ uint shares; if (totalShares == 0) { shares = _amount; } else { shares = _amount.mul(totalShares).div(totalUnderlying); } _mint(msg.sender, shares); IERC20(token).safeTransferFrom(msg.sender, address(this), _amount); } function _getExpectedReturn( uint _shares, uint _balInVault, uint _balInStrat ) private view returns (uint) { /* s = shares T = total supply of shares w = amount of underlying token to withdraw U = total amount of redeemable underlying token in vault + strategy s / T = w / U w = s / T * U */ /* total underlying = bal in vault + min(total debt, bal in strat) if bal in strat > total debt, redeemable = total debt else redeemable = bal in strat */ uint totalDebt = _totalDebtInStrategy(); uint totalUnderlying; if (_balInStrat > totalDebt) { totalUnderlying = _balInVault.add(totalDebt); } else { totalUnderlying = _balInVault.add(_balInStrat); } uint totalShares = totalSupply(); if (totalShares > 0) { return _shares.mul(totalUnderlying) / totalShares; } return 0; } /* @notice Calculate amount of underlying token that can be withdrawn @param _shares Amount of shares @return Amount of underlying token that can be withdrawn */ function getExpectedReturn(uint _shares) external view override returns (uint) { uint balInVault = _balanceInVault(); uint balInStrat = _balanceInStrategy(); return _getExpectedReturn(_shares, balInVault, balInStrat); } /* @notice Withdraw underlying token @param _shares Amount of shares to burn @param _min Minimum amount of underlying token to return @dev Keep `guard` modifier, else attacker can deposit and then use smart contract to attack from withdraw */ function withdraw(uint _shares, uint _min) external override nonReentrant guard { require(_shares > 0, "shares = 0"); uint balInVault = _balanceInVault(); uint balInStrat = _balanceInStrategy(); uint withdrawAmount = _getExpectedReturn(_shares, balInVault, balInStrat); // Must burn after calculating withdraw amount _burn(msg.sender, _shares); if (balInVault < withdrawAmount) { // maximize withdraw amount from strategy uint amountFromStrat = withdrawAmount; if (balInStrat < withdrawAmount) { amountFromStrat = balInStrat; } IStrategy(strategy).withdraw(amountFromStrat); uint balAfter = _balanceInVault(); uint diff = balAfter.sub(balInVault); if (diff < amountFromStrat) { // withdraw amount - withdraw amount from strat = amount to withdraw from vault // diff = actual amount returned from strategy // NOTE: withdrawAmount >= amountFromStrat withdrawAmount = (withdrawAmount - amountFromStrat).add(diff); } // transfer to treasury uint fee = withdrawAmount.mul(withdrawFee) / FEE_MAX; if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); withdrawAmount = withdrawAmount - fee; IERC20(token).safeTransfer(treasury, fee); } } require(withdrawAmount >= _min, "withdraw < min"); IERC20(token).safeTransfer(msg.sender, withdrawAmount); } /* @notice Transfer token != underlying token in vault to admin @param _token Address of token to transfer @dev Must transfer token to admin @dev _token must not be equal to underlying token @dev Used to transfer token that was accidentally sent to this vault */ function sweep(address _token) external override onlyAdmin { require(_token != token, "token = vault.token"); IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/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 {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies 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.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../protocol/IController.sol"; /* solium-disable */ contract MockController is IController { bytes32 public constant override ADMIN_ROLE = keccak256(abi.encodePacked("ADMIN")); bytes32 public constant override HARVESTER_ROLE = keccak256(abi.encodePacked("HARVESTER")); address public override admin; address public override treasury; constructor(address _treasury) public { admin = msg.sender; treasury = _treasury; } function setAdmin(address _admin) external override {} function setTreasury(address _treasury) external override {} function grantRole(bytes32 _role, address _addr) external override {} function revokeRole(bytes32 _role, address _addr) external override {} function invest(address _vault) external override {} function setStrategy( address _vault, address _strategy, uint _min ) external override {} function harvest(address _strategy) external override {} function skim(address _strategy) external override {} function withdraw( address _strategy, uint _amount, uint _min ) external override {} function withdrawAll(address _strategy, uint _min) external override {} function exit(address _strategy, uint _min) external override {} /* test helper */ function _setTreasury_(address _treasury) external { treasury = _treasury; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./protocol/IStrategy.sol"; import "./protocol/IController.sol"; abstract contract StrategyBase is IStrategy { using SafeERC20 for IERC20; using SafeMath for uint; address public override admin; address public override controller; address public override vault; address public override underlying; // total amount of underlying transferred from vault uint public override totalDebt; // performance fee sent to treasury when harvest() generates profit uint public override performanceFee = 100; uint internal constant PERFORMANCE_FEE_MAX = 10000; // valuable tokens that cannot be swept mapping(address => bool) public override assets; constructor( address _controller, address _vault, address _underlying ) public { require(_controller != address(0), "controller = zero address"); require(_vault != address(0), "vault = zero address"); require(_underlying != address(0), "underlying = zero address"); admin = msg.sender; controller = _controller; vault = _vault; underlying = _underlying; assets[underlying] = true; } modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } modifier onlyAuthorized() { require( msg.sender == admin || msg.sender == controller || msg.sender == vault, "!authorized" ); _; } function setAdmin(address _admin) external override onlyAdmin { require(_admin != address(0), "admin = zero address"); admin = _admin; } function setController(address _controller) external override onlyAdmin { require(_controller != address(0), "controller = zero address"); controller = _controller; } function setPerformanceFee(uint _fee) external override onlyAdmin { require(_fee <= PERFORMANCE_FEE_MAX, "performance fee > max"); performanceFee = _fee; } function _increaseDebt(uint _underlyingAmount) private { uint balBefore = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransferFrom(vault, address(this), _underlyingAmount); uint balAfter = IERC20(underlying).balanceOf(address(this)); totalDebt = totalDebt.add(balAfter.sub(balBefore)); } function _decreaseDebt(uint _underlyingAmount) private { uint balBefore = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransfer(vault, _underlyingAmount); uint balAfter = IERC20(underlying).balanceOf(address(this)); uint diff = balBefore.sub(balAfter); if (diff > totalDebt) { totalDebt = 0; } else { totalDebt = totalDebt - diff; } } function _totalAssets() internal view virtual returns (uint); /* @notice Returns amount of underlying tokens locked in this contract */ function totalAssets() external view override returns (uint) { return _totalAssets(); } function _depositUnderlying() internal virtual; /* @notice Deposit underlying token into this strategy @param _underlyingAmount Amount of underlying token to deposit */ function deposit(uint _underlyingAmount) external override onlyAuthorized { require(_underlyingAmount > 0, "underlying = 0"); _increaseDebt(_underlyingAmount); _depositUnderlying(); } /* @notice Returns total shares owned by this contract for depositing underlying into external Defi */ function _getTotalShares() internal view virtual returns (uint); function _getShares(uint _underlyingAmount, uint _totalUnderlying) internal view returns (uint) { /* calculate shares to withdraw w = amount of underlying to withdraw U = total redeemable underlying s = shares to withdraw P = total shares deposited into external liquidity pool w / U = s / P s = w / U * P */ if (_totalUnderlying > 0) { uint totalShares = _getTotalShares(); return _underlyingAmount.mul(totalShares) / _totalUnderlying; } return 0; } function _withdrawUnderlying(uint _shares) internal virtual; /* @notice Withdraw undelying token to vault @param _underlyingAmount Amount of underlying token to withdraw @dev Caller should implement guard agains slippage */ function withdraw(uint _underlyingAmount) external override onlyAuthorized { require(_underlyingAmount > 0, "underlying = 0"); uint totalUnderlying = _totalAssets(); require(_underlyingAmount <= totalUnderlying, "underlying > total"); uint shares = _getShares(_underlyingAmount, totalUnderlying); if (shares > 0) { _withdrawUnderlying(shares); } // transfer underlying token to vault uint underlyingBal = IERC20(underlying).balanceOf(address(this)); if (underlyingBal > 0) { _decreaseDebt(underlyingBal); } } function _withdrawAll() internal { uint totalShares = _getTotalShares(); if (totalShares > 0) { _withdrawUnderlying(totalShares); } uint underlyingBal = IERC20(underlying).balanceOf(address(this)); if (underlyingBal > 0) { _decreaseDebt(underlyingBal); totalDebt = 0; } } /* @notice Withdraw all underlying to vault @dev Caller should implement guard agains slippage */ function withdrawAll() external override onlyAuthorized { _withdrawAll(); } /* @notice Sell any staking rewards for underlying, deposit or transfer undelying depending on total debt */ function harvest() external virtual override; /* @notice Transfer profit over total debt to vault */ function skim() external override onlyAuthorized { uint totalUnderlying = _totalAssets(); if (totalUnderlying > totalDebt) { uint profit = totalUnderlying - totalDebt; uint shares = _getShares(profit, totalUnderlying); if (shares > 0) { uint balBefore = IERC20(underlying).balanceOf(address(this)); _withdrawUnderlying(shares); uint balAfter = IERC20(underlying).balanceOf(address(this)); uint diff = balAfter.sub(balBefore); if (diff > 0) { IERC20(underlying).safeTransfer(vault, diff); } } } } function exit() external virtual override; function sweep(address _token) external override onlyAdmin { require(!assets[_token], "asset"); IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this))); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../StrategyBase.sol"; import "./TestToken.sol"; /* solium-disable */ contract StrategyTest is StrategyBase { // test helper uint public _depositAmount_; uint public _withdrawAmount_; bool public _harvestWasCalled_; bool public _exitWasCalled_; // simulate strategy withdrawing less than requested uint public _maxWithdrawAmount_ = uint(-1); // mock liquidity provider address public constant _POOL_ = address(1); constructor( address _controller, address _vault, address _underlying ) public StrategyBase(_controller, _vault, _underlying) { // allow this contract to freely withdraw from POOL TestToken(underlying)._approve_(_POOL_, address(this), uint(-1)); } function _totalAssets() internal view override returns (uint) { return IERC20(underlying).balanceOf(_POOL_); } function _depositUnderlying() internal override { uint bal = IERC20(underlying).balanceOf(address(this)); _depositAmount_ = bal; IERC20(underlying).transfer(_POOL_, bal); } function _getTotalShares() internal view override returns (uint) { return IERC20(underlying).balanceOf(_POOL_); } function _withdrawUnderlying(uint _shares) internal override { _withdrawAmount_ = _shares; if (_shares > _maxWithdrawAmount_) { _withdrawAmount_ = _maxWithdrawAmount_; } IERC20(underlying).transferFrom(_POOL_, address(this), _withdrawAmount_); } function harvest() external override onlyAuthorized { _harvestWasCalled_ = true; } function exit() external override onlyAuthorized { _exitWasCalled_ = true; _withdrawAll(); } // test helpers function _setVault_(address _vault) external { vault = _vault; } function _setUnderlying_(address _token) external { underlying = _token; } function _setAsset_(address _token) external { assets[_token] = true; } function _mintToPool_(uint _amount) external { TestToken(underlying)._mint_(_POOL_, _amount); } function _setTotalDebt_(uint _debt) external { totalDebt = _debt; } function _setMaxWithdrawAmount_(uint _max) external { _maxWithdrawAmount_ = _max; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /* solium-disable */ contract TestToken is ERC20 { constructor() public ERC20("test", "TEST") { _setupDecimals(18); } /* test helper */ function _mint_(address _to, uint _amount) external { _mint(_to, _amount); } function _burn_(address _from, uint _amount) external { _burn(_from, _amount); } function _approve_( address _from, address _to, uint _amount ) external { _approve(_from, _to, _amount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../protocol/IStrategy.sol"; /* This is a "placeholder" strategy used during emergency shutdown */ contract StrategyNoOp is IStrategy { using SafeERC20 for IERC20; address public override admin; address public override controller; address public override vault; address public override underlying; uint public override totalDebt; uint public override performanceFee; mapping(address => bool) public override assets; constructor( address _controller, address _vault, address _underlying ) public { require(_controller != address(0), "controller = zero address"); require(_vault != address(0), "vault = zero address"); require(_underlying != address(0), "underlying = zero address"); admin = msg.sender; controller = _controller; vault = _vault; underlying = _underlying; assets[underlying] = true; } modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } function setAdmin(address _admin) external override onlyAdmin { require(_admin != address(0), "admin = zero address"); admin = _admin; } // @dev variable name is removed to silence compiler warning function setController(address) external override { revert("no-op"); } // @dev variable name is removed to silence compiler warning function setPerformanceFee(uint) external override { revert("no-op"); } function totalAssets() external view override returns (uint) { return 0; } // @dev variable name is removed to silence compiler warning function deposit(uint) external override { revert("no-op"); } // @dev variable name is removed to silence compiler warning function withdraw(uint) external override { revert("no-op"); } function withdrawAll() external override { revert("no-op"); } function harvest() external override { revert("no-op"); } function skim() external override { revert("no-op"); } function exit() external override { // left as blank so that Vault can call exit() during Vault.setStrategy() } function sweep(address _token) external override onlyAdmin { require(!assets[_token], "asset"); IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this))); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/uniswap/Uniswap.sol"; contract UseUniswap { using SafeERC20 for IERC20; using SafeMath for uint; // Uniswap // address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; function _swap( address _from, address _to, uint _amount ) internal { require(_to != address(0), "to = zero address"); // Swap with uniswap IERC20(_from).safeApprove(UNISWAP, 0); IERC20(_from).safeApprove(UNISWAP, _amount); address[] memory path; if (_from == WETH || _to == WETH) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = WETH; path[2] = _to; } Uniswap(UNISWAP).swapExactTokensForTokens( _amount, 0, path, address(this), now.add(60) ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface Uniswap { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../interfaces/pickle/PickleJar.sol"; import "../interfaces/pickle/MasterChef.sol"; import "../interfaces/pickle/PickleStaking.sol"; import "../StrategyBase.sol"; import "../UseUniswap.sol"; contract StrategyPdaiDai is StrategyBase, UseUniswap { address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // Pickle // address private constant JAR = 0x6949Bb624E8e8A90F87cD2058139fcd77D2F3F87; address private constant CHEF = 0xbD17B1ce622d73bD438b9E658acA5996dc394b0d; address private constant PICKLE = 0x429881672B9AE42b8EbA0E26cD9C73711b891Ca5; address private constant STAKING = 0xa17a8883dA1aBd57c690DF9Ebf58fC194eDAb66F; // percentage of Pickle to sell, rest is staked uint public pickleSell = 5000; uint private constant PICKLE_SELL_MAX = 10000; // POOL ID for PDAI JAR uint private constant POOL_ID = 16; constructor(address _controller, address _vault) public StrategyBase(_controller, _vault, DAI) { // Assets that cannot be swept by admin assets[PICKLE] = true; } function setPickleSell(uint _sell) external onlyAdmin { require(_sell <= PICKLE_SELL_MAX, "sell > max"); pickleSell = _sell; } // TODO security: vulnerable to price manipulation? function _totalAssets() internal view override returns (uint) { // getRatio() is multiplied by 10 ** 18 uint pricePerShare = PickleJar(JAR).getRatio(); (uint shares, ) = MasterChef(CHEF).userInfo(POOL_ID, address(this)); return shares.mul(pricePerShare).div(1e18); } function _depositUnderlying() internal override { // deposit DAI into PICKLE uint bal = IERC20(underlying).balanceOf(address(this)); if (bal > 0) { IERC20(underlying).safeApprove(JAR, 0); IERC20(underlying).safeApprove(JAR, bal); PickleJar(JAR).deposit(bal); } // stake pDai uint pDaiBal = IERC20(JAR).balanceOf(address(this)); if (pDaiBal > 0) { IERC20(JAR).safeApprove(CHEF, 0); IERC20(JAR).safeApprove(CHEF, pDaiBal); MasterChef(CHEF).deposit(POOL_ID, pDaiBal); } // stake PICKLE uint pickleBal = IERC20(PICKLE).balanceOf(address(this)); if (pickleBal > 0) { IERC20(PICKLE).safeApprove(STAKING, 0); IERC20(PICKLE).safeApprove(STAKING, pickleBal); PickleStaking(STAKING).stake(pickleBal); } } function _getTotalShares() internal view override returns (uint) { (uint pDaiBal, ) = MasterChef(CHEF).userInfo(POOL_ID, address(this)); return pDaiBal; } function _withdrawUnderlying(uint _pDaiAmount) internal override { // unstake MasterChef(CHEF).withdraw(POOL_ID, _pDaiAmount); // withdraw DAI from PICKLE PickleJar(JAR).withdraw(_pDaiAmount); // Now we have underlying } function _swapWeth() private { uint wethBal = IERC20(WETH).balanceOf(address(this)); if (wethBal > 0) { _swap(WETH, underlying, wethBal); // Now this contract has underlying token } } /* @notice Sell PICKLE and deposit most premium token into CURVE */ function harvest() external override onlyAuthorized { // claim Pickle MasterChef(CHEF).deposit(POOL_ID, 0); // unsold amount will be staked in _depositUnderlying() uint pickleBal = IERC20(PICKLE).balanceOf(address(this)); uint pickleAmount = pickleBal.mul(pickleSell).div(PICKLE_SELL_MAX); if (pickleAmount > 0) { _swap(PICKLE, underlying, pickleAmount); // Now this contract has underlying token } // get staking rewards WETH PickleStaking(STAKING).getReward(); _swapWeth(); uint bal = IERC20(underlying).balanceOf(address(this)); if (bal > 0) { // transfer fee to treasury uint fee = bal.mul(performanceFee).div(PERFORMANCE_FEE_MAX); if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); IERC20(underlying).safeTransfer(treasury, fee); } _depositUnderlying(); } } /* @dev Caller should implement guard agains slippage */ function exit() external override onlyAuthorized { /* PICKLE is minted on deposit / withdraw so here we 0. Unstake PICKLE and claim WETH rewards 1. Sell WETH 2. Withdraw from MasterChef 3. Sell PICKLE 4. Transfer underlying to vault */ uint staked = PickleStaking(STAKING).balanceOf(address(this)); if (staked > 0) { PickleStaking(STAKING).exit(); _swapWeth(); } _withdrawAll(); uint pickleBal = IERC20(PICKLE).balanceOf(address(this)); if (pickleBal > 0) { _swap(PICKLE, underlying, pickleBal); // Now this contract has underlying token } uint bal = IERC20(underlying).balanceOf(address(this)); if (bal > 0) { IERC20(underlying).safeTransfer(vault, bal); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface PickleJar { /* @notice returns price of token / share @dev ratio is multiplied by 10 ** 18 */ function getRatio() external view returns (uint); function deposit(uint _amount) external; function withdraw(uint _amount) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface MasterChef { function userInfo(uint _pid, address _user) external view returns (uint _amount, uint _rewardDebt); function deposit(uint _pid, uint _amount) external; function withdraw(uint _pid, uint _amount) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface PickleStaking { function balanceOf(address account) external view returns (uint); function earned(address account) external view returns (uint); function stake(uint amount) external; function withdraw(uint amount) external; function getReward() external; function exit() external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../interfaces/curve/StableSwap3.sol"; import "../interfaces/pickle/PickleJar.sol"; import "../interfaces/pickle/MasterChef.sol"; import "../StrategyBase.sol"; import "../UseUniswap.sol"; contract StrategyP3Crv is StrategyBase, UseUniswap { address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; // DAI = 0 | USDC = 1 | USDT = 2 uint internal underlyingIndex; // precision to convert 10 ** 18 to underlying decimals uint internal precisionDiv = 1; // Curve // // 3Crv address private constant THREE_CRV = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; // StableSwap3 address private constant CURVE = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; // Pickle // address private constant JAR = 0x1BB74b5DdC1f4fC91D6f9E7906cf68bc93538e33; address private constant CHEF = 0xbD17B1ce622d73bD438b9E658acA5996dc394b0d; address private constant PICKLE = 0x429881672B9AE42b8EbA0E26cD9C73711b891Ca5; // POOL ID for 3Crv JAR uint private constant POOL_ID = 14; constructor( address _controller, address _vault, address _underlying ) public StrategyBase(_controller, _vault, _underlying) { // Assets that cannot be swept by admin assets[PICKLE] = true; } // TODO security: vulnerable to price manipulation function _totalAssets() internal view override returns (uint) { // getRatio() is multiplied by 10 ** 18 uint pricePerShare = PickleJar(JAR).getRatio(); (uint shares, ) = MasterChef(CHEF).userInfo(POOL_ID, address(this)); return shares.mul(pricePerShare).div(precisionDiv) / 1e18; } function _deposit(address _token, uint _index) private { // token to THREE_CRV uint bal = IERC20(_token).balanceOf(address(this)); if (bal > 0) { IERC20(_token).safeApprove(CURVE, 0); IERC20(_token).safeApprove(CURVE, bal); // mint THREE_CRV uint[3] memory amounts; amounts[_index] = bal; StableSwap3(CURVE).add_liquidity(amounts, 0); // Now we have 3Crv } // deposit 3Crv into PICKLE uint threeBal = IERC20(THREE_CRV).balanceOf(address(this)); if (threeBal > 0) { IERC20(THREE_CRV).safeApprove(JAR, 0); IERC20(THREE_CRV).safeApprove(JAR, threeBal); PickleJar(JAR).deposit(threeBal); } // stake p3crv uint p3crvBal = IERC20(JAR).balanceOf(address(this)); if (p3crvBal > 0) { IERC20(JAR).safeApprove(CHEF, 0); IERC20(JAR).safeApprove(CHEF, p3crvBal); MasterChef(CHEF).deposit(POOL_ID, p3crvBal); } // TODO stake } function _depositUnderlying() internal override { _deposit(underlying, underlyingIndex); } function _getTotalShares() internal view override returns (uint) { (uint p3CrvBal, ) = MasterChef(CHEF).userInfo(POOL_ID, address(this)); return p3CrvBal; } function _withdrawUnderlying(uint _p3CrvAmount) internal override { // unstake MasterChef(CHEF).withdraw(POOL_ID, _p3CrvAmount); // withdraw THREE_CRV from PICKLE PickleJar(JAR).withdraw(_p3CrvAmount); // withdraw underlying uint threeBal = IERC20(THREE_CRV).balanceOf(address(this)); // creates THREE_CRV dust StableSwap3(CURVE).remove_liquidity_one_coin( threeBal, int128(underlyingIndex), 0 ); // Now we have underlying } /* @notice Returns address and index of token with lowest balance in CURVE pool */ function _getMostPremiumToken() private view returns (address, uint) { uint[] memory balances = new uint[](3); balances[0] = StableSwap3(CURVE).balances(0); // DAI balances[1] = StableSwap3(CURVE).balances(1).mul(1e12); // USDC balances[2] = StableSwap3(CURVE).balances(2).mul(1e12); // USDT // DAI if (balances[0] <= balances[1] && balances[0] <= balances[2]) { return (DAI, 0); } // USDC if (balances[1] <= balances[0] && balances[1] <= balances[2]) { return (USDC, 1); } // USDT return (USDT, 2); } function _swapPickleFor(address _token) private { uint pickleBal = IERC20(PICKLE).balanceOf(address(this)); if (pickleBal > 0) { _swap(PICKLE, _token, pickleBal); // Now this contract has underlying token } } /* @notice Sell PICKLE and deposit most premium token into CURVE */ function harvest() external override onlyAuthorized { // TODO: claim Pickle // MasterChef(CHER).deposit(POOL_ID, 0); (address token, uint index) = _getMostPremiumToken(); _swapPickleFor(token); uint bal = IERC20(token).balanceOf(address(this)); if (bal > 0) { // transfer fee to treasury uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX; if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); IERC20(token).safeTransfer(treasury, fee); } _deposit(token, index); } } /* @dev Caller should implement guard agains slippage */ function exit() external override onlyAuthorized { // PICKLE is minted on withdraw so here we // 1. Withdraw from MasterChef // 2. Sell PICKLE // 3. Transfer underlying to vault _withdrawAll(); _swapPickleFor(underlying); uint underlyingBal = IERC20(underlying).balanceOf(address(this)); if (underlyingBal > 0) { IERC20(underlying).safeTransfer(vault, underlyingBal); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface StableSwap3 { /* @dev Returns price of 1 Curve LP token in USD */ function get_virtual_price() external view returns (uint); function add_liquidity(uint[3] calldata amounts, uint min_mint_amount) external; function remove_liquidity_one_coin( uint token_amount, int128 i, uint min_uamount ) external; function balances(uint index) external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyP3Crv.sol"; contract StrategyP3CrvUsdt is StrategyP3Crv { constructor(address _controller, address _vault) public StrategyP3Crv(_controller, _vault, USDT) { // usdt underlyingIndex = 2; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyP3Crv.sol"; contract StrategyP3CrvUsdc is StrategyP3Crv { constructor(address _controller, address _vault) public StrategyP3Crv(_controller, _vault, USDC) { // usdc underlyingIndex = 1; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyP3Crv.sol"; contract StrategyP3CrvDai is StrategyP3Crv { constructor(address _controller, address _vault) public StrategyP3Crv(_controller, _vault, DAI) { // dai underlyingIndex = 0; precisionDiv = 1; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../interfaces/curve/StableSwapGusd.sol"; import "../interfaces/curve/DepositGusd.sol"; import "../interfaces/curve/StableSwap3.sol"; import "./StrategyCurve.sol"; contract StrategyGusd is StrategyCurve { // 3Pool StableSwap address private constant BASE_POOL = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; // GUSD StableSwap address private constant SWAP = 0x4f062658EaAF2C1ccf8C8e36D6824CDf41167956; address private constant GUSD = 0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd; address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; constructor( address _controller, address _vault, address _underlying ) public StrategyCurve(_controller, _vault, _underlying) { // Curve // GUSD / 3CRV lp = 0xD2967f45c4f384DEEa880F807Be904762a3DeA07; // DepositGusd pool = 0x64448B78561690B70E17CBE8029a3e5c1bB7136e; // Gauge gauge = 0xC5cfaDA84E902aD92DD40194f0883ad49639b023; // Minter minter = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // DAO crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; } function _getVirtualPrice() internal view override returns (uint) { return StableSwapGusd(SWAP).get_virtual_price(); } function _addLiquidity(uint _amount, uint _index) internal override { uint[4] memory amounts; amounts[_index] = _amount; DepositGusd(pool).add_liquidity(amounts, 0); } function _removeLiquidityOneCoin(uint _lpAmount) internal override { IERC20(lp).safeApprove(pool, 0); IERC20(lp).safeApprove(pool, _lpAmount); DepositGusd(pool).remove_liquidity_one_coin( _lpAmount, int128(underlyingIndex), 0 ); } function _getMostPremiumToken() internal view override returns (address, uint) { uint[4] memory balances; balances[0] = StableSwapGusd(SWAP).balances(0).mul(1e16); // GUSD balances[1] = StableSwap3(BASE_POOL).balances(0); // DAI balances[2] = StableSwap3(BASE_POOL).balances(1).mul(1e12); // USDC balances[3] = StableSwap3(BASE_POOL).balances(2).mul(1e12); // USDT uint minIndex = 0; for (uint i = 1; i < balances.length; i++) { if (balances[i] <= balances[minIndex]) { minIndex = i; } } if (minIndex == 0) { return (GUSD, 0); } if (minIndex == 1) { return (DAI, 1); } if (minIndex == 2) { return (USDC, 2); } return (USDT, 3); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface StableSwapGusd { function get_virtual_price() external view returns (uint); /* 0 GUSD 1 3CRV */ function balances(uint index) external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface DepositGusd { /* 0 GUSD 1 DAI 2 USDC 3 USDT */ function add_liquidity(uint[4] memory amounts, uint min) external returns (uint); function remove_liquidity_one_coin( uint amount, int128 index, uint min ) external returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../interfaces/curve/Gauge.sol"; import "../interfaces/curve/Minter.sol"; import "../StrategyBase.sol"; import "../UseUniswap.sol"; /* potential hacks? - front running? - slippage when withdrawing all from strategy */ abstract contract StrategyCurve is StrategyBase, UseUniswap { // DAI = 0 | USDC = 1 | USDT = 2 uint internal underlyingIndex; // precision to convert 10 ** 18 to underlying decimals uint internal precisionDiv = 1; // Curve // // liquidity provider token (cDAI/cUSDC or 3Crv) address internal lp; // ICurveFi2 or ICurveFi3 address internal pool; // Gauge address internal gauge; // Minter address internal minter; // DAO address internal crv; constructor( address _controller, address _vault, address _underlying ) public StrategyBase(_controller, _vault, _underlying) {} function _getVirtualPrice() internal view virtual returns (uint); function _totalAssets() internal view override returns (uint) { uint lpBal = Gauge(gauge).balanceOf(address(this)); uint pricePerShare = _getVirtualPrice(); return lpBal.mul(pricePerShare).div(precisionDiv) / 1e18; } function _addLiquidity(uint _amount, uint _index) internal virtual; /* @notice deposit token into curve */ function _deposit(address _token, uint _index) private { // token to lp uint bal = IERC20(_token).balanceOf(address(this)); if (bal > 0) { IERC20(_token).safeApprove(pool, 0); IERC20(_token).safeApprove(pool, bal); // mint lp _addLiquidity(bal, _index); } // stake into Gauge uint lpBal = IERC20(lp).balanceOf(address(this)); if (lpBal > 0) { IERC20(lp).safeApprove(gauge, 0); IERC20(lp).safeApprove(gauge, lpBal); Gauge(gauge).deposit(lpBal); } } /* @notice Deposits underlying to Gauge */ function _depositUnderlying() internal override { _deposit(underlying, underlyingIndex); } function _removeLiquidityOneCoin(uint _lpAmount) internal virtual; function _getTotalShares() internal view override returns (uint) { return Gauge(gauge).balanceOf(address(this)); } function _withdrawUnderlying(uint _lpAmount) internal override { // withdraw lp from Gauge Gauge(gauge).withdraw(_lpAmount); // withdraw underlying uint lpBal = IERC20(lp).balanceOf(address(this)); // creates lp dust _removeLiquidityOneCoin(lpBal); // Now we have underlying } /* @notice Returns address and index of token with lowest balance in Curve pool */ function _getMostPremiumToken() internal view virtual returns (address, uint); function _swapCrvFor(address _token) private { Minter(minter).mint(gauge); uint crvBal = IERC20(crv).balanceOf(address(this)); if (crvBal > 0) { _swap(crv, _token, crvBal); // Now this contract has token } } /* @notice Claim CRV and deposit most premium token into Curve */ function harvest() external override onlyAuthorized { (address token, uint index) = _getMostPremiumToken(); _swapCrvFor(token); uint bal = IERC20(token).balanceOf(address(this)); if (bal > 0) { // transfer fee to treasury uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX; if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); IERC20(token).safeTransfer(treasury, fee); } _deposit(token, index); } } /* @notice Exit strategy by harvesting CRV to underlying token and then withdrawing all underlying to vault @dev Must return all underlying token to vault @dev Caller should implement guard agains slippage */ function exit() external override onlyAuthorized { _swapCrvFor(underlying); _withdrawAll(); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; // https://github.com/curvefi/curve-contract/blob/master/contracts/gauges/LiquidityGauge.vy interface Gauge { function deposit(uint) external; function balanceOf(address) external view returns (uint); function withdraw(uint) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; // https://github.com/curvefi/curve-dao-contracts/blob/master/contracts/Minter.vy interface Minter { function mint(address) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyGusd.sol"; contract StrategyGusdUsdt is StrategyGusd { constructor(address _controller, address _vault) public StrategyGusd(_controller, _vault, USDT) { // usdt underlyingIndex = 3; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyGusd.sol"; contract StrategyGusdUsdc is StrategyGusd { constructor(address _controller, address _vault) public StrategyGusd(_controller, _vault, USDC) { // usdc underlyingIndex = 2; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyGusd.sol"; contract StrategyGusdDai is StrategyGusd { constructor(address _controller, address _vault) public StrategyGusd(_controller, _vault, DAI) { // dai underlyingIndex = 1; precisionDiv = 1; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../interfaces/curve/StableSwapPax.sol"; import "../interfaces/curve/DepositPax.sol"; import "./StrategyCurve.sol"; contract StrategyPax is StrategyCurve { // PAX StableSwap address private constant SWAP = 0x06364f10B501e868329afBc005b3492902d6C763; address private constant PAX = 0x8E870D67F660D95d5be530380D0eC0bd388289E1; address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; constructor( address _controller, address _vault, address _underlying ) public StrategyCurve(_controller, _vault, _underlying) { // Curve // DAI/USDC/USDT/PAX lp = 0xD905e2eaeBe188fc92179b6350807D8bd91Db0D8; // DepositPax pool = 0xA50cCc70b6a011CffDdf45057E39679379187287; // Gauge gauge = 0x64E3C23bfc40722d3B649844055F1D51c1ac041d; // Minter minter = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // DAO crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; } function _getVirtualPrice() internal view override returns (uint) { return StableSwapPax(SWAP).get_virtual_price(); } function _addLiquidity(uint _amount, uint _index) internal override { uint[4] memory amounts; amounts[_index] = _amount; DepositPax(pool).add_liquidity(amounts, 0); } function _removeLiquidityOneCoin(uint _lpAmount) internal override { IERC20(lp).safeApprove(pool, 0); IERC20(lp).safeApprove(pool, _lpAmount); DepositPax(pool).remove_liquidity_one_coin( _lpAmount, int128(underlyingIndex), 0, false ); } function _getMostPremiumToken() internal view override returns (address, uint) { uint[4] memory balances; balances[0] = StableSwapPax(SWAP).balances(0); // DAI balances[1] = StableSwapPax(SWAP).balances(1).mul(1e12); // USDC balances[2] = StableSwapPax(SWAP).balances(2).mul(1e12); // USDT balances[3] = StableSwapPax(SWAP).balances(3); // PAX uint minIndex = 0; for (uint i = 1; i < balances.length; i++) { if (balances[i] <= balances[minIndex]) { minIndex = i; } } if (minIndex == 0) { return (DAI, 0); } if (minIndex == 1) { return (USDC, 1); } if (minIndex == 2) { return (USDT, 2); } return (PAX, 3); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface StableSwapPax { function get_virtual_price() external view returns (uint); /* 0 DAI 1 USDC 2 USDT 3 PAX */ function balances(int128 index) external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface DepositPax { /* 0 DAI 1 USDC 2 USDT 3 PAX */ function add_liquidity(uint[4] memory amounts, uint min) external; function remove_liquidity_one_coin( uint amount, int128 index, uint min, bool donateDust ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyPax.sol"; contract StrategyPaxUsdt is StrategyPax { constructor(address _controller, address _vault) public StrategyPax(_controller, _vault, USDT) { // usdt underlyingIndex = 2; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyPax.sol"; contract StrategyPaxUsdc is StrategyPax { constructor(address _controller, address _vault) public StrategyPax(_controller, _vault, USDC) { // usdc underlyingIndex = 1; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyPax.sol"; contract StrategyPaxDai is StrategyPax { constructor(address _controller, address _vault) public StrategyPax(_controller, _vault, DAI) { // dai underlyingIndex = 0; precisionDiv = 1; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../interfaces/curve/StableSwap2.sol"; import "../interfaces/curve/Deposit2.sol"; import "./StrategyCurve.sol"; contract StrategyCusd is StrategyCurve { address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address private constant SWAP = 0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56; constructor( address _controller, address _vault, address _underlying ) public StrategyCurve(_controller, _vault, _underlying) { // Curve // cDAI/cUSDC lp = 0x845838DF265Dcd2c412A1Dc9e959c7d08537f8a2; // DepositCompound pool = 0xeB21209ae4C2c9FF2a86ACA31E123764A3B6Bc06; // Gauge gauge = 0x7ca5b0a2910B33e9759DC7dDB0413949071D7575; // Minter minter = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // DAO crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; } /* @dev Returns USD price of 1 Curve Compound LP token */ function _getVirtualPrice() internal view override returns (uint) { return StableSwap2(SWAP).get_virtual_price(); } function _addLiquidity(uint _amount, uint _index) internal override { uint[2] memory amounts; amounts[_index] = _amount; Deposit2(pool).add_liquidity(amounts, 0); } function _removeLiquidityOneCoin(uint _lpAmount) internal override { IERC20(lp).safeApprove(pool, 0); IERC20(lp).safeApprove(pool, _lpAmount); Deposit2(pool).remove_liquidity_one_coin( _lpAmount, int128(underlyingIndex), 0, true ); } function _getMostPremiumToken() internal view override returns (address, uint) { uint[] memory balances = new uint[](2); balances[0] = StableSwap2(SWAP).balances(0); // DAI balances[1] = StableSwap2(SWAP).balances(1).mul(1e12); // USDC // DAI if (balances[0] < balances[1]) { return (DAI, 0); } return (USDC, 1); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface StableSwap2 { /* @dev Returns price of 1 Curve LP token in USD */ function get_virtual_price() external view returns (uint); function add_liquidity(uint[2] calldata amounts, uint min_mint_amount) external; function remove_liquidity_one_coin( uint token_amount, int128 i, uint min_uamount, bool donate_dust ) external; function balances(int128 index) external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface Deposit2 { function add_liquidity(uint[2] calldata amounts, uint min_mint_amount) external; function remove_liquidity_one_coin( uint token_amount, int128 i, uint min_uamount, bool donate_dust ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyCusd.sol"; contract StrategyCusdUsdc is StrategyCusd { constructor(address _controller, address _vault) public StrategyCusd(_controller, _vault, USDC) { // usdc underlyingIndex = 1; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyCusd.sol"; contract StrategyCusdDai is StrategyCusd { constructor(address _controller, address _vault) public StrategyCusd(_controller, _vault, DAI) { // dai underlyingIndex = 0; precisionDiv = 1; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../interfaces/curve/StableSwapBusd.sol"; import "../interfaces/curve/DepositBusd.sol"; import "./StrategyCurve.sol"; contract StrategyBusd is StrategyCurve { // BUSD StableSwap address private constant SWAP = 0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27; address private constant BUSD = 0x4Fabb145d64652a948d72533023f6E7A623C7C53; address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; constructor( address _controller, address _vault, address _underlying ) public StrategyCurve(_controller, _vault, _underlying) { // Curve // yDAI/yUSDC/yUSDT/yBUSD lp = 0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B; // DepositBusd pool = 0xb6c057591E073249F2D9D88Ba59a46CFC9B59EdB; // Gauge gauge = 0x69Fb7c45726cfE2baDeE8317005d3F94bE838840; // Minter minter = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // DAO crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; } function _getVirtualPrice() internal view override returns (uint) { return StableSwapBusd(SWAP).get_virtual_price(); } function _addLiquidity(uint _amount, uint _index) internal override { uint[4] memory amounts; amounts[_index] = _amount; DepositBusd(pool).add_liquidity(amounts, 0); } function _removeLiquidityOneCoin(uint _lpAmount) internal override { IERC20(lp).safeApprove(pool, 0); IERC20(lp).safeApprove(pool, _lpAmount); DepositBusd(pool).remove_liquidity_one_coin( _lpAmount, int128(underlyingIndex), 0, false ); } function _getMostPremiumToken() internal view override returns (address, uint) { uint[4] memory balances; balances[0] = StableSwapBusd(SWAP).balances(0); // DAI balances[1] = StableSwapBusd(SWAP).balances(1).mul(1e12); // USDC balances[2] = StableSwapBusd(SWAP).balances(2).mul(1e12); // USDT balances[3] = StableSwapBusd(SWAP).balances(3); // BUSD uint minIndex = 0; for (uint i = 1; i < balances.length; i++) { if (balances[i] <= balances[minIndex]) { minIndex = i; } } if (minIndex == 0) { return (DAI, 0); } if (minIndex == 1) { return (USDC, 1); } if (minIndex == 2) { return (USDT, 2); } return (BUSD, 3); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface StableSwapBusd { function get_virtual_price() external view returns (uint); /* 0 DAI 1 USDC 2 USDT 3 BUSD */ function balances(int128 index) external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface DepositBusd { /* 0 DAI 1 USDC 2 USDT 3 BUSD */ function add_liquidity(uint[4] memory amounts, uint min) external; function remove_liquidity_one_coin( uint amount, int128 index, uint min, bool donateDust ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyBusd.sol"; contract StrategyBusdUsdt is StrategyBusd { constructor(address _controller, address _vault) public StrategyBusd(_controller, _vault, USDT) { // usdt underlyingIndex = 2; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyBusd.sol"; contract StrategyBusdUsdc is StrategyBusd { constructor(address _controller, address _vault) public StrategyBusd(_controller, _vault, USDC) { // usdc underlyingIndex = 1; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./StrategyBusd.sol"; contract StrategyBusdDai is StrategyBusd { constructor(address _controller, address _vault) public StrategyBusd(_controller, _vault, DAI) { // dai underlyingIndex = 0; precisionDiv = 1; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../interfaces/curve/StableSwap3.sol"; import "./StrategyCurve.sol"; contract Strategy3Crv is StrategyCurve { address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; constructor( address _controller, address _vault, address _underlying ) public StrategyCurve(_controller, _vault, _underlying) { // Curve // 3Crv lp = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; // 3 Pool pool = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; // Gauge gauge = 0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A; // Minter minter = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // DAO crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; } function _getVirtualPrice() internal view override returns (uint) { return StableSwap3(pool).get_virtual_price(); } function _addLiquidity(uint _amount, uint _index) internal override { uint[3] memory amounts; amounts[_index] = _amount; StableSwap3(pool).add_liquidity(amounts, 0); } function _removeLiquidityOneCoin(uint _lpAmount) internal override { StableSwap3(pool).remove_liquidity_one_coin( _lpAmount, int128(underlyingIndex), 0 ); } function _getMostPremiumToken() internal view override returns (address, uint) { uint[] memory balances = new uint[](3); balances[0] = StableSwap3(pool).balances(0); // DAI balances[1] = StableSwap3(pool).balances(1).mul(1e12); // USDC balances[2] = StableSwap3(pool).balances(2).mul(1e12); // USDT // DAI if (balances[0] <= balances[1] && balances[0] <= balances[2]) { return (DAI, 0); } // USDC if (balances[1] <= balances[0] && balances[1] <= balances[2]) { return (USDC, 1); } return (USDT, 2); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./Strategy3Crv.sol"; contract Strategy3CrvUsdt is Strategy3Crv { constructor(address _controller, address _vault) public Strategy3Crv(_controller, _vault, USDT) { // usdt underlyingIndex = 2; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./Strategy3Crv.sol"; contract Strategy3CrvUsdc is Strategy3Crv { constructor(address _controller, address _vault) public Strategy3Crv(_controller, _vault, USDC) { // usdc underlyingIndex = 1; precisionDiv = 1e12; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "./Strategy3Crv.sol"; contract Strategy3CrvDai is Strategy3Crv { constructor(address _controller, address _vault) public Strategy3Crv(_controller, _vault, DAI) { // dai underlyingIndex = 0; precisionDiv = 1; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./protocol/ITimeLock.sol"; contract TimeLock is ITimeLock { using SafeMath for uint; event NewAdmin(address admin); event NewDelay(uint delay); event Queue( bytes32 indexed txHash, address indexed target, uint value, bytes data, uint eta ); event Execute( bytes32 indexed txHash, address indexed target, uint value, bytes data, uint eta ); event Cancel( bytes32 indexed txHash, address indexed target, uint value, bytes data, uint eta ); uint public constant GRACE_PERIOD = 14 days; uint public constant MIN_DELAY = 1 days; uint public constant MAX_DELAY = 30 days; address public override admin; uint public override delay; mapping(bytes32 => bool) public override queued; constructor(uint _delay) public { admin = msg.sender; _setDelay(_delay); } receive() external payable override {} modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } function setAdmin(address _admin) external override onlyAdmin { require(_admin != address(0), "admin = zero address"); admin = _admin; emit NewAdmin(_admin); } function _setDelay(uint _delay) private { require(_delay >= MIN_DELAY, "delay < min"); require(_delay <= MAX_DELAY, "delay > max"); delay = _delay; emit NewDelay(delay); } /* @dev Only this contract can execute this function */ function setDelay(uint _delay) external override { require(msg.sender == address(this), "!timelock"); _setDelay(_delay); } function _getTxHash( address target, uint value, bytes memory data, uint eta ) private pure returns (bytes32) { return keccak256(abi.encode(target, value, data, eta)); } function getTxHash( address target, uint value, bytes calldata data, uint eta ) external pure override returns (bytes32) { return _getTxHash(target, value, data, eta); } /* @notice Queue transaction @param target Address of contract or account to call @param value Ether value to send @param data Data to send to `target` @eta Execute Tx After. Time after which transaction can be executed. */ function queue( address target, uint value, bytes calldata data, uint eta ) external override onlyAdmin returns (bytes32) { require(eta >= block.timestamp.add(delay), "eta < now + delay"); bytes32 txHash = _getTxHash(target, value, data, eta); queued[txHash] = true; emit Queue(txHash, target, value, data, eta); return txHash; } function execute( address target, uint value, bytes calldata data, uint eta ) external payable override onlyAdmin returns (bytes memory) { bytes32 txHash = _getTxHash(target, value, data, eta); require(queued[txHash], "!queued"); require(block.timestamp >= eta, "eta < now"); require(block.timestamp <= eta.add(GRACE_PERIOD), "eta expired"); queued[txHash] = false; // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value: value}(data); require(success, "tx failed"); emit Execute(txHash, target, value, data, eta); return returnData; } function cancel( address target, uint value, bytes calldata data, uint eta ) external override onlyAdmin { bytes32 txHash = _getTxHash(target, value, data, eta); require(queued[txHash], "!queued"); queued[txHash] = false; emit Cancel(txHash, target, value, data, eta); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface ITimeLock { event NewAdmin(address admin); event NewDelay(uint delay); event Queue( bytes32 indexed txHash, address indexed target, uint value, bytes data, uint eta ); event Execute( bytes32 indexed txHash, address indexed target, uint value, bytes data, uint eta ); event Cancel( bytes32 indexed txHash, address indexed target, uint value, bytes data, uint eta ); function admin() external view returns (address); function delay() external view returns (uint); function queued(bytes32 _txHash) external view returns (bool); function setAdmin(address _admin) external; function setDelay(uint _delay) external; receive() external payable; function getTxHash( address target, uint value, bytes calldata data, uint eta ) external pure returns (bytes32); function queue( address target, uint value, bytes calldata data, uint eta ) external returns (bytes32); function execute( address target, uint value, bytes calldata data, uint eta ) external payable returns (bytes memory); function cancel( address target, uint value, bytes calldata data, uint eta ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../protocol/IVault.sol"; /* solium-disable */ contract MockVault is IVault { address public override admin; address public override controller; address public override token; address public override strategy; address public override timeLock; uint public override reserveMin; uint public override withdrawFee; bool public override paused; mapping(address => bool) public override strategies; mapping(address => bool) public override whitelist; // test helpers uint public _setStrategyMin_; bool public _investWasCalled_; uint public _depositAmount_; uint public _withdrawAmount_; uint public _withdrawMin_; constructor( address _controller, address _timeLock, address _token ) public { admin = msg.sender; controller = _controller; timeLock = _timeLock; token = _token; } function setAdmin(address _admin) external override {} function setController(address _controller) external override {} function setTimeLock(address _timeLock) external override {} function setPause(bool _paused) external override {} function setWhitelist(address _addr, bool _approve) external override {} function setReserveMin(uint _min) external override {} function setWithdrawFee(uint _fee) external override {} function approveStrategy(address _strategy) external override {} function revokeStrategy(address _strategy) external override {} function setStrategy(address _strategy, uint _min) external override { strategy = _strategy; _setStrategyMin_ = _min; } function balanceInVault() external view override returns (uint) { return 0; } function balanceInStrategy() external view override returns (uint) { return 0; } function totalDebtInStrategy() external view override returns (uint) { return 0; } function totalAssets() external view override returns (uint) { return 0; } function minReserve() external view override returns (uint) { return 0; } function availableToInvest() external view override returns (uint) { return 0; } function invest() external override { _investWasCalled_ = true; } function deposit(uint _amount) external override { _depositAmount_ = _amount; } function getExpectedReturn(uint) external view override returns (uint) { return 0; } function withdraw(uint _shares, uint _min) external override { _withdrawAmount_ = _shares; _withdrawMin_ = _min; } function sweep(address _token) external override {} } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; import "../protocol/IVault.sol"; /* solium-disable */ contract MockTimeLock { // test helpers function _setTimeLock_(address _vault, address _timeLock) external { IVault(_vault).setTimeLock(_timeLock); } function _approveStrategy_(address _vault, address _strategy) external { IVault(_vault).approveStrategy(_strategy); } }
unstake withdraw DAI from PICKLE Now we have underlying
function _withdrawUnderlying(uint _pDaiAmount) internal override { MasterChef(CHEF).withdraw(POOL_ID, _pDaiAmount); PickleJar(JAR).withdraw(_pDaiAmount); }
13,453,044
[ 1, 23412, 911, 598, 9446, 463, 18194, 628, 225, 453, 16656, 900, 4494, 732, 1240, 6808, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1918, 9446, 14655, 6291, 12, 11890, 389, 84, 40, 10658, 6275, 13, 2713, 3849, 288, 203, 3639, 13453, 39, 580, 74, 12, 5007, 42, 2934, 1918, 9446, 12, 20339, 67, 734, 16, 389, 84, 40, 10658, 6275, 1769, 203, 203, 3639, 23038, 298, 10813, 12, 46, 985, 2934, 1918, 9446, 24899, 84, 40, 10658, 6275, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xaa282C8aB681fbD501A2B8fA0Ea558cbF5785F73/sources/contracts/AvocadoMultisig/AvocadoMultisig.sol
Address.functionDelegateCall will revert if success = false @notice hook called after executing an upgrade from previous `fromImplementation_`, with flexible bytes `data_`
function _afterUpgradeHook(address fromImplementation_, bytes calldata data_) public virtual onlySelf {}
3,129,134
[ 1, 1887, 18, 915, 9586, 1477, 903, 15226, 309, 2216, 273, 629, 225, 3953, 2566, 1839, 11274, 392, 8400, 628, 2416, 1375, 2080, 13621, 67, 9191, 598, 16600, 1523, 1731, 1375, 892, 67, 68, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5205, 10784, 5394, 12, 2867, 628, 13621, 67, 16, 1731, 745, 892, 501, 67, 13, 1071, 5024, 1338, 10084, 2618, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT-open-group pragma solidity >= 0.5.15; import "../lib/ds-stop/stop.sol"; import "./diamonds/interfaces/Token.sol"; import "./diamonds/interfaces/ValidatorsEvents.sol"; import "./Constants.sol"; import "./Registry.sol"; import "./SafeMath.sol"; contract Deposit is Constants, DSStop, RegistryClient, SimpleAuth, ValidatorsEvents { /// @notice Event emitted when a deposit is received event DepositReceived(uint256 depositID, address depositor, uint256 amount); using SafeMath for uint256; Registry registry; bytes32 constant STORAGE_LOCATION = keccak256("deposit.storage"); struct DepositStorage { uint256 totalDeposited; uint256 depositID; // Monatomically increasing mapping(uint256 => uint256) deposits; // Key is deposit id, value is amount deposited mapping(uint256 => address) depositor; // Key is deposit id, value is who deposited BasicERC20 token; // Minting only required for migration } function depositStorage() internal pure returns (DepositStorage storage s) { bytes32 position = STORAGE_LOCATION; assembly { // solium-disable-line s.slot := position } } constructor(Registry registry_) { registry = registry_; DepositStorage storage ds = depositStorage(); ds.depositID = 1; } function reloadRegistry() external override onlyOperator { DepositStorage storage ds = depositStorage(); ds.token = BasicERC20(registry.lookup(UTILITY_TOKEN)); require(address(ds.token) != address(0), "invalid address for token"); } function deposit(uint256 amount) external stoppable returns (bool) { return _deposit(msg.sender, amount); } function depositFor(address who, uint256 amount) external stoppable returns (bool) { return _deposit(msg.sender, amount); } function _deposit(address who, uint256 amount) internal returns (bool) { DepositStorage storage ds = depositStorage(); ds.deposits[ds.depositID] = amount; ds.depositor[ds.depositID] = who; ds.totalDeposited = ds.totalDeposited.add(amount); emit DepositReceived(ds.depositID, who, amount); ds.depositID = ds.depositID.add(1); require(ds.token.transferFrom(who, address(this), amount), "Transfer failed"); return true; } function directDeposit( uint256 _depositID, address who, uint256 amount ) external stoppable onlyOperator returns (bool) { emit DepositReceived(_depositID, who, amount); DepositStorage storage ds = depositStorage(); uint256 originalAmount = ds.deposits[_depositID]; ds.deposits[_depositID] = amount; ds.depositor[_depositID] = who; if (amount > originalAmount) { uint256 tmp = amount.sub(originalAmount); ds.totalDeposited = ds.totalDeposited.add(tmp); } else if (amount < originalAmount) { uint256 tmp = originalAmount.sub(amount); ds.totalDeposited = ds.totalDeposited.sub(tmp); } MintableERC20 mintable = MintableERC20(address(ds.token)); mintable.mint(address(this), amount); } function deposits(uint256 _depositID) external view returns (uint256) { return depositStorage().deposits[_depositID]; } function depositID() external view returns (uint256) { return depositStorage().depositID; } function setDepositID(uint256 _depositID) external onlyOperator { depositStorage().depositID = _depositID; } function totalDeposited() external view returns (uint256) { return depositStorage().totalDeposited; } }
Minting only required for migration
BasicERC20 token;
5,547,919
[ 1, 49, 474, 310, 1338, 1931, 364, 6333, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 7651, 654, 39, 3462, 1147, 31, 15604, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns (address); function getModuleFee(address _module, uint256 _feeType) external view returns (uint256); function isModule(address _module) external view returns (bool); function isSet(address _setToken) external view returns (bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns (address); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; interface IIntegrationRegistry { function addIntegration( address _module, string memory _id, address _wrapper ) external; function getIntegrationAdapter(address _module, string memory _id) external view returns (address); function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns (address); function isValidIntegration(address _module, string memory _id) external view returns (bool); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; /** * @title IModule * @author Set Protocol * * Interface for interacting with Modules. */ interface IModule { /** * Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included * in case checks need to be made or state needs to be cleared. */ function removeModule() external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; /** * @title IPriceOracle * @author Set Protocol * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; pragma experimental "ABIEncoderV2"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit( address _component, address _positionModule, int256 _realUnit ) external; function editExternalPositionData( address _component, address _positionModule, bytes calldata _data ) external; function invoke( address _target, uint256 _value, bytes calldata _data ) external returns (bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns (int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns (int256); function getComponents() external view returns (address[] memory); function getExternalPositionModules(address _component) external view returns (address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns (bytes memory); function isExternalPositionModule(address _component, address _module) external view returns (bool); function isComponent(address _component) external view returns (bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns (int256); function isInitializedModule(address _module) external view returns (bool); function isPendingModule(address _module) external view returns (bool); function isLocked() external view returns (bool); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import {ISetToken} from "../interfaces/ISetToken.sol"; interface ISetValuer { function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays * * CHANGELOG: * - 4/21/21: Added validatePairsWithArray methods */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns (bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A, ) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint256[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title ExplicitERC20 * @author Set Protocol * * Utility functions for ERC20 transfers that require the explicit amount to be transferred. */ library ExplicitERC20 { using SafeMath for uint256; /** * When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity". * Ensures that the recipient has received the correct quantity (ie no fees taken on transfer) * * @param _token ERC20 token to approve * @param _from The account to transfer tokens from * @param _to The account to transfer tokens to * @param _quantity The quantity to transfer */ function transferFrom( IERC20 _token, address _from, address _to, uint256 _quantity ) internal { // Call specified ERC20 contract to transfer tokens (via proxy). if (_quantity > 0) { uint256 existingBalance = _token.balanceOf(_to); SafeERC20.safeTransferFrom(_token, _from, _to, _quantity); uint256 newBalance = _token.balanceOf(_to); // Verify transfer quantity is reflected in balance require(newBalance == existingBalance.add(_quantity), "Invalid post transfer balance"); } } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SignedSafeMath} from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function * - 4/21/21: Added approximatelyEquals function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 internal constant PRECISE_UNIT = 10**18; int256 internal constant PRECISE_UNIT_INT = 10**18; // Max unsigned integer value uint256 internal constant MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 internal constant MAX_INT_256 = type(int256).max; int256 internal constant MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower(uint256 a, uint256 pow) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++) { uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * @dev Returns true if a =~ b within range, false otherwise. */ function approximatelyEquals( uint256 a, uint256 b, uint256 range ) internal pure returns (bool) { return a <= b.add(range) && a >= b.sub(range); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {ISetToken} from "../../interfaces/ISetToken.sol"; /** * @title Invoke * @author Set Protocol * * A collection of common utility functions for interacting with the SetToken's invoke function */ library Invoke { using SafeMath for uint256; /* ============ Internal ============ */ /** * Instructs the SetToken to set approvals of the ERC20 token to a spender. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to approve * @param _spender The account allowed to spend the SetToken's balance * @param _quantity The quantity of allowance to allow */ function invokeApprove( ISetToken _setToken, address _token, address _spender, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature( "approve(address,uint256)", _spender, _quantity ); _setToken.invoke(_token, 0, callData); } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function invokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity); _setToken.invoke(_token, 0, callData); } } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * The new SetToken balance must equal the existing balance less the quantity transferred * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function strictInvokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { // Retrieve current balance of token for the SetToken uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken)); Invoke.invokeTransfer(_setToken, _token, _to, _quantity); // Get new balance of transferred token for SetToken uint256 newBalance = IERC20(_token).balanceOf(address(_setToken)); // Verify only the transfer quantity is subtracted require(newBalance == existingBalance.sub(_quantity), "Invalid post transfer balance"); } } /** * Instructs the SetToken to unwrap the passed quantity of WETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeUnwrapWETH( ISetToken _setToken, address _weth, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity); _setToken.invoke(_weth, 0, callData); } /** * Instructs the SetToken to wrap the passed quantity of ETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeWrapWETH( ISetToken _setToken, address _weth, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature("deposit()"); _setToken.invoke(_weth, _quantity, callData); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {AddressArrayUtils} from "../../lib/AddressArrayUtils.sol"; import {ExplicitERC20} from "../../lib/ExplicitERC20.sol"; import {IController} from "../../interfaces/IController.sol"; import {IModule} from "../../interfaces/IModule.sol"; import {ISetToken} from "../../interfaces/ISetToken.sol"; import {Invoke} from "./Invoke.sol"; import {Position} from "./Position.sol"; import {PreciseUnitMath} from "../../lib/PreciseUnitMath.sol"; import {ResourceIdentifier} from "./ResourceIdentifier.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SignedSafeMath} from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title ModuleBase * @author Set Protocol * * Abstract class that houses common Module-related state and functions. * * CHANGELOG: * - 4/21/21: Delegated modifier logic to internal helpers to reduce contract size * */ abstract contract ModuleBase is IModule { using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; using PreciseUnitMath for uint256; using ResourceIdentifier for IController; using SafeCast for int256; using SafeCast for uint256; using SafeMath for uint256; using SignedSafeMath for int256; /* ============ State Variables ============ */ // Address of the controller IController public controller; /* ============ Modifiers ============ */ modifier onlyManagerAndValidSet(ISetToken _setToken) { _validateOnlyManagerAndValidSet(_setToken); _; } modifier onlySetManager(ISetToken _setToken, address _caller) { _validateOnlySetManager(_setToken, _caller); _; } modifier onlyValidAndInitializedSet(ISetToken _setToken) { _validateOnlyValidAndInitializedSet(_setToken); _; } /** * Throws if the sender is not a SetToken's module or module not enabled */ modifier onlyModule(ISetToken _setToken) { _validateOnlyModule(_setToken); _; } /** * Utilized during module initializations to check that the module is in pending state * and that the SetToken is valid */ modifier onlyValidAndPendingSet(ISetToken _setToken) { _validateOnlyValidAndPendingSet(_setToken); _; } /* ============ Constructor ============ */ /** * Set state variables and map asset pairs to their oracles * * @param _controller Address of controller contract */ constructor(IController _controller) { controller = _controller; } /* ============ Internal Functions ============ */ /** * Transfers tokens from an address (that has set allowance on the module). * * @param _token The address of the ERC20 token * @param _from The address to transfer from * @param _to The address to transfer to * @param _quantity The number of tokens to transfer */ function transferFrom( IERC20 _token, address _from, address _to, uint256 _quantity ) internal { ExplicitERC20.transferFrom(_token, _from, _to, _quantity); } /** * Gets the integration for the module with the passed in name. Validates that the address is not empty */ function getAndValidateAdapter(string memory _integrationName) internal view returns (address) { bytes32 integrationHash = getNameHash(_integrationName); return getAndValidateAdapterWithHash(integrationHash); } /** * Gets the integration for the module with the passed in hash. Validates that the address is not empty */ function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns (address) { address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash( address(this), _integrationHash ); require(adapter != address(0), "Must be valid adapter"); return adapter; } /** * Gets the total fee for this module of the passed in index (fee % * quantity) */ function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns (uint256) { uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex); return _quantity.preciseMul(feePercentage); } /** * Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient */ function payProtocolFeeFromSetToken( ISetToken _setToken, address _token, uint256 _feeQuantity ) internal { if (_feeQuantity > 0) { _setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity); } } /** * Returns true if the module is in process of initialization on the SetToken */ function isSetPendingInitialization(ISetToken _setToken) internal view returns (bool) { return _setToken.isPendingModule(address(this)); } /** * Returns true if the address is the SetToken's manager */ function isSetManager(ISetToken _setToken, address _toCheck) internal view returns (bool) { return _setToken.manager() == _toCheck; } /** * Returns true if SetToken must be enabled on the controller * and module is registered on the SetToken */ function isSetValidAndInitialized(ISetToken _setToken) internal view returns (bool) { return controller.isSet(address(_setToken)) && _setToken.isInitializedModule(address(this)); } /** * Hashes the string and returns a bytes32 value */ function getNameHash(string memory _name) internal pure returns (bytes32) { return keccak256(bytes(_name)); } /* ============== Modifier Helpers =============== * Internal functions used to reduce bytecode size */ /** * Caller must SetToken manager and SetToken must be valid and initialized */ function _validateOnlyManagerAndValidSet(ISetToken _setToken) internal view { require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager"); require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); } /** * Caller must SetToken manager */ function _validateOnlySetManager(ISetToken _setToken, address _caller) internal view { require(isSetManager(_setToken, _caller), "Must be the SetToken manager"); } /** * SetToken must be valid and initialized */ function _validateOnlyValidAndInitializedSet(ISetToken _setToken) internal view { require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); } /** * Caller must be initialized module and module must be enabled on the controller */ function _validateOnlyModule(ISetToken _setToken) internal view { require( _setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED, "Only the module can call" ); require(controller.isModule(msg.sender), "Module must be enabled on controller"); } /** * SetToken must be in a pending state and module must be in pending state */ function _validateOnlyValidAndPendingSet(ISetToken _setToken) internal view { require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken"); require(isSetPendingInitialization(_setToken), "Must be pending initialization"); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; pragma experimental "ABIEncoderV2"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SignedSafeMath} from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import {ISetToken} from "../../interfaces/ISetToken.sol"; import {PreciseUnitMath} from "../../lib/PreciseUnitMath.sol"; /** * @title Position * @author Set Protocol * * Collection of helper functions for handling and updating SetToken Positions * * CHANGELOG: * - Updated editExternalPosition to work when no external position is associated with module */ library Position { using SafeCast for uint256; using SafeMath for uint256; using SafeCast for int256; using SignedSafeMath for int256; using PreciseUnitMath for uint256; /* ============ Helper ============ */ /** * Returns whether the SetToken has a default position for a given component (if the real unit is > 0) */ function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns (bool) { return _setToken.getDefaultPositionRealUnit(_component) > 0; } /** * Returns whether the SetToken has an external position for a given component (if # of position modules is > 0) */ function hasExternalPosition(ISetToken _setToken, address _component) internal view returns (bool) { return _setToken.getExternalPositionModules(_component).length > 0; } /** * Returns whether the SetToken component default position real unit is greater than or equal to units passed in. */ function hasSufficientDefaultUnits( ISetToken _setToken, address _component, uint256 _unit ) internal view returns (bool) { return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); } /** * Returns whether the SetToken component external position is greater than or equal to the real units passed in. */ function hasSufficientExternalUnits( ISetToken _setToken, address _component, address _positionModule, uint256 _unit ) internal view returns (bool) { return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256(); } /** * If the position does not exist, create a new Position and add to the SetToken. If it already exists, * then set the position units. If the new units is 0, remove the position. Handles adding/removing of * components where needed (in light of potential external positions). * * @param _setToken Address of SetToken being modified * @param _component Address of the component * @param _newUnit Quantity of Position units - must be >= 0 */ function editDefaultPosition( ISetToken _setToken, address _component, uint256 _newUnit ) internal { bool isPositionFound = hasDefaultPosition(_setToken, _component); if (!isPositionFound && _newUnit > 0) { // If there is no Default Position and no External Modules, then component does not exist if (!hasExternalPosition(_setToken, _component)) { _setToken.addComponent(_component); } } else if (isPositionFound && _newUnit == 0) { // If there is a Default Position and no external positions, remove the component if (!hasExternalPosition(_setToken, _component)) { _setToken.removeComponent(_component); } } _setToken.editDefaultPositionUnit(_component, _newUnit.toInt256()); } /** * Update an external position and remove and external positions or components if necessary. The logic flows as follows: * 1) If component is not already added then add component and external position. * 2) If component is added but no existing external position using the passed module exists then add the external position. * 3) If the existing position is being added to then just update the unit and data * 4) If the position is being closed and no other external positions or default positions are associated with the component * then untrack the component and remove external position. * 5) If the position is being closed and other existing positions still exist for the component then just remove the * external position. * * @param _setToken SetToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function editExternalPosition( ISetToken _setToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { if (_newUnit != 0) { if (!_setToken.isComponent(_component)) { _setToken.addComponent(_component); _setToken.addExternalPositionModule(_component, _module); } else if (!_setToken.isExternalPositionModule(_component, _module)) { _setToken.addExternalPositionModule(_component, _module); } _setToken.editExternalPositionUnit(_component, _module, _newUnit); _setToken.editExternalPositionData(_component, _module, _data); } else { require(_data.length == 0, "Passed data must be null"); // If no default or external position remaining then remove component from components array if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) { address[] memory positionModules = _setToken.getExternalPositionModules(_component); if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) { require( positionModules[0] == _module, "External positions must be 0 to remove component" ); _setToken.removeComponent(_component); } _setToken.removeExternalPositionModule(_component, _module); } } } /** * Get total notional amount of Default position * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _positionUnit Quantity of Position units * * @return Total notional amount of units */ function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _setTokenSupply.preciseMul(_positionUnit); } /** * Get position unit from total notional amount * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _totalNotional Total notional amount of component prior to * @return Default position unit */ function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) { return _totalNotional.preciseDiv(_setTokenSupply); } /** * Get the total tracked balance - total supply * position unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @return Notional tracked balance */ function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns (uint256) { int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component); return _setToken.totalSupply().preciseMul(positionUnit.toUint256()); } /** * Calculates the new default position unit and performs the edit with the new unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @param _setTotalSupply Current SetToken supply * @param _componentPreviousBalance Pre-action component balance * @return Current component balance * @return Previous position unit * @return New position unit */ function calculateAndEditDefaultPosition( ISetToken _setToken, address _component, uint256 _setTotalSupply, uint256 _componentPreviousBalance ) internal returns ( uint256, uint256, uint256 ) { uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken)); uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256(); uint256 newTokenUnit; if (currentBalance > 0) { newTokenUnit = calculateDefaultEditPositionUnit( _setTotalSupply, _componentPreviousBalance, currentBalance, positionUnit ); } else { newTokenUnit = 0; } editDefaultPosition(_setToken, _component, newTokenUnit); return (currentBalance, positionUnit, newTokenUnit); } /** * Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state * The intention is to make updates to the units without accidentally picking up airdropped assets as well. * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _preTotalNotional Total notional amount of component prior to executing action * @param _postTotalNotional Total notional amount of component after the executing action * @param _prePositionUnit Position unit of SetToken prior to executing action * @return New position unit */ function calculateDefaultEditPositionUnit( uint256 _setTokenSupply, uint256 _preTotalNotional, uint256 _postTotalNotional, uint256 _prePositionUnit ) internal pure returns (uint256) { // If pre action total notional amount is greater then subtract post action total notional and calculate new position units uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply)); return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import {IController} from "../../interfaces/IController.sol"; import {IIntegrationRegistry} from "../../interfaces/IIntegrationRegistry.sol"; import {IPriceOracle} from "../../interfaces/IPriceOracle.sol"; import {ISetValuer} from "../../interfaces/ISetValuer.sol"; /** * @title ResourceIdentifier * @author Set Protocol * * A collection of utility functions to fetch information related to Resource contracts in the system */ library ResourceIdentifier { // IntegrationRegistry will always be resource ID 0 in the system uint256 internal constant INTEGRATION_REGISTRY_RESOURCE_ID = 0; // PriceOracle will always be resource ID 1 in the system uint256 internal constant PRICE_ORACLE_RESOURCE_ID = 1; // SetValuer resource will always be resource ID 2 in the system uint256 internal constant SET_VALUER_RESOURCE_ID = 2; /* ============ Internal ============ */ /** * Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on * the Controller */ function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) { return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID)); } /** * Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller */ function getPriceOracle(IController _controller) internal view returns (IPriceOracle) { return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID)); } /** * Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller */ function getSetValuer(IController _controller) internal view returns (ISetValuer) { return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID)); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; pragma experimental "ABIEncoderV2"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {AddressArrayUtils} from "../../lib/AddressArrayUtils.sol"; import {IController} from "../../interfaces/IController.sol"; import {ISetToken} from "../../interfaces/ISetToken.sol"; import {Invoke} from "../lib/Invoke.sol"; import {ModuleBase} from "../lib/ModuleBase.sol"; import {Position} from "../lib/Position.sol"; import {PreciseUnitMath} from "../../lib/PreciseUnitMath.sol"; /** * @title AirdropModule * @author Set Protocol * * Module that enables managers to absorb tokens sent to the SetToken into the token's positions. With each SetToken, * managers are able to specify 1) the airdrops they want to include, 2) an airdrop fee recipient, 3) airdrop fee, * and 4) whether all users are allowed to trigger an airdrop. */ contract AirdropModule is ModuleBase, ReentrancyGuard { using PreciseUnitMath for uint256; using SafeMath for uint256; using Position for uint256; using SafeCast for int256; using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; /* ============ Structs ============ */ struct AirdropSettings { address[] airdrops; // Array of tokens manager is allowing to be absorbed address feeRecipient; // Address airdrop fees are sent to uint256 airdropFee; // Percentage in preciseUnits of airdrop sent to feeRecipient (1e16 = 1%) bool anyoneAbsorb; // Boolean indicating if any address can call absorb or just the manager } /* ============ Events ============ */ event ComponentAbsorbed( ISetToken indexed _setToken, address _absorbedToken, uint256 _absorbedQuantity, uint256 _managerFee, uint256 _protocolFee ); /* ============ Modifiers ============ */ /** * Throws if claim is confined to the manager and caller is not the manager */ modifier onlyValidCaller(ISetToken _setToken) { require(_isValidCaller(_setToken), "Must be valid caller"); _; } /* ============ Constants ============ */ uint256 public constant AIRDROP_MODULE_PROTOCOL_FEE_INDEX = 0; /* ============ State Variables ============ */ mapping(ISetToken => AirdropSettings) public airdropSettings; /* ============ Constructor ============ */ // solhint-disable-next-line no-empty-blocks constructor(IController _controller) ModuleBase(_controller) {} /* ============ External Functions ============ */ /** * Absorb passed tokens into respective positions. If airdropFee defined, send portion to feeRecipient and portion to * protocol feeRecipient address. Callable only by manager unless manager has set anyoneAbsorb to true. * * @param _setToken Address of SetToken * @param _tokens Array of tokens to absorb */ function batchAbsorb(ISetToken _setToken, address[] memory _tokens) external nonReentrant onlyValidCaller(_setToken) onlyValidAndInitializedSet(_setToken) { _batchAbsorb(_setToken, _tokens); } /** * Absorb specified token into position. If airdropFee defined, send portion to feeRecipient and portion to * protocol feeRecipient address. Callable only by manager unless manager has set anyoneAbsorb to true. * * @param _setToken Address of SetToken * @param _token Address of token to absorb */ function absorb(ISetToken _setToken, address _token) external nonReentrant onlyValidCaller(_setToken) onlyValidAndInitializedSet(_setToken) { _absorb(_setToken, _token); } /** * SET MANAGER ONLY. Adds new tokens to be added to positions when absorb is called. * * @param _setToken Address of SetToken * @param _airdrop List of airdrops to add */ function addAirdrop(ISetToken _setToken, address _airdrop) external onlyManagerAndValidSet(_setToken) { require(!isAirdropToken(_setToken, _airdrop), "Token already added."); airdropSettings[_setToken].airdrops.push(_airdrop); } /** * SET MANAGER ONLY. Removes tokens from list to be absorbed. * * @param _setToken Address of SetToken * @param _airdrop List of airdrops to remove */ function removeAirdrop(ISetToken _setToken, address _airdrop) external onlyManagerAndValidSet(_setToken) { require(isAirdropToken(_setToken, _airdrop), "Token not added."); airdropSettings[_setToken].airdrops = airdropSettings[_setToken].airdrops.remove(_airdrop); } /** * SET MANAGER ONLY. Update whether manager allows other addresses to call absorb. * * @param _setToken Address of SetToken */ function updateAnyoneAbsorb(ISetToken _setToken) external onlyManagerAndValidSet(_setToken) { airdropSettings[_setToken].anyoneAbsorb = !airdropSettings[_setToken].anyoneAbsorb; } /** * SET MANAGER ONLY. Update address manager fees are sent to. * * @param _setToken Address of SetToken * @param _newFeeRecipient Address of new fee recipient */ function updateFeeRecipient(ISetToken _setToken, address _newFeeRecipient) external onlySetManager(_setToken, msg.sender) onlyValidAndInitializedSet(_setToken) { require(_newFeeRecipient != address(0), "Passed address must be non-zero"); airdropSettings[_setToken].feeRecipient = _newFeeRecipient; } /** * SET MANAGER ONLY. Update airdrop fee percentage. * * @param _setToken Address of SetToken * @param _newFee Percentage, in preciseUnits, of new airdrop fee (1e16 = 1%) */ function updateAirdropFee(ISetToken _setToken, uint256 _newFee) external onlySetManager(_setToken, msg.sender) onlyValidAndInitializedSet(_setToken) { require(_newFee < PreciseUnitMath.preciseUnit(), "Airdrop fee can't exceed 100%"); // Absorb all outstanding tokens before fee is updated _batchAbsorb(_setToken, airdropSettings[_setToken].airdrops); airdropSettings[_setToken].airdropFee = _newFee; } /** * SET MANAGER ONLY. Initialize module with SetToken and set initial airdrop tokens as well as specify * whether anyone can call absorb. * * @param _setToken Address of SetToken * @param _airdropSettings Struct of airdrop setting for Set including accepted airdrops, feeRecipient, * airdropFee, and indicating if anyone can call an absorb */ function initialize(ISetToken _setToken, AirdropSettings memory _airdropSettings) external onlySetManager(_setToken, msg.sender) onlyValidAndPendingSet(_setToken) { require(_airdropSettings.airdrops.length > 0, "At least one token must be passed."); require(_airdropSettings.airdropFee <= PreciseUnitMath.preciseUnit(), "Fee must be <= 100%."); airdropSettings[_setToken] = _airdropSettings; _setToken.initializeModule(); } /** * Removes this module from the SetToken, via call by the SetToken. Token's airdrop settings are deleted. * Airdrops are not absorbed. */ function removeModule() external override { delete airdropSettings[ISetToken(msg.sender)]; } /** * Get list of tokens approved to collect airdrops for the SetToken. * * @param _setToken Address of SetToken * @return Array of tokens approved for airdrops */ function getAirdrops(ISetToken _setToken) external view returns (address[] memory) { return _airdrops(_setToken); } /** * Get boolean indicating if token is approved for airdrops. * * @param _setToken Address of SetToken * @return Boolean indicating approval for airdrops */ function isAirdropToken(ISetToken _setToken, address _token) public view returns (bool) { return _airdrops(_setToken).contains(_token); } /* ============ Internal Functions ============ */ /** * Check token approved for airdrops then handle airdropped postion. */ function _absorb(ISetToken _setToken, address _token) internal { require(isAirdropToken(_setToken, _token), "Must be approved token."); _handleAirdropPosition(_setToken, _token); } function _batchAbsorb(ISetToken _setToken, address[] memory _tokens) internal { for (uint256 i = 0; i < _tokens.length; i++) { _absorb(_setToken, _tokens[i]); } } /** * Calculate amount of tokens airdropped since last absorption, then distribute fees and update position. * * @param _setToken Address of SetToken * @param _token Address of airdropped token */ function _handleAirdropPosition(ISetToken _setToken, address _token) internal { uint256 preFeeTokenBalance = ERC20(_token).balanceOf(address(_setToken)); uint256 amountAirdropped = preFeeTokenBalance.sub(_setToken.getDefaultTrackedBalance(_token)); if (amountAirdropped > 0) { (uint256 managerTake, uint256 protocolTake, uint256 totalFees) = _handleFees( _setToken, _token, amountAirdropped ); uint256 newUnit = _getPostAirdropUnit(_setToken, preFeeTokenBalance, totalFees); _setToken.editDefaultPosition(_token, newUnit); emit ComponentAbsorbed(_setToken, _token, amountAirdropped, managerTake, protocolTake); } } /** * Calculate fee total and distribute between feeRecipient defined on module and the protocol feeRecipient. * * @param _setToken Address of SetToken * @param _component Address of airdropped component * @param _amountAirdropped Amount of tokens airdropped to the SetToken * @return Amount of airdropped tokens set aside for manager fees * @return Amount of airdropped tokens set aside for protocol fees * @return Total fees paid */ function _handleFees( ISetToken _setToken, address _component, uint256 _amountAirdropped ) internal returns ( uint256, uint256, uint256 ) { uint256 airdropFee = airdropSettings[_setToken].airdropFee; if (airdropFee > 0) { uint256 managerTake = _amountAirdropped.preciseMul(airdropFee); uint256 protocolTake = ModuleBase.getModuleFee( AIRDROP_MODULE_PROTOCOL_FEE_INDEX, managerTake ); uint256 netManagerTake = managerTake.sub(protocolTake); uint256 totalFees = netManagerTake.add(protocolTake); _setToken.invokeTransfer(_component, airdropSettings[_setToken].feeRecipient, netManagerTake); ModuleBase.payProtocolFeeFromSetToken(_setToken, _component, protocolTake); return (netManagerTake, protocolTake, totalFees); } else { return (0, 0, 0); } } /** * Retrieve new unit, which is the current balance less fees paid divided by total supply */ function _getPostAirdropUnit( ISetToken _setToken, uint256 _totalComponentBalance, uint256 _totalFeesPaid ) internal view returns (uint256) { uint256 totalSupply = _setToken.totalSupply(); return totalSupply.getDefaultPositionUnit(_totalComponentBalance.sub(_totalFeesPaid)); } /** * If absorption is confined to the manager, manager must be caller */ function _isValidCaller(ISetToken _setToken) internal view returns (bool) { return airdropSettings[_setToken].anyoneAbsorb || isSetManager(_setToken, msg.sender); } function _airdrops(ISetToken _setToken) internal view returns (address[] memory) { return airdropSettings[_setToken].airdrops; } }
* @title IModule @author Set Protocol Interface for interacting with Modules./
interface IModule { function removeModule() external; Copyright 2020 Set Labs Inc. pragma solidity 0.7.6; }
100,857
[ 1, 45, 3120, 225, 1000, 4547, 6682, 364, 16592, 310, 598, 25493, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 3120, 288, 203, 225, 445, 1206, 3120, 1435, 3903, 31, 203, 565, 25417, 26599, 20, 1000, 511, 5113, 15090, 18, 203, 683, 9454, 18035, 560, 374, 18, 27, 18, 26, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x4CC84b41ECECC387244512242Eec226Eb7948A92/sources/browser/KASSIAHOME.sol
* @notice Currently returns the internal storage amount @param who The address to query. @return The underlying balance of the specified address./
function balanceOfUnderlying(address who) external view returns (uint256) { return _kassiahomeBalances[who]; }
9,696,393
[ 1, 3935, 715, 1135, 326, 2713, 2502, 3844, 225, 10354, 1021, 1758, 358, 843, 18, 327, 1021, 6808, 11013, 434, 326, 1269, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11013, 951, 14655, 6291, 12, 2867, 10354, 13, 203, 1377, 3903, 203, 1377, 1476, 203, 1377, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 1377, 327, 389, 79, 428, 1155, 8712, 38, 26488, 63, 3350, 83, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4.21; import "usingtellor/contracts/UsingTellor.sol"; /** * @title Tellor Fund * @notice Allows the Tellor communtiy to propose and fund different * activities like paid AMA's, listing fees influencer's interviews. * The proposal is originally funded by the creator and if it fails to * reach the minimum threshold it refunds the funds to the users that "voted" */ contract TellorFund is UsingTellor{ /*Variables*/ uint private proposalCount; uint public tellorPriceID; //?? uint public granularity; //?? uint[] openProposals; struct Proposal{ string title; string description; address owner; uint minAmountUSD; uint expirationDate; uint trbBalance; bool open; bool passed; } struct Funder{ address funder; uint amount; } struct Statement{ uint id; uint amount; } mapping(uint => Proposal) idToProposal; mapping(uint => Funder[]) idToFunders; mapping(address => Statement[]) addressToStatements;//??? mapping(uint => uint) idToOpenIndex; mapping(address => uint) availableForWithdraw; /*Events*/ event NewProposal(uint _id,string _title,string _desc,uint _minAmountUSD,uint _daystilComplete); event ProposalFunded(uint _id, address _funder, uint _amount); event ProposalClosed(uint _id, bool _funded, uint _amount); /* * @dev Sets the usercontract, tellor's request data Id and * amount of decimals to include(granularity) * @param _userContract is the userContract address for Tellor * @param _tellorPriceID is Tellor's request ID to read data from ?? * @param _granularity is the amount of decimals to include in the price feed */ constructor(address _userContract, uint _tellorPriceID, uint _granularity) public UsingTellor(_userContract){ proposalCount = 1; tellorPriceID = _tellorPriceID; granularity = _granularity; openProposals.length++; } /* * @dev Creates a proposoal * @param _title is the proposal's title * @param _desc is the proposal description * @param _minAmountUSD is the minimun USD threshold to fund before the proposal goes to a vote??? * @param _daystilComplete number of days allowed for funding??? * @return proposal Id */ //be sure to approve first function createProposal(string calldata _title, string calldata _desc,uint _minAmountUSD, uint _daystilComplete) external returns(uint _id){ Tellor _tellor = Tellor(tellorUserContract.tellorStorageAddress()); require(_tellor.transferFrom(msg.sender,address(this),1e18), "Fee to create proposal failed to tranfer"); require(_daystilComplete < 30); _id = proposalCount; proposalCount++; idToProposal[_id] = Proposal({ title:_title, description:_desc, owner:msg.sender, minAmountUSD:_minAmountUSD, expirationDate:now + _daystilComplete * 86400, trbBalance:0, open:true, passed:false }); idToOpenIndex[_id] = openProposals.length; openProposals.push(_id); Statement memory thisStatement= Statement({ id:_id, amount:0 }); addressToStatements[msg.sender].push(thisStatement);//what is the statememt??? emit NewProposal(_id,_title,_desc,_minAmountUSD,_daystilComplete); } /* * @dev Funds a specified proposoal * @param _id is the proposal Id * @param _amountTRB amount of TRB to fund */ function fund(uint _id, uint _amountTRB) external { require(_amountTRB > 0); Proposal storage thisProp = idToProposal[_id]; require(thisProp.open); Tellor _tellor = Tellor(tellorUserContract.tellorStorageAddress()); require(_tellor.transferFrom(msg.sender,address(this),_amountTRB), "Funding Failed"); Statement memory thisStatement= Statement({ id:_id, amount:_amountTRB }); addressToStatements[msg.sender].push(thisStatement); thisProp.trbBalance += _amountTRB; Funder memory thisFunder = Funder({ funder:msg.sender, amount:_amountTRB }); idToFunders[_id].push(thisFunder); emit ProposalFunded(_id,msg.sender,_amountTRB); } /* * @dev Closes the specified proposal. Closes the proposal, it makes the funders * funds available for withdraw if the proposal fails, and updates the proposal array. * @param _id is the proposal id */ function closeProposal(uint _id) external{ Proposal storage thisProp = idToProposal[_id]; require(thisProp.open); require(_id > 0); require(now > thisProp.expirationDate); Tellor _tellor = Tellor(tellorUserContract.tellorStorageAddress()); if(percentFunded(_id) >= 100){ thisProp.passed = true; _tellor.transfer(thisProp.owner,thisProp.trbBalance); } else{ Funder[] storage theseFunders = idToFunders[_id]; for(uint i=0;i < theseFunders.length;i++){ availableForWithdraw[theseFunders[i].funder] += theseFunders[i].amount; } } uint _index = idToOpenIndex[_id]; if(_index == openProposals.length - 1){ openProposals.length--; } else{ uint _lastId = openProposals[openProposals.length - 1]; openProposals[_index] = _lastId; idToOpenIndex[_lastId] = _index; openProposals.length--; idToOpenIndex[_id] = 0; } thisProp.open = false; emit ProposalClosed(_id,thisProp.passed,thisProp.trbBalance); thisProp.trbBalance = 0; } /* * @dev Allows funders to withdraw their funds if the proposal was unsuccessful */ function withdrawMoney() external{ Tellor _tellor = Tellor(tellorUserContract.tellorStorageAddress()); uint _amt = availableForWithdraw[msg.sender]; availableForWithdraw[msg.sender] =0; _tellor.transfer(msg.sender,_amt); } /* * @dev Getter function for all open proposals * @returns an array with all open proposals */ function getAllOpenProposals() external view returns(uint[] memory){ return openProposals; } /* * @dev Getter function for amount available for withdraw by funder(specified address) * @param _user is the funder address * @return amount available for withdraw for the specified user address */ function getAvailableForWithdraw(address _user) external returns(uint){ return availableForWithdraw[_user]; } /* * @dev Getter function for the proposal information by the id * @param _id is the proposal id * @return title of proposal * @return description of proposal * @return owner of proposal * @return minAmountUSD for proposal to pass * @return expirationDate of proposal * @return trbBalance of proposal * @return open- bool true if proposal is still open * @return passed- bool true if proposal passed * @return percentFunded */ function getProposalById(uint _id) external view returns(string memory,string memory,address,uint,uint,uint,bool,bool,uint){ Proposal memory t = idToProposal[_id]; return (t.title,t.description,t.owner,t.minAmountUSD,t.expirationDate,t.trbBalance,t.open,t.passed,100 * (t.trbBalance* viewTellorPrice()/1e20) / t.minAmountUSD); } /* * @dev Getter function for all proposals funded by the specified address * @param _funder is the funder address to look up * @return two arrays containing all proposals and amounts contributed to each by the specified funder address */ function getProposalsByAddress(address _funder) public view returns(uint[] memory propArray,uint[] memory amountArray){ Statement[] memory theseStatements = addressToStatements[_funder]; propArray = new uint[](theseStatements.length); amountArray = new uint[](theseStatements.length); for(uint i=0;i < theseStatements.length;i++){ propArray[i] = theseStatements[i].id; amountArray[i]= theseStatements[i].amount; } return (propArray,amountArray); } /* * @dev Getter function for funder address by proposal id * @param _id is the proposal id * @return array of all addresses that have funded the specified proposoal id */ function getAddressesById(uint _id) public view returns(address[] memory addArray){ Funder[] memory theseFunders = idToFunders[_id]; addArray = new address[](theseFunders.length); for(uint i=0;i < theseFunders.length;i++){ addArray[i] = theseFunders[i].funder; } } /* * @dev Gets the percent funded for the specified proposal * @param _id is the proposal id * @return the percent funded for the specified proposal id */ function percentFunded(uint _id) public view returns(uint){ Proposal memory thisProp = idToProposal[_id]; return (thisProp.trbBalance* viewTellorPrice()/1e18) / thisProp.minAmountUSD ; } /* * @dev Gets Tellor's Price for the request ID specified in the constructor * @returns Tellors price value */ function viewTellorPrice() public view returns(uint){ bool _didget; uint _value; uint _timestamp; (_didget,_value,_timestamp) = getCurrentValue(tellorPriceID); if(!_didget){ return 0; } else if(_timestamp > now - 60 minutes){ for(uint i=120;i< 2400;i++){ (_didget,_value,_timestamp) = getAnyDataAfter(tellorPriceID,now - i * 60); //if the value was obtained within the hour, stop looping. if(_didget && _timestamp < now - 60 minutes){ i = 2400; } else if(!_didget){ return 0; } } } return _value*100/granularity; } /* * @dev Getter for proposal count * @return the number of proposals */ function getProposalCount() public view returns(uint){ return proposalCount -1; } /* * @dev Getter function for Tellor's address * @param the Tellor's Master address */ function tellorAddress() public view returns(address){ return tellorUserContract.tellorStorageAddress(); } }
what is the statememt???
addressToStatements[msg.sender].push(thisStatement);
5,401,090
[ 1, 23770, 353, 326, 919, 3917, 88, 14646, 35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1758, 774, 14663, 63, 3576, 18, 15330, 8009, 6206, 12, 2211, 3406, 1769, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x931D8441599B533DfEd618E93Fc32d110543a087/sources/contracts/radiant/staking/MultiFeeDistribution.sol
* @notice Update user reward info. @param account address/
function _updateReward(address account) internal { uint256 balance = _balances[account].lockedWithMultiplier; uint256 length = rewardTokens.length; for (uint256 i = 0; i < length; ) { address token = rewardTokens[i]; uint256 rpt = rewardPerToken(token); Reward storage r = rewardData[token]; r.rewardPerTokenStored = rpt; r.lastUpdateTime = lastTimeRewardApplicable(token); if (account != address(this)) { rewards[account][token] = _earned(account, token, balance, rpt); userRewardPerTokenPaid[account][token] = rpt; } unchecked { i++; } } }
8,422,296
[ 1, 1891, 729, 19890, 1123, 18, 225, 2236, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 389, 2725, 17631, 1060, 12, 2867, 2236, 13, 2713, 288, 203, 202, 202, 11890, 5034, 11013, 273, 389, 70, 26488, 63, 4631, 8009, 15091, 1190, 23365, 31, 203, 202, 202, 11890, 5034, 769, 273, 19890, 5157, 18, 2469, 31, 203, 202, 202, 1884, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 769, 31, 262, 288, 203, 1082, 202, 2867, 1147, 273, 19890, 5157, 63, 77, 15533, 203, 1082, 202, 11890, 5034, 31656, 273, 19890, 2173, 1345, 12, 2316, 1769, 203, 203, 1082, 202, 17631, 1060, 2502, 436, 273, 19890, 751, 63, 2316, 15533, 203, 1082, 202, 86, 18, 266, 2913, 2173, 1345, 18005, 273, 31656, 31, 203, 1082, 202, 86, 18, 2722, 1891, 950, 273, 31323, 17631, 1060, 27873, 12, 2316, 1769, 203, 203, 1082, 202, 430, 261, 4631, 480, 1758, 12, 2211, 3719, 288, 203, 9506, 202, 266, 6397, 63, 4631, 6362, 2316, 65, 273, 389, 73, 1303, 329, 12, 4631, 16, 1147, 16, 11013, 16, 31656, 1769, 203, 9506, 202, 1355, 17631, 1060, 2173, 1345, 16507, 350, 63, 4631, 6362, 2316, 65, 273, 31656, 31, 203, 1082, 202, 97, 203, 1082, 202, 5847, 288, 203, 9506, 202, 77, 9904, 31, 203, 1082, 202, 97, 203, 202, 202, 97, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.6; pragma experimental ABIEncoderV2; import "./NumericalMath.sol"; import "./FixidityLib.sol"; import "https://github.com/smartcontractkit/chainlink/blob/master/evm-contracts/src/v0.6/VRFConsumerBase.sol"; import "https://github.com/jstat17/Random-Walk-NFT/blob/main/openzeppelin-contracts/token/ERC721/ERC721.sol"; /** * @title RandomWalkNFT * @author John Michael Statheros (GitHub: jstat17) * @notice Contract for creating random walk map NFTs. */ contract RandomWalkNFT is ERC721, VRFConsumerBase { bytes32 internal keyHash = 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311; address internal vrfCoordinator = 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B; address internal linkToken = 0x01BE23585060835E02B77ef475b0Cc51aA1e0709; uint256 internal fee; int256 public randomResult; struct RandomWalk { string name; uint256 ID; uint256 nodes; int256[] x; int256[] y; } RandomWalk[] private randomWalks; mapping(bytes32 => string) public requestToMapName; mapping(bytes32 => address) public requestToSender; mapping(bytes32 => uint256) public requestToTokenID; mapping(bytes32 => uint256) public requestToNodes; mapping(address => bytes32) public senderToRequest; struct Walker { int256 x; int256 y; int256 currAngle; int256 angle_orig; uint8 digits; } /** * Constructor inherits VRFConsumerBase * * Network: Kovan * Chainlink VRF Coordinator address: 0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9 * LINK token address: 0xa36085F69e2889c224210F603D836748e7dC0088 * Key Hash: 0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4 * * Network: Rinkeby * Chainlink VRF Coordinator address: 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B * LINK token address: 0x01be23585060835e02b77ef475b0cc51aa1e0709 * Key Hash: 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311 */ constructor () //constructor (address _VRFCoordinator, address _LinkToken, bytes32 _keyHash) ERC721("Random Walk","RWalk") VRFConsumerBase(vrfCoordinator, linkToken) //VRFConsumerBase(_VRFCoordinator, _LinkToken) public { //vrfCoordinator = _VRFCoordinator; //keyHash = _keyHash; fee = 0.1 * 10**18; // 0.1 LINK } /** * @notice This function must be called AFTER calling * the requestRandomWalk function.This will then * generate the random walk as an NFT and the sender * will have it added to their wallet and show up * in etherscan as an ERC721. * @return success -> true if successful */ function generateRandomWalkNFT() public returns(bool success) { bytes32 requestID = senderToRequest[msg.sender]; require(requestID != 0x0000000000000000000000000000000000000000000000000000000000000000); uint256 newID = randomWalks.length; requestToTokenID[requestID] = newID; int256[] memory xs = new int256[](requestToNodes[requestID]); int256[] memory ys = new int256[](requestToNodes[requestID]); xs[0] = 0; ys[0] = 0; // Constants: int256 _2pi = FixidityLib.multiply(FixidityLib.newFixed(2), NumericalMath.pi()); int256 _pi_on_2 = FixidityLib.multiply(FixidityLib.divide(1, 2), NumericalMath.pi()); int256 _pi_on_4 = FixidityLib.multiply(FixidityLib.divide(1, 4), NumericalMath.pi()); // Struct to store walker details: Walker memory walker; walker.x = 0; walker.y = 0; // Starting angle between 0 and 2π rad: walker.angle_orig = NumericalMath.convBtwUpLo(randomResult, 0, _2pi); walker.digits = FixidityLib.digits(); // Create all nodes of the walk: for (uint256 _i = 1; _i < requestToNodes[requestID]; _i++) { // Get new angle to walk towards if (_i == 1) { walker.currAngle = walker.angle_orig; } else { randomResult = NumericalMath.callKeccak256(abi.encodePacked(randomResult)); walker.currAngle = FixidityLib.add(walker.currAngle, FixidityLib.subtract(NumericalMath.getRandomNum(randomResult, 0, _pi_on_2), _pi_on_4)); } // Walk forwards in the new angle by 1 unit walker.x = FixidityLib.add(walker.x, NumericalMath.cos(walker.currAngle, walker.digits)); walker.y = FixidityLib.add(walker.y, NumericalMath.sin(walker.currAngle, walker.digits)); // Add new location as a node xs[_i] = walker.x; ys[_i] = walker.y; } // Add new Random Walk: randomWalks.push( RandomWalk( requestToMapName[requestID], newID, requestToNodes[requestID], xs, ys ) ); _safeMint(requestToSender[requestID], newID); senderToRequest[msg.sender] = 0x0000000000000000000000000000000000000000000000000000000000000000; return true; } /** The user enters an integer seed and the number * of walk nodes, then a random number is * generated by the VRF oracle and reserved * for the specific user that interacted with this * function. * @param userProvidedSeed: the integer seed * @param nodes: the number of nodes in the walk * @return requestID: the ID of the specific * request generated */ function requestRandomWalk(uint256 userProvidedSeed, uint256 nodes) public returns(bytes32) { bytes32 requestID = requestRandomness(keyHash, fee, userProvidedSeed); // get a random number from the oracle requestToMapName[requestID] = string(abi.encodePacked(uint2str(nodes), "-node walk")); requestToSender[requestID] = msg.sender; requestToNodes[requestID] = nodes; //senderToRequest[msg.sender] = requestID; return requestID; } /** * @notice This is the function that the VRF * oracle interacts with. * @param requestID: the ID of the request of * the user done in requestRandomWalk function * @param randomness: the VRF oracle's generated * random number */ function fulfillRandomness(bytes32 requestID, uint256 randomness) internal override { randomResult = FixidityLib.abs(int256(randomness)); senderToRequest[requestToSender[requestID]] = requestID; } /** * @notice Set the token URI for an NFT so that it can be viewed * in a market like opensea. * @param tokenID: the ID of the specific NFT * @param _tokenURI: the token URI */ function setTokenURI(uint256 tokenID, string memory _tokenURI) public { require( _isApprovedOrOwner(_msgSender(), tokenID), "ERC721: transfer caller is not owner nor approved" ); _setTokenURI(tokenID, _tokenURI); } /** * @notice Input the unique token ID for an NFT * and all the details of it will be returned. * @param tokenID: the ID of the desired NFT * @return details of the NFT */ function seeRandomWalk(uint256 tokenID) public view returns(RandomWalk memory) { return randomWalks[tokenID]; } /** * @notice Function that converts a uint256 to a string. * Works for ^0.8.0 and below. * @param _i: uint256 * @return _uintAsString * @dev created by Barnabas Ujvari (stackoverflow) * https://stackoverflow.com/questions/47129173/how-to-convert-uint-to-string-in-solidity */ function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } }
Add new location as a node
xs[_i] = walker.x;
5,478,209
[ 1, 986, 394, 2117, 487, 279, 756, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 9280, 63, 67, 77, 65, 273, 14810, 18, 92, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.16; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./IStakingContract.sol"; import "./IStakeChangeNotifier.sol"; contract StakingContract is IStakingContract, IMigratableStakingContract { using SafeMath for uint256; struct Stake { uint256 amount; uint256 cooldownAmount; uint256 cooldownEndTime; } struct WithdrawResult { uint256 withdrawnAmount; uint256 stakedAmount; uint256 stakedAmountDiff; } // The version of the smart contract. uint256 public constant VERSION = 1; // The maximum number of approved staking contracts as migration destinations. uint256 public constant MAX_APPROVED_STAKING_CONTRACTS = 10; // The mapping between stake owners and their data. mapping(address => Stake) internal stakes; // Total amount of staked tokens (not including unstaked tokes in cooldown or pending withdrawal). uint256 internal totalStakedTokens; // The period (in seconds) between a stake owner's request to stop staking and being able to withdraw them. uint256 public cooldownPeriodInSec; // The address responsible for managing migration to a new staking contract. address public migrationManager; // The address responsible for emergency operations and graceful return of staked tokens back to their owners. address public emergencyManager; // The list of staking contracts that are approved by this contract. It would be only allowed to migrate a stake to // one of these contracts. IMigratableStakingContract[] public approvedStakingContracts; // The address of the contract responsible for publishing stake change notifications. IStakeChangeNotifier public notifier; // The address of the $EDI Token Contract IERC20 internal token; // Represents whether the contract accepts new staking requests. Please note, that even when it's turned off, // it'd be still possible to unstake or withdraw tokens. // // Note: This can be turned off only once by the emergency manager of the contract. bool public acceptingNewStakes = true; // Represents whether this staking contract allows releasing all unstaked tokens unconditionally. When it's turned // on, stake owners could release their staked tokens, without explicitly requesting to unstake them, and their // previously unstaked tokens, regardless of the cooldown period. This also stops the contract from accepting new // stakes. // // Note: This can be turned off only once by the emergency manager of the contract. bool public releasingAllStakes = false; event MigrationManagerUpdated(address indexed migrationManager); event MigrationDestinationAdded( IMigratableStakingContract indexed stakingContract ); event MigrationDestinationRemoved( IMigratableStakingContract indexed stakingContract ); event EmergencyManagerUpdated(address indexed emergencyManager); event StakeChangeNotifierUpdated(IStakeChangeNotifier indexed notifier); event StoppedAcceptingNewStake(); event ReleasedAllStakes(); modifier onlyMigrationManager() { require( msg.sender == migrationManager, "StakingContract: caller is not the migration manager" ); _; } modifier onlyEmergencyManager() { require( msg.sender == emergencyManager, "StakingContract: caller is not the emergency manager" ); _; } modifier onlyWhenAcceptingNewStakes() { require( acceptingNewStakes && !releasingAllStakes, "StakingContract: not accepting new stakes" ); _; } modifier onlyWhenStakesReleased() { require( releasingAllStakes, "StakingContract: not releasing all stakes" ); _; } modifier onlyWhenStakesNotReleased() { require(!releasingAllStakes, "StakingContract: releasing all stakes"); _; } /// @dev Initializes the staking contract. /// @param _cooldownPeriodInSec uint256 The period (in seconds) between a stake owner's request to stop staking and being /// able to withdraw them. /// @param _migrationManager address The address responsible for managing migration to a new staking contract. /// @param _emergencyManager address The address responsible for emergency operations and graceful return of staked /// tokens back to their owners. /// @param _token IERC20 The address of the $EDI Token constructor( uint256 _cooldownPeriodInSec, address _migrationManager, address _emergencyManager, IERC20 _token ) public { require( _cooldownPeriodInSec > 0, "StakingContract::ctor - cooldown period must be greater than 0" ); require( _migrationManager != address(0), "StakingContract::ctor - migration manager must not be 0" ); require( _emergencyManager != address(0), "StakingContract::ctor - emergency manager must not be 0" ); require( address(_token) != address(0), "StakingContract::ctor - $EDI token must not be 0" ); cooldownPeriodInSec = _cooldownPeriodInSec; migrationManager = _migrationManager; emergencyManager = _emergencyManager; token = _token; } /// @dev Sets the address of the migration manager. /// @param _newMigrationManager address The address of the new migration manager. function setMigrationManager(address _newMigrationManager) external onlyMigrationManager { require( _newMigrationManager != address(0), "StakingContract::setMigrationManager - address must not be 0" ); require( migrationManager != _newMigrationManager, "StakingContract::setMigrationManager - address must be different than the current address" ); migrationManager = _newMigrationManager; emit MigrationManagerUpdated(_newMigrationManager); } /// @dev Sets the address of the emergency manager. /// @param _newEmergencyManager address The address of the new emergency manager. function setEmergencyManager(address _newEmergencyManager) external onlyEmergencyManager { require( _newEmergencyManager != address(0), "StakingContract::setEmergencyManager - address must not be 0" ); require( emergencyManager != _newEmergencyManager, "StakingContract::setEmergencyManager - address must be different than the current address" ); emergencyManager = _newEmergencyManager; emit EmergencyManagerUpdated(_newEmergencyManager); } /// @dev Sets the address of the stake change notifier contract. /// @param _newNotifier IStakeChangeNotifier The address of the new stake change notifier contract. /// /// Note: it's allowed to reset the notifier to a zero address. function setStakeChangeNotifier(IStakeChangeNotifier _newNotifier) external onlyMigrationManager { require( notifier != _newNotifier, "StakingContract::setStakeChangeNotifier - address must be different than the current address" ); notifier = _newNotifier; emit StakeChangeNotifierUpdated(notifier); } /// @dev Adds a new contract to the list of approved staking contracts migration destinations. /// @param _newStakingContract IMigratableStakingContract The new contract to add. function addMigrationDestination( IMigratableStakingContract _newStakingContract ) external onlyMigrationManager { require( address(_newStakingContract) != address(0), "StakingContract::addMigrationDestination - address must not be 0" ); uint256 length = approvedStakingContracts.length; require( length + 1 <= MAX_APPROVED_STAKING_CONTRACTS, "StakingContract::addMigrationDestination - can't add more staking contracts" ); // Check for duplicates. for (uint256 i = 0; i < length; ++i) { require( approvedStakingContracts[i] != _newStakingContract, "StakingContract::addMigrationDestination - can't add a duplicate staking contract" ); } approvedStakingContracts.push(_newStakingContract); emit MigrationDestinationAdded(_newStakingContract); } /// @dev Removes a contract from the list of approved staking contracts migration destinations. /// @param _stakingContract IMigratableStakingContract The contract to remove. function removeMigrationDestination( IMigratableStakingContract _stakingContract ) external onlyMigrationManager { require( address(_stakingContract) != address(0), "StakingContract::removeMigrationDestination - address must not be 0" ); // Check for existence. (uint256 i, bool exists) = findApprovedStakingContractIndex( _stakingContract ); require( exists, "StakingContract::removeMigrationDestination - staking contract doesn't exist" ); // Swap the requested element with the last element and then delete it using pop/ approvedStakingContracts[i] = approvedStakingContracts[approvedStakingContracts .length - 1]; approvedStakingContracts.pop(); emit MigrationDestinationRemoved(_stakingContract); } /// @dev Stakes $EDI tokens on behalf of msg.sender. This method assumes that the user has already approved at least /// the required amount using ERC20 approve. /// @param _amount uint256 The amount of tokens to stake. function stake(uint256 _amount) external onlyWhenAcceptingNewStakes { address stakeOwner = msg.sender; uint256 totalStakedAmount = stake(stakeOwner, _amount); emit Staked(stakeOwner, _amount, totalStakedAmount); // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChange(stakeOwner, _amount, true, totalStakedAmount); } /// @dev Unstakes $EDI tokens from msg.sender. If successful, this will start the cooldown period, after which /// msg.sender would be able to withdraw all of his tokens. /// @param _amount uint256 The amount of tokens to unstake. function unstake(uint256 _amount) external { require( _amount > 0, "StakingContract::unstake - amount must be greater than 0" ); address stakeOwner = msg.sender; Stake storage stakeData = stakes[stakeOwner]; uint256 stakedAmount = stakeData.amount; uint256 cooldownAmount = stakeData.cooldownAmount; uint256 cooldownEndTime = stakeData.cooldownEndTime; require( _amount <= stakedAmount, "StakingContract::unstake - can't unstake more than the current stake" ); // If any tokens in cooldown are ready for withdrawal - revert. Stake owner should withdraw their unstaked // tokens first. require( cooldownAmount == 0 || cooldownEndTime > now, "StakingContract::unstake - unable to unstake when there are tokens pending withdrawal" ); // Update the amount of tokens in cooldown. Please note that this will also restart the cooldown period of all // tokens in cooldown. stakeData.amount = stakedAmount.sub(_amount); stakeData.cooldownAmount = cooldownAmount.add(_amount); stakeData.cooldownEndTime = now.add(cooldownPeriodInSec); totalStakedTokens = totalStakedTokens.sub(_amount); uint256 totalStakedAmount = stakeData.amount; emit Unstaked(stakeOwner, _amount, totalStakedAmount); // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChange(stakeOwner, _amount, false, totalStakedAmount); } /// @dev Requests to withdraw all of staked $EDI tokens back to msg.sender. Stake owners can withdraw their $EDI /// tokens only after previously unstaking them and after the cooldown period has passed (unless the contract was /// requested to release all stakes). function withdraw() external { address stakeOwner = msg.sender; WithdrawResult memory res = withdraw(stakeOwner); emit Withdrew(stakeOwner, res.withdrawnAmount, res.stakedAmount); // Trigger staking state change notifications only if the staking amount was changed. if (res.stakedAmountDiff == 0) { return; } // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChange(stakeOwner, res.stakedAmountDiff, false, res.stakedAmount); } /// @dev Restakes unstaked $EDI tokens (in or after cooldown) for msg.sender. function restake() external onlyWhenAcceptingNewStakes { address stakeOwner = msg.sender; Stake storage stakeData = stakes[stakeOwner]; uint256 cooldownAmount = stakeData.cooldownAmount; require( cooldownAmount > 0, "StakingContract::restake - no unstaked tokens" ); stakeData.amount = stakeData.amount.add(cooldownAmount); stakeData.cooldownAmount = 0; stakeData.cooldownEndTime = 0; totalStakedTokens = totalStakedTokens.add(cooldownAmount); uint256 totalStakedAmount = stakeData.amount; emit Restaked(stakeOwner, cooldownAmount, totalStakedAmount); // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChange(stakeOwner, cooldownAmount, true, totalStakedAmount); } /// @dev Stakes $EDI tokens on behalf of msg.sender. This method assumes that the user has already approved at least /// the required amount using ERC20 approve. /// @param _stakeOwner address The specified stake owner. /// @param _amount uint256 The amount of tokens to stake. function acceptMigration(address _stakeOwner, uint256 _amount) external onlyWhenAcceptingNewStakes { uint256 totalStakedAmount = stake(_stakeOwner, _amount); emit AcceptedMigration(_stakeOwner, _amount, totalStakedAmount); // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChange(_stakeOwner, _amount, true, totalStakedAmount); } /// @dev Migrates the stake of msg.sender from this staking contract to a new approved staking contract. /// @param _newStakingContract IMigratableStakingContract The new staking contract which supports stake migration. /// @param _amount uint256 The amount of tokens to migrate. function migrateStakedTokens( IMigratableStakingContract _newStakingContract, uint256 _amount ) external onlyWhenStakesNotReleased { require( isApprovedStakingContract(_newStakingContract), "StakingContract::migrateStakedTokens - migration destination wasn't approved" ); require( _amount > 0, "StakingContract::migrateStakedTokens - amount must be greater than 0" ); address stakeOwner = msg.sender; Stake storage stakeData = stakes[stakeOwner]; uint256 stakedAmount = stakeData.amount; require( stakedAmount > 0, "StakingContract::migrateStakedTokens - no staked tokens" ); require( _amount <= stakedAmount, "StakingContract::migrateStakedTokens - amount exceeds staked token balance" ); stakeData.amount = stakedAmount.sub(_amount); totalStakedTokens = totalStakedTokens.sub(_amount); require( _newStakingContract.getToken() == token, "StakingContract::migrateStakedTokens - staked tokens must be the same" ); require( token.approve(address(_newStakingContract), _amount), "StakingContract::migrateStakedTokens - couldn't approve transfer" ); emit MigratedStake(stakeOwner, _amount, stakeData.amount); _newStakingContract.acceptMigration(stakeOwner, _amount); // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeMigration(stakeOwner, _amount); } /// @dev Distributes staking rewards to a list of addresses by directly adding rewards to their stakes. This method /// assumes that the user has already approved at least the required amount using ERC20 approve. Since this is a /// convenience method, we aren't concerned about reaching block gas limit by using large lists. We assume that /// callers will be able to batch/paginate their requests properly. /// @param _totalAmount uint256 The total amount of rewards to distributes. /// @param _stakeOwners address[] The addresses of the stake owners. /// @param _amounts uint256[] The amounts of the rewards. function distributeRewards( uint256 _totalAmount, address[] calldata _stakeOwners, uint256[] calldata _amounts ) external onlyWhenAcceptingNewStakes { require( _totalAmount > 0, "StakingContract::distributeRewards - total amount must be greater than 0" ); uint256 stakeOwnersLength = _stakeOwners.length; uint256 amountsLength = _amounts.length; require( stakeOwnersLength > 0 && amountsLength > 0, "StakingContract::distributeRewards - lists can't be empty" ); require( stakeOwnersLength == amountsLength, "StakingContract::distributeRewards - lists must be of the same size" ); // Transfer all the tokens to the smart contract and update the stake owners list accordingly. require( token.transferFrom(msg.sender, address(this), _totalAmount), "StakingContract::distributeRewards - insufficient allowance" ); bool[] memory signs = new bool[](amountsLength); uint256[] memory totalStakedAmounts = new uint256[](amountsLength); uint256 expectedTotalAmount = 0; for (uint256 i = 0; i < stakeOwnersLength; ++i) { address stakeOwner = _stakeOwners[i]; uint256 amount = _amounts[i]; require( stakeOwner != address(0), "StakingContract::distributeRewards - stake owner can't be 0" ); require( amount > 0, "StakingContract::distributeRewards - amount must be greater than 0" ); Stake storage stakeData = stakes[stakeOwner]; stakeData.amount = stakeData.amount.add(amount); expectedTotalAmount = expectedTotalAmount.add(amount); uint256 totalStakedAmount = stakeData.amount; signs[i] = true; totalStakedAmounts[i] = totalStakedAmount; emit Staked(stakeOwner, amount, totalStakedAmount); } require( _totalAmount == expectedTotalAmount, "StakingContract::distributeRewards - incorrect total amount" ); totalStakedTokens = totalStakedTokens.add(_totalAmount); // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChangeBatch(_stakeOwners, _amounts, signs, totalStakedAmounts); } /// @dev Returns the stake of the specified stake owner (excluding unstaked tokens). /// @param _stakeOwner address The address to check. /// @return uint256 The stake of the stake owner. function getStakeBalanceOf(address _stakeOwner) external view returns (uint256) { return stakes[_stakeOwner].amount; } /// @dev Returns the total amount staked tokens (excluding unstaked tokens). /// @return uint256 The total staked tokens of all stake owners. function getTotalStakedTokens() external view returns (uint256) { return totalStakedTokens; } /// @dev Returns the time that the cooldown period ends (or ended) and the amount of tokens to be released. /// @param _stakeOwner address The address to check. /// @return cooldownAmount uint256 The total tokens in cooldown. /// @return cooldownEndTime uint256 The time when the cooldown period ends (in seconds). function getUnstakeStatus(address _stakeOwner) external view returns (uint256 cooldownAmount, uint256 cooldownEndTime) { Stake memory stakeData = stakes[_stakeOwner]; cooldownAmount = stakeData.cooldownAmount; cooldownEndTime = stakeData.cooldownEndTime; } /// @dev Returns the address of the underlying staked token. /// @return IERC20 The address of the token. function getToken() external view returns (IERC20) { return token; } /// @dev Requests the contract to stop accepting new staking requests. function stopAcceptingNewStakes() external onlyEmergencyManager onlyWhenAcceptingNewStakes { acceptingNewStakes = false; emit StoppedAcceptingNewStake(); } /// @dev Requests the contract to release all stakes. function releaseAllStakes() external onlyEmergencyManager onlyWhenStakesNotReleased { releasingAllStakes = true; emit ReleasedAllStakes(); } /// @dev Requests withdraw of released tokens for a list of addresses. /// @param _stakeOwners address[] The addresses of the stake owners. function withdrawReleasedStakes(address[] calldata _stakeOwners) external onlyWhenStakesReleased { uint256 stakeOwnersLength = _stakeOwners.length; uint256[] memory stakedAmountDiffs = new uint256[](stakeOwnersLength); bool[] memory signs = new bool[](stakeOwnersLength); uint256[] memory totalStakedAmounts = new uint256[](stakeOwnersLength); for (uint256 i = 0; i < stakeOwnersLength; ++i) { address stakeOwner = _stakeOwners[i]; WithdrawResult memory res = withdraw(stakeOwner); stakedAmountDiffs[i] = res.stakedAmountDiff; signs[i] = false; totalStakedAmounts[i] = res.stakedAmount; emit Withdrew(stakeOwner, res.withdrawnAmount, res.stakedAmount); } // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChangeBatch( _stakeOwners, stakedAmountDiffs, signs, totalStakedAmounts ); } /// @dev Returns whether a specific staking contract was approved as a migration destination. /// @param _stakingContract IMigratableStakingContract The staking contract to look for. /// @return exists bool The approval status. function isApprovedStakingContract( IMigratableStakingContract _stakingContract ) public view returns (bool exists) { (, exists) = findApprovedStakingContractIndex(_stakingContract); } /// @dev Returns whether stake change notification is enabled. function shouldNotifyStakeChange() internal view returns (bool) { return address(notifier) != address(0); } /// @dev Notifies of stake change events. /// @param _stakeOwner address The address of the subject stake owner. /// @param _amount int256 The difference in the total staked amount. /// @param _sign bool The sign of the added (true) or subtracted (false) amount. /// @param _updatedStake uint256 The updated total staked amount. function stakeChange( address _stakeOwner, uint256 _amount, bool _sign, uint256 _updatedStake ) internal { if (!shouldNotifyStakeChange()) { return; } notifier.stakeChange(_stakeOwner, _amount, _sign, _updatedStake); } /// @dev Notifies of multiple stake change events. /// @param _stakeOwners address[] The addresses of subject stake owners. /// @param _amounts uint256[] The differences in total staked amounts. /// @param _signs bool[] The signs of the added (true) or subtracted (false) amounts. /// @param _updatedStakes uint256[] The updated total staked amounts. function stakeChangeBatch( address[] memory _stakeOwners, uint256[] memory _amounts, bool[] memory _signs, uint256[] memory _updatedStakes ) internal { if (!shouldNotifyStakeChange()) { return; } notifier.stakeChangeBatch( _stakeOwners, _amounts, _signs, _updatedStakes ); } /// @dev Notifies of stake migration event. /// @param _stakeOwner address The address of the subject stake owner. /// @param _amount uint256 The migrated amount. function stakeMigration(address _stakeOwner, uint256 _amount) internal { if (!shouldNotifyStakeChange()) { return; } notifier.stakeMigration(_stakeOwner, _amount); } /// @dev Stakes amount of $EDI tokens on behalf of the specified stake owner. /// @param _stakeOwner address The specified stake owner. /// @param _amount uint256 The amount of tokens to stake. /// @return totalStakedAmount uint256 The total stake of the stake owner. function stake(address _stakeOwner, uint256 _amount) private returns (uint256 totalStakedAmount) { require( _stakeOwner != address(0), "StakingContract::stake - stake owner can't be 0" ); require( _amount > 0, "StakingContract::stake - amount must be greater than 0" ); Stake storage stakeData = stakes[_stakeOwner]; stakeData.amount = stakeData.amount.add(_amount); totalStakedTokens = totalStakedTokens.add(_amount); totalStakedAmount = stakeData.amount; // Transfer the tokens to the smart contract and update the stake owners list accordingly. require( token.transferFrom(msg.sender, address(this), _amount), "StakingContract::stake - insufficient allowance" ); } /// @dev Requests to withdraw all of staked $EDI tokens back to the specified stake owner. Stake owners can withdraw /// their $EDI tokens only after previously unstaking them and after the cooldown period has passed (unless the /// contract was requested to release all stakes). /// @return res WithdrawResult The result of the withdraw operation. function withdraw(address _stakeOwner) private returns (WithdrawResult memory res) { require( _stakeOwner != address(0), "StakingContract::withdraw - stake owner can't be 0" ); Stake storage stakeData = stakes[_stakeOwner]; res.stakedAmount = stakeData.amount; res.withdrawnAmount = stakeData.cooldownAmount; res.stakedAmountDiff = 0; if (!releasingAllStakes) { require( res.withdrawnAmount > 0, "StakingContract::withdraw - no unstaked tokens" ); require( stakeData.cooldownEndTime <= now, "StakingContract::withdraw - tokens are still in cooldown" ); } else { // If the contract was requested to release all stakes - allow to withdraw all staked and unstaked tokens. res.withdrawnAmount = res.withdrawnAmount.add(res.stakedAmount); res.stakedAmountDiff = res.stakedAmount; require( res.withdrawnAmount > 0, "StakingContract::withdraw - no staked or unstaked tokens" ); stakeData.amount = 0; totalStakedTokens = totalStakedTokens.sub(res.stakedAmount); res.stakedAmount = 0; } stakeData.cooldownAmount = 0; stakeData.cooldownEndTime = 0; require( token.transfer(_stakeOwner, res.withdrawnAmount), "StakingContract::withdraw - couldn't transfer stake" ); } /// @dev Returns an index of an existing approved staking contract. /// @param _stakingContract IMigratableStakingContract The staking contract to look for. /// @return index uint The index of the located staking contract (in the case that it was found). /// @return exists bool The search result. function findApprovedStakingContractIndex( IMigratableStakingContract _stakingContract ) private view returns (uint256 index, bool exists) { uint256 length = approvedStakingContracts.length; for (index = 0; index < length; ++index) { if (approvedStakingContracts[index] == _stakingContract) { exists = true; return (index, exists); } } exists = false; } }
@dev Removes a contract from the list of approved staking contracts migration destinations. @param _stakingContract IMigratableStakingContract The contract to remove. Check for existence. Swap the requested element with the last element and then delete it using pop/
function removeMigrationDestination( IMigratableStakingContract _stakingContract ) external onlyMigrationManager { require( address(_stakingContract) != address(0), "StakingContract::removeMigrationDestination - address must not be 0" ); (uint256 i, bool exists) = findApprovedStakingContractIndex( _stakingContract ); require( exists, "StakingContract::removeMigrationDestination - staking contract doesn't exist" ); approvedStakingContracts[i] = approvedStakingContracts[approvedStakingContracts .length - 1]; approvedStakingContracts.pop(); emit MigrationDestinationRemoved(_stakingContract); }
1,815,877
[ 1, 6220, 279, 6835, 628, 326, 666, 434, 20412, 384, 6159, 20092, 6333, 20456, 18, 225, 389, 334, 6159, 8924, 6246, 2757, 8163, 510, 6159, 8924, 1021, 6835, 358, 1206, 18, 2073, 364, 15782, 18, 12738, 326, 3764, 930, 598, 326, 1142, 930, 471, 1508, 1430, 518, 1450, 1843, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 10224, 5683, 12, 203, 3639, 6246, 2757, 8163, 510, 6159, 8924, 389, 334, 6159, 8924, 203, 565, 262, 3903, 1338, 10224, 1318, 288, 203, 3639, 2583, 12, 203, 5411, 1758, 24899, 334, 6159, 8924, 13, 480, 1758, 12, 20, 3631, 203, 5411, 315, 510, 6159, 8924, 2866, 4479, 10224, 5683, 300, 1758, 1297, 486, 506, 374, 6, 203, 3639, 11272, 203, 203, 3639, 261, 11890, 5034, 277, 16, 1426, 1704, 13, 273, 1104, 31639, 510, 6159, 8924, 1016, 12, 203, 5411, 389, 334, 6159, 8924, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 1704, 16, 203, 5411, 315, 510, 6159, 8924, 2866, 4479, 10224, 5683, 300, 384, 6159, 6835, 3302, 1404, 1005, 6, 203, 3639, 11272, 203, 203, 3639, 20412, 510, 6159, 20723, 63, 77, 65, 273, 20412, 510, 6159, 20723, 63, 25990, 510, 6159, 20723, 203, 5411, 263, 2469, 300, 404, 15533, 203, 3639, 20412, 510, 6159, 20723, 18, 5120, 5621, 203, 203, 3639, 3626, 15309, 5683, 10026, 24899, 334, 6159, 8924, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import './AbstractERC1155Factory.sol'; import "./PaymentSplitter.sol"; /* * @title ERC1155 token for Pixelvault planets * * @author Niftydude */ contract Planets is AbstractERC1155Factory, PaymentSplitter { using Counters for Counters.Counter; Counters.Counter private counter; uint256 constant MOON_ID = 3; uint256 public claimWindowOpens = 4788607340; uint256 public claimWindowCloses = 4788607340; uint256 public purchaseWindowOpens = 4788607340; uint256 public daoBurnWindowOpens = 4788607340; uint256 public burnWindowOpens = 4788607340; ERC721Contract public comicContract; ERC721Contract public founderDAOContract; bool burnClosed; mapping(uint256 => bool) private isSaleClosed; mapping(uint256 => bool) private isClaimClosed; mapping(uint256 => Planet) public planets; event Claimed(uint indexed index, address indexed account, uint amount); event Purchased(uint indexed index, address indexed account, uint amount); struct Planet { uint256 mintPrice; uint256 maxSupply; uint256 maxPurchaseSupply; uint256 maxPurchaseTx; uint256 purchased; string ipfsMetadataHash; bytes32 merkleRoot; mapping(address => uint256) claimed; } constructor( string memory _name, string memory _symbol, address _comicContract, address _founderDAOContract, address[] memory payees, uint256[] memory shares_ ) ERC1155("ipfs://") PaymentSplitter(payees, shares_) { name_ = _name; symbol_ = _symbol; comicContract = ERC721Contract(_comicContract); founderDAOContract = ERC721Contract(_founderDAOContract); } /** * @notice adds a new planet * * @param _merkleRoot the merkle root to verify eligile claims * @param _mintPrice mint price in gwei * @param _maxSupply maximum total supply * @param _maxPurchaseSupply maximum supply that can be purchased * @param _ipfsMetadataHash the ipfs hash for planet metadata */ function addPlanet( bytes32 _merkleRoot, uint256 _mintPrice, uint256 _maxSupply, uint256 _maxPurchaseSupply, uint256 _maxPurchaseTx, string memory _ipfsMetadataHash ) public onlyOwner { Planet storage p = planets[counter.current()]; p.merkleRoot = _merkleRoot; p.mintPrice = _mintPrice; p.maxSupply = _maxSupply; p.maxPurchaseSupply = _maxPurchaseSupply; p.maxPurchaseTx = _maxPurchaseTx; p.ipfsMetadataHash = _ipfsMetadataHash; counter.increment(); } /** * @notice edit an existing planet * * @param _merkleRoot the merkle root to verify eligile claims * @param _mintPrice mint price in gwei * @param _maxPurchaseSupply maximum total supply * @param _ipfsMetadataHash the ipfs hash for planet metadata * @param _planetIndex the planet id to change */ function editPlanet( bytes32 _merkleRoot, uint256 _mintPrice, uint256 _maxPurchaseSupply, uint256 _maxPurchaseTx, string memory _ipfsMetadataHash, uint256 _planetIndex ) external onlyOwner { require(exists(_planetIndex), "EditPlanet: planet does not exist"); planets[_planetIndex].merkleRoot = _merkleRoot; planets[_planetIndex].mintPrice = _mintPrice; planets[_planetIndex].maxPurchaseSupply = _maxPurchaseSupply; planets[_planetIndex].maxPurchaseTx = _maxPurchaseTx; planets[_planetIndex].ipfsMetadataHash = _ipfsMetadataHash; } /** * @notice mint planet tokens * * @param planetID the planet id to mint * @param amount the amount of tokens to mint */ function mint(uint256 planetID, uint256 amount, address to) external onlyOwner { require(exists(planetID), "Mint: planet does not exist"); require(totalSupply(planetID) + amount <= planets[planetID].maxSupply, "Mint: Max supply reached"); _mint(to, planetID, amount, ""); } /** * @notice close planet sale * * @param planetIds the planet ids to close the sale for */ function closeSale(uint256[] calldata planetIds) external onlyOwner { uint256 count = planetIds.length; for (uint256 i; i < count; i++) { require(exists(planetIds[i]), "Close sale: planet does not exist"); isSaleClosed[planetIds[i]] = true; } } /** * @notice close claiming planets for MHs hold * * @param planetIds the planet ids to close claiming for */ function closeClaim(uint256[] calldata planetIds) external onlyOwner { uint256 count = planetIds.length; for (uint256 i; i < count; i++) { require(exists(planetIds[i]), "Close claim: planet does not exist"); isClaimClosed[planetIds[i]] = true; } } /** * @notice close burning comics for moon tokens */ function closeBurn() external onlyOwner { burnClosed = true; } /** * @notice edit windows for claiming and purchasing planets * * @param _claimWindowOpens UNIX timestamp for claiming window opening time * @param _claimWindowOpens UNIX timestamp for claiming window close time * @param _claimWindowOpens UNIX timestamp for purchasing window opening time */ function editWindows( uint256 _purchaseWindowOpens, uint256 _daoBurnWindowOpens, uint256 _burnWindowOpens, uint256 _claimWindowOpens, uint256 _claimWindowCloses ) external onlyOwner { claimWindowOpens = _claimWindowOpens; claimWindowCloses = _claimWindowCloses; purchaseWindowOpens = _purchaseWindowOpens; daoBurnWindowOpens = _daoBurnWindowOpens; burnWindowOpens = _burnWindowOpens; } /** * @notice purchase planet tokens * * @param planetID the planet id to purchase * @param amount the amount of tokens to purchase */ function purchase(uint256 planetID, uint256 amount) external payable whenNotPaused { require(!isSaleClosed[planetID], "Purchase: sale is closed"); require (block.timestamp >= purchaseWindowOpens, "Purchase: window closed"); require(amount <= planets[planetID].maxPurchaseTx, "Purchase: Max purchase per tx exceeded"); require(planets[planetID].purchased + amount <= planets[planetID].maxPurchaseSupply, "Purchase: Max purchase supply reached"); require(totalSupply(planetID) + amount <= planets[planetID].maxSupply, "Purchase: Max total supply reached"); require(msg.value == amount * planets[planetID].mintPrice, "Purchase: Incorrect payment"); planets[planetID].purchased += amount; _mint(msg.sender, planetID, amount, ""); emit Purchased(planetID, msg.sender, amount); } /** * @notice burn punks comics to receive moon tokens * * @param tokenIds the token ids of the comics to burn */ function burnComicForMoon(uint256[] calldata tokenIds) external whenNotPaused { require(!burnClosed, "Burn: is closed"); require((founderDAOContract.balanceOf(msg.sender) > 0 && block.timestamp >= daoBurnWindowOpens) || block.timestamp >= burnWindowOpens, "burnComicForMoon: window not open or DAO token required"); uint256 count = tokenIds.length; require(count <= 40, "Too many tokens"); require(totalSupply(MOON_ID) + count <= planets[MOON_ID].maxSupply, "Burn comic: Max moon supply reached"); for (uint256 i; i < count; i++) { comicContract.burn(tokenIds[i]); } _mint(msg.sender, MOON_ID, count, ""); } /** * @notice burn punks comics to receive moon tokens * * @param amount the amount of planet tokens to claim * @param planetId the id of the planet to claim for * @param index the index of the merkle proof * @param maxAmount the max amount óf planet tokens sender is eligible to claim * @param merkleProof the valid merkle proof of sender for given planet id */ function claim( uint256 amount, uint256 planetId, uint256 index, uint256 maxAmount, bytes32[] calldata merkleProof ) external whenNotPaused { require(!isClaimClosed[planetId], "Claim: is closed"); require (block.timestamp >= claimWindowOpens && block.timestamp <= claimWindowCloses, "Claim: time window closed"); require(planets[planetId].claimed[msg.sender] + amount <= maxAmount, "Claim: Not allowed to claim given amount"); bytes32 node = keccak256(abi.encodePacked(index, msg.sender, maxAmount)); require( MerkleProof.verify(merkleProof, planets[planetId].merkleRoot, node), "MerkleDistributor: Invalid proof." ); planets[planetId].claimed[msg.sender] = planets[planetId].claimed[msg.sender] + amount; _mint(msg.sender, planetId, amount, ""); emit Claimed(planetId, msg.sender, amount); } /** * @notice Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. * * @param account the payee to release funds for */ function release(address payable account) public override onlyOwner { super.release(account); } /** * @notice return total supply for all existing planets */ function totalSupplyAll() external view returns (uint[] memory) { uint[] memory result = new uint[](counter.current()); for(uint256 i; i < counter.current(); i++) { result[i] = totalSupply(i); } return result; } /** * @notice indicates weither any token exist with a given id, or not */ function exists(uint256 id) public view override returns (bool) { return planets[id].maxSupply > 0; } /** * @notice returns the metadata uri for a given id * * @param _id the planet id to return metadata for */ function uri(uint256 _id) public view override returns (string memory) { require(exists(_id), "URI: nonexistent token"); return string(abi.encodePacked(super.uri(_id), planets[_id].ipfsMetadataHash)); } } interface ERC721Contract is IERC721 { function burn(uint256 tokenId) external; } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT 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.4; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol'; import '@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Pausable.sol'; import '@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol'; abstract contract AbstractERC1155Factory is ERC1155Pausable, ERC1155Supply, ERC1155Burnable, Ownable { string public name_; string public symbol_; function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } function setURI(string memory baseURI) external onlyOwner { _setURI(baseURI); } function name() public view returns (string memory) { return name_; } function symbol() public view returns (string memory) { return symbol_; } function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual override(ERC1155, ERC1155Supply) { super._mint(account, id, amount, data); } function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155, ERC1155Supply) { super._mintBatch(to, ids, amounts, data); } function _burn( address account, uint256 id, uint256 amount ) internal virtual override(ERC1155, ERC1155Supply) { super._burn(account, id, amount); } function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual override(ERC1155, ERC1155Supply) { super._burnBatch(account, ids, amounts); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155Pausable, ERC1155) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + _totalReleased; uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account]; require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] = _released[account] + payment; _totalReleased = _totalReleased + payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn( address account, uint256 id, uint256 value ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1155.sol"; import "../../../security/Pausable.sol"; /** * @dev ERC1155 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. * * _Available since v3.1._ */ abstract contract ERC1155Pausable is ERC1155, Pausable { /** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!paused(), "ERC1155Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates weither any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_mint}. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual override { super._mint(account, id, amount, data); _totalSupply[id] += amount; } /** * @dev See {ERC1155-_mintBatch}. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._mintBatch(to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } /** * @dev See {ERC1155-_burn}. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual override { super._burn(account, id, amount); _totalSupply[id] -= amount; } /** * @dev See {ERC1155-_burnBatch}. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual override { super._burnBatch(account, ids, amounts); for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } // 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; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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 "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
* @notice purchase planet tokens @param planetID the planet id to purchase @param amount the amount of tokens to purchase/
function purchase(uint256 planetID, uint256 amount) external payable whenNotPaused { require(!isSaleClosed[planetID], "Purchase: sale is closed"); require (block.timestamp >= purchaseWindowOpens, "Purchase: window closed"); require(amount <= planets[planetID].maxPurchaseTx, "Purchase: Max purchase per tx exceeded"); require(planets[planetID].purchased + amount <= planets[planetID].maxPurchaseSupply, "Purchase: Max purchase supply reached"); require(totalSupply(planetID) + amount <= planets[planetID].maxSupply, "Purchase: Max total supply reached"); require(msg.value == amount * planets[planetID].mintPrice, "Purchase: Incorrect payment"); planets[planetID].purchased += amount; _mint(msg.sender, planetID, amount, ""); emit Purchased(planetID, msg.sender, amount); }
12,566,993
[ 1, 12688, 12104, 4995, 278, 2430, 225, 4995, 278, 734, 326, 4995, 278, 612, 358, 23701, 225, 3844, 326, 3844, 434, 2430, 358, 23701, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 23701, 12, 11890, 5034, 4995, 278, 734, 16, 2254, 5034, 3844, 13, 3903, 8843, 429, 1347, 1248, 28590, 288, 203, 3639, 2583, 12, 5, 291, 30746, 7395, 63, 7088, 278, 734, 6487, 315, 23164, 30, 272, 5349, 353, 4375, 8863, 203, 3639, 2583, 261, 2629, 18, 5508, 1545, 23701, 3829, 17778, 16, 315, 23164, 30, 2742, 4375, 8863, 203, 3639, 2583, 12, 8949, 1648, 4995, 2413, 63, 7088, 278, 734, 8009, 1896, 23164, 4188, 16, 315, 23164, 30, 4238, 23701, 1534, 2229, 12428, 8863, 1171, 203, 3639, 2583, 12, 7088, 2413, 63, 7088, 278, 734, 8009, 12688, 343, 8905, 397, 3844, 1648, 4995, 2413, 63, 7088, 278, 734, 8009, 1896, 23164, 3088, 1283, 16, 315, 23164, 30, 4238, 23701, 14467, 8675, 8863, 203, 3639, 2583, 12, 4963, 3088, 1283, 12, 7088, 278, 734, 13, 397, 3844, 1648, 4995, 2413, 63, 7088, 278, 734, 8009, 1896, 3088, 1283, 16, 315, 23164, 30, 4238, 2078, 14467, 8675, 8863, 203, 3639, 2583, 12, 3576, 18, 1132, 422, 3844, 380, 4995, 2413, 63, 7088, 278, 734, 8009, 81, 474, 5147, 16, 315, 23164, 30, 657, 6746, 5184, 8863, 7010, 203, 3639, 4995, 2413, 63, 7088, 278, 734, 8009, 12688, 343, 8905, 1011, 3844, 31, 203, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 4995, 278, 734, 16, 3844, 16, 1408, 1769, 203, 203, 3639, 3626, 14466, 343, 8905, 12, 7088, 278, 734, 16, 1234, 18, 15330, 16, 3844, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0xa4a8e396d325Ca4213b80c003bdf7a8C60EF97dD/sources/IlikeTests.sol
Total Tax is 5% of each HFLY transaction 2.5% go to HFLY/ROT LP rewards 2.5% go to HFLY/ROT liq locke Half of 2.5% are sold for ROT Then both are injected into the HFLY/ROT pair leftorver Maggots are sent back to ROT/MAGGOT pool--------------------------------Storage Start-----------------------------Indicator for migration window initiationBlock at which the migration was initatedBlock at which the migration will End1 dayCounter for Total rewards for HFLY/ROT LP poolCounter for Total amount to be locked in liquidity for HFLY/ROT poolPair Address of HFLY/ROTBurn AddressMAGGOT Token Address 40 = 2.5% 2.5% of HFLY tx go to HFLY/ROT LP rewards40 = 2.5%UniswapV2Router02 Addressaddress private uniswapV2Router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;UNI-V2 LP Token HFLY/ROTROT Token AddressROT/MAGGOT Pair AddressFactory Address UniswapThis addressModifier that makes function callable only on these requirements are metUsed in Migration function
contract IlikeTests is ERC20("TestT5", "TEST5"), Ownable { using SafeMath for uint256; bool private isMigrationInitiated = false; uint256 private INITIATED_IN_BLOCK; uint256 private MIGRATION_END_BLOCK; uint256 private TOTAL_REWARDS_LP_HFLY_ROT; uint256 private TOTAL_TO_LOCK_IN_LIQ; address private HFLYROTPairAddress; address private constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; address private constant MAGGOT_ADDRESS = 0xBB93D51b9A8Ae40d8Cc0A4Fa3d0e454d1Fd8e2dE; uint256 private constant LIQUIDITY_LOCK_DIVISOR = 40; uint8 private constant LP_REWARD_DIVISOR = 40; IUniswapV2Router02 public constant uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address private UNISWAP_V2_LP_TOKEN_HFLY_ROT; address private constant ROTAddress = 0xa750D70d20fdb157fEf6f59C507Db21eafF7EDfB; address private constant MAGGOT_ROT_PAIR_ADDRESS = 0x3FE677eB9957cfDDCD7B4008Dd156AA3F36F262d; address private constant UNIV2Factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; modifier isMigrationOpen { require(isMigrationInitiated, "Migration is not initiated"); require(block.number <= MIGRATION_END_BLOCK, "Current block is after migration end block"); require(block.number >= INITIATED_IN_BLOCK, "Current block is before migration start block"); _; } ROTStorage private ROT_STORAGE_CONTRACT; address private ZAPPER_ADDRESS; address private ROT_STORAGE_ADDRESS; address constant private WETHRinkeby = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; constructor() public { _mint(msg.sender, 100000000000000000000000); } function calcTaxAndRewardsAndLockOnTx(uint256 amountIn) internal returns (uint256, uint256) { uint256 LPRewards = amountIn.div(LP_REWARD_DIVISOR); uint256 ToLock = amountIn.div(LIQUIDITY_LOCK_DIVISOR); uint256 Tax = LPRewards.add(ToLock); uint256 amountOut = amountIn.sub(Tax); require(amountOut < amountIn, "Final amt calc Failed"); require(Tax > 0, "Tax calc Failed"); require(amountOut.add(Tax) == amountIn, "Tax + AmountOut should equal AmountIn"); TOTAL_REWARDS_LP_HFLY_ROT = TOTAL_REWARDS_LP_HFLY_ROT.add(LPRewards); TOTAL_TO_LOCK_IN_LIQ = TOTAL_TO_LOCK_IN_LIQ.add(ToLock); return (amountOut, Tax); } function transfer(address recipient, uint256 amount) public override returns (bool) { require(amount!=0, "Amount should be bigger than 0"); (uint256 finalAmount, uint256 amountTaxed) = calcTaxAndRewardsAndLockOnTx(amount); require(finalAmount < amount, "Did not deduct tax"); require(amountTaxed > 0, "Did not factor tax"); super.transfer(address(this), amountTaxed); return super.transfer(recipient, finalAmount); } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { require(amount!=0, "Amount should be bigger than 0"); (uint256 finalAmount, uint256 amountTaxed) = calcTaxAndRewardsAndLockOnTx(amount); require(finalAmount < amount, "Did not deduct tax"); require(amountTaxed > 0, "Did not factor tax"); super.transferFrom(sender, address(this), amountTaxed); return super.transferFrom(sender, recipient, finalAmount); } function openMigration() public onlyOwner { require(isMigrationInitiated == false, "Migration Already initiated"); isMigrationInitiated = true; INITIATED_IN_BLOCK = block.number; MIGRATION_END_BLOCK = INITIATED_IN_BLOCK.add(22176); } function migrateMaggotsForHorsefly(uint256 amountMaggot) external isMigrationOpen { require(amountMaggot!=0, "Maggot Amount cant be 0"); require(amountMaggot <= ERC20(MAGGOT_ADDRESS).balanceOf(msg.sender), "Can't migrate more maggots than what u have" ); ERC20(MAGGOT_ADDRESS).transferFrom(msg.sender, BURN_ADDRESS, amountMaggot); (uint256 finalAmount, uint256 amountTaxed) = calcTaxAndRewardsAndLockOnTx(amountMaggot); if(address(msg.sender) == address(ZAPPER_ADDRESS)){ _mint(msg.sender, amountMaggot); _mint(msg.sender, finalAmount); _mint(address(this), amountTaxed); } } function migrateMaggotsForHorsefly(uint256 amountMaggot) external isMigrationOpen { require(amountMaggot!=0, "Maggot Amount cant be 0"); require(amountMaggot <= ERC20(MAGGOT_ADDRESS).balanceOf(msg.sender), "Can't migrate more maggots than what u have" ); ERC20(MAGGOT_ADDRESS).transferFrom(msg.sender, BURN_ADDRESS, amountMaggot); (uint256 finalAmount, uint256 amountTaxed) = calcTaxAndRewardsAndLockOnTx(amountMaggot); if(address(msg.sender) == address(ZAPPER_ADDRESS)){ _mint(msg.sender, amountMaggot); _mint(msg.sender, finalAmount); _mint(address(this), amountTaxed); } } } else { function distributeLPRewardsForHFLYROT() public { require(TOTAL_REWARDS_LP_HFLY_ROT!=0,"Amount cant be 0"); require(HFLYROTPairAddress!=address(0),"Address cant be 0"); require(balanceOf(address(this)) >= TOTAL_REWARDS_LP_HFLY_ROT); _burn(address(this), TOTAL_REWARDS_LP_HFLY_ROT); _mint(HFLYROTPairAddress, TOTAL_REWARDS_LP_HFLY_ROT); syncUniswapPairHFLYROT(); TOTAL_REWARDS_LP_HFLY_ROT = 0; } function distributeLPRewardsForMaggotRot() public { getMaggotAmountFromROTSTorage(); uint256 MAGGOTBalance = ERC20(MAGGOT_ADDRESS).balanceOf(address(this)); require(MAGGOTBalance!=0,"Maggot balance should be more than 0"); ERC20(MAGGOT_ADDRESS).approve(address(this), MAGGOTBalance); ERC20(MAGGOT_ADDRESS).transferFrom(address(this), MAGGOT_ROT_PAIR_ADDRESS, MAGGOTBalance); syncUniswapPairMaggotRot(); } function swapAndLock() public { require(TOTAL_TO_LOCK_IN_LIQ <= balanceOf(address(this)), "Lock amount higher than lockable balance"); require(TOTAL_TO_LOCK_IN_LIQ != 0, "Lock amount cannot be 0"); uint256 amountToSwapForROT = TOTAL_TO_LOCK_IN_LIQ.div(2); uint256 amountToAddLiquidityHFLY = TOTAL_TO_LOCK_IN_LIQ.sub(amountToSwapForROT); uint256 rotBurnDivisor = 20; uint256 burnAmountInROT = amountToAddLiquidityHFLY.div(rotBurnDivisor); amountToAddLiquidityHFLY = amountToAddLiquidityHFLY.sub(burnAmountInROT); uint256 ROTBalanceBeforeSwap = ERC20(ROTAddress).balanceOf(address(this)); swapHFLYintoROT(amountToSwapForROT); getROTAmountFromROTStorage(); uint256 ROTReceived = ERC20(ROTAddress).balanceOf(address(this)).sub(ROTBalanceBeforeSwap); require(ROTReceived!=0, "ROT Recieved is 0"); addLiquidity(amountToAddLiquidityHFLY, ROTReceived); syncUniswapPairHFLYROT(); TOTAL_TO_LOCK_IN_LIQ = 0; } function distriubteEverything() public { distributeLPRewardsForHFLYROT(); swapAndLock(); distributeLPRewardsForMaggotRot(); burnLPTokens(); TOTAL_REWARDS_LP_HFLY_ROT = balanceOf(address(this)).div(2); TOTAL_TO_LOCK_IN_LIQ = balanceOf(address(this)).sub(TOTAL_REWARDS_LP_HFLY_ROT); } function swapHFLYintoROT(uint256 tokenAmount) public { require(tokenAmount!=0, "Amount cant be 0"); require(ROT_STORAGE_ADDRESS!=address(0), "Liq lock storage contract should not be 0"); address[] memory path2 = new address[](2); path2[0] = address(this); path2[1] = ROTAddress; _approve(address(this), address(uniswapV2Router), tokenAmount); _approve(ROTAddress, address(uniswapV2Router), tokenAmount); uniswapV2Router .swapExactTokensForTokensSupportingFeeOnTransferTokens ( tokenAmount, uint256(0), path2, address(ROT_STORAGE_ADDRESS), block.timestamp ); syncUniswapPairHFLYROT(); } function addLiquidity(uint256 HFLYtokenAmount, uint256 ROTAmount) public { require(HFLYtokenAmount!=0,"Amount cant be 0"); require(ROTAmount !=0,"Amount cant be 0"); _approve(address(this), address(uniswapV2Router), HFLYtokenAmount); _approve(ROTAddress, address(uniswapV2Router), ROTAmount); uniswapV2Router .addLiquidity ( address(this), ROTAddress, HFLYtokenAmount, ROTAmount, 0, 0, address(this), block.timestamp ); syncUniswapPairHFLYROT(); } function burnLPTokens() private { require(UNISWAP_V2_LP_TOKEN_HFLY_ROT!=address(0),"Address cant be 0"); uint256 balanceOfLpTokens = ERC20(UNISWAP_V2_LP_TOKEN_HFLY_ROT).balanceOf(address(this)); require(balanceOfLpTokens!=0, "BalanceOf LP tokens cant be 0"); ERC20(UNISWAP_V2_LP_TOKEN_HFLY_ROT).transferFrom(address(this),BURN_ADDRESS, balanceOfLpTokens); } function syncUniswapPairHFLYROT() public { require(HFLYROTPairAddress != address(0),"Address cant be 0"); IUniswapV2Pair(HFLYROTPairAddress).sync(); } function syncUniswapPairMaggotRot() public { require(MAGGOT_ROT_PAIR_ADDRESS!=address(0),"Address cant be 0"); IUniswapV2Pair(MAGGOT_ROT_PAIR_ADDRESS).sync(); } function createPairHFLYROT() public onlyOwner returns (address pairaddy) { require(ROTAddress!=address(0),"Address cant be 0"); HFLYROTPairAddress = IUniswapV2Factory(UNIV2Factory).createPair(address(this), ROTAddress); UNISWAP_V2_LP_TOKEN_HFLY_ROT = HFLYROTPairAddress; return HFLYROTPairAddress; } function getROTAmountFromROTStorage() public { uint256 balanceBefore=ERC20(MAGGOT_ADDRESS).balanceOf(address(this)); ROT_STORAGE_ADDRESS.call(abi.encodeWithSignature("GiveAllRotToHFLYContract()")); uint256 balanceAfter=ERC20(MAGGOT_ADDRESS).balanceOf(address(this)); require(balanceAfter>balanceBefore,"ROT Balance didnt increase"); } function getMaggotAmountFromROTSTorage() public { uint256 balanceBefore=ERC20(MAGGOT_ADDRESS).balanceOf(address(this)); ROT_STORAGE_ADDRESS.call(abi.encodeWithSignature("GiveAllMaggotToHFLYContract()")); uint256 balanceAfter=ERC20(MAGGOT_ADDRESS).balanceOf(address(this)); require(balanceAfter>balanceBefore,"MAAGGOT Balance didnt increase"); } function setROTStorageAddress(address rotstad) public onlyOwner { require(rotstad!=address(0)); ROT_STORAGE_ADDRESS = rotstad; } function setZapperAddress(address zappAdd) public onlyOwner { require(zappAdd!=address(0)); ZAPPER_ADDRESS = zappAdd; } function makeBurnAddressOwner() public onlyOwner { transferOwnership(burnAdd); } function createPairHFLYROTwithLiqADD(uint256 hfly, uint256 rot) public onlyOwner returns (address pairaddy) { require(ROTAddress!=address(0),"Address cant be 0"); require(hfly!=0 && rot != 0); HFLYROTPairAddress = IUniswapV2Factory(UNIV2Factory).createPair(address(this), ROTAddress); addLiquidity(hfly, rot); uniswapLPToken = HFLYROTPairAddress; return HFLYROTPairAddress; } }
8,695,758
[ 1, 5269, 18240, 353, 1381, 9, 434, 1517, 670, 42, 7076, 2492, 576, 18, 25, 9, 1960, 358, 670, 42, 7076, 19, 1457, 56, 511, 52, 283, 6397, 576, 18, 25, 9, 1960, 358, 670, 42, 7076, 19, 1457, 56, 4501, 85, 2176, 73, 670, 6186, 434, 576, 18, 25, 9, 854, 272, 1673, 364, 534, 1974, 9697, 3937, 854, 15776, 1368, 326, 670, 42, 7076, 19, 1457, 56, 3082, 2002, 280, 502, 12342, 75, 6968, 854, 3271, 1473, 358, 534, 1974, 19, 49, 1781, 43, 1974, 2845, 2443, 3245, 3603, 1271, 16982, 13140, 364, 6333, 2742, 1208, 7072, 1768, 622, 1492, 326, 6333, 1703, 1208, 690, 1768, 622, 1492, 326, 6333, 903, 4403, 21, 2548, 4789, 364, 10710, 283, 6397, 364, 670, 42, 7076, 19, 1457, 56, 511, 52, 2845, 4789, 364, 10710, 3844, 358, 506, 8586, 316, 4501, 372, 24237, 364, 670, 42, 7076, 19, 1457, 56, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 467, 5625, 14650, 353, 4232, 39, 3462, 2932, 4709, 56, 25, 3113, 315, 16961, 25, 6, 3631, 14223, 6914, 288, 7010, 203, 202, 9940, 14060, 10477, 364, 2254, 5034, 31, 203, 377, 203, 203, 565, 1426, 3238, 353, 10224, 2570, 10206, 273, 629, 31, 203, 565, 2254, 5034, 3238, 12584, 45, 6344, 67, 706, 67, 11403, 31, 203, 565, 2254, 5034, 3238, 490, 3047, 24284, 67, 4415, 67, 11403, 31, 203, 565, 2254, 5034, 3238, 399, 19851, 67, 862, 16777, 3948, 67, 14461, 67, 44, 42, 7076, 67, 1457, 56, 31, 203, 565, 2254, 5034, 3238, 399, 19851, 67, 4296, 67, 6589, 67, 706, 67, 2053, 53, 31, 203, 565, 1758, 3238, 670, 42, 7076, 1457, 56, 4154, 1887, 31, 203, 565, 1758, 3238, 5381, 605, 8521, 67, 15140, 273, 374, 92, 12648, 12648, 12648, 12648, 2787, 72, 41, 69, 40, 31, 203, 565, 1758, 3238, 5381, 490, 1781, 43, 1974, 67, 15140, 273, 374, 92, 9676, 11180, 40, 10593, 70, 29, 37, 28, 37, 73, 7132, 72, 28, 39, 71, 20, 37, 24, 29634, 23, 72, 20, 73, 24, 6564, 72, 21, 27263, 28, 73, 22, 72, 41, 31, 203, 565, 2254, 5034, 3238, 5381, 8961, 53, 3060, 4107, 67, 6589, 67, 2565, 26780, 916, 273, 8063, 31, 203, 565, 2254, 28, 3238, 5381, 511, 52, 67, 862, 21343, 67, 2565, 26780, 916, 273, 8063, 31, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 5381, 640, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-02-24 */ /** //SPDX-License-Identifier: Unlicensed */ pragma solidity ^0.8.6; 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); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; return msg.data; } } library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } 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); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { _owner = 0x606b8c57D59Df05BE011b182056D17Cd69B35e55; emit OwnershipTransferred(address(0), _owner); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface 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 Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract SaveUkraineCoin is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) public _isExcludedFromFee; mapping (address => bool) private _isExcluded; // Blacklist: If 'noBlackList' is true wallets on this list can not buy - used for known bots mapping (address => bool) public _isBlacklisted; // Set contract so that blacklisted wallets cannot buy (default is false) bool public noBlackList; address[] private _excluded; // Excluded from rewards address payable private Wallet_Marketing = payable(0x2F67253a6377d147235d30348267D955F2196b2a); address payable private Wallet_Token_Burn = payable(0x2F67253a6377d147235d30348267D955F2196b2a); address payable private Wallet_Dev = payable(0x2F67253a6377d147235d30348267D955F2196b2a); address payable private Wallet_Burn = payable(0x000000000000000000000000000000000000dEaD); address payable private Wallet_zero = payable(0x0000000000000000000000000000000000000000); uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 15000000000 * 10**18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "Save Ukraine Coin"; string private _symbol = "SAVUK"; uint8 private _decimals = 18; // Counter for liquify trigger uint8 private txCount = 0; uint8 private swapTrigger = 4; // This is the max fee that the contract will accept, it is hard-coded to protect buyers uint256 public maxPossibleFee = 17; uint256 public minPossibleReflect = 0; // Setting the initial fees uint256 public _FeeReflection = 2; uint256 public _FeeBurnTokens = 0; uint256 public _FeeLiquidity = 7; uint256 public _FeeMarketing = 4; uint256 public _FeeDev = 0; // 'Previous fees' are used to keep track of fee settings when removing and restoring fees uint256 private _previousFeeReflection = _FeeReflection; uint256 private _previousFeeLiquidity = _FeeLiquidity; uint256 private _previousFeeMarketing = _FeeMarketing; uint256 private _previousFeeDev = _FeeDev; uint256 private _previousFeeBurnTokens = _FeeBurnTokens; // The following settings are used to calculate fee splits when distributing bnb to liquidity and external wallets uint256 private _promoFee = _FeeMarketing+_FeeDev; uint256 public _FeesTotal = _FeeMarketing+_FeeDev+_FeeLiquidity+_FeeReflection+_FeeBurnTokens; // Fee for the auto LP and the all bnb wallets - used to process fees uint256 private _liquidityAndPromoFee = _FeeMarketing+_FeeDev+_FeeLiquidity; // Wallet limits // Max wallet holding (10% at launch) uint256 public _maxWalletToken = _tTotal.mul(10).div(100); uint256 private _previousMaxWalletToken = _maxWalletToken; // Maximum transaction amount (15% at launch) uint256 public _maxTxAmount = _tTotal.mul(15).div(100); uint256 private _previousMaxTxAmount = _maxTxAmount; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool public inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[owner()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[Wallet_Token_Burn] = true; _isExcludedFromFee[Wallet_Marketing] = true; _isExcludedFromFee[Wallet_Dev] = true; emit Transfer(address(0), owner(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } /* Presale Functions Presales have different settings, turn them on and off with the click on a button! */ // Get ready for presale! function Presale_START() external onlyOwner { set_Swap_And_Liquify_Enabled(false); removeAllFee(); removeWalletLimits(); } // Presale done! Set all fees function Presale_END() external onlyOwner { set_Swap_And_Liquify_Enabled(true); restoreAllFee(); restoreWalletLimits(); } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already included"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } // Set a wallet address so that it does not have to pay transaction fees function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } // Set a wallet address so that it has to pay transaction fees function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } /* FEES SAFETY FEATURES TO PROTECT BUYERS! The fee adjustments are limited to protect buyers 1. The total fees can not go above 15% */ function _set_Fees(uint256 Liquidity, uint256 Marketing, uint256 Reflection, uint256 TokenBurn, uint256 Developer) external onlyOwner() { // Check fee limits require((Reflection+TokenBurn+Liquidity+Marketing+Developer) <= maxPossibleFee, "Total fees too high!"); require(Reflection >= minPossibleReflect, "Reflection fee too low"); require(Developer >= 1, "Developer fee too low"); // Set the fees _FeeLiquidity = Liquidity; _FeeMarketing = Marketing; _FeeReflection = Reflection; _FeeBurnTokens = TokenBurn; _FeeDev = Developer; // For calculations and processing _promoFee = _FeeMarketing+_FeeDev; _liquidityAndPromoFee = _FeeLiquidity+_promoFee; _FeesTotal = _FeeMarketing+_FeeDev+_FeeLiquidity+_FeeBurnTokens+_FeeReflection; } /* Updating Wallets */ //Update the marketing wallet function Wallet_Update_Marketing(address payable wallet) public onlyOwner() { Wallet_Marketing = wallet; _isExcludedFromFee[Wallet_Marketing] = true; } //Update the dev wallet function Wallet_Update_Dev(address payable wallet) public onlyOwner() { Wallet_Dev = wallet; _isExcludedFromFee[Wallet_Dev] = true; } //Update the token burn and giveaway wallet function Wallet_Update_Token_Burn(address payable wallet) public onlyOwner() { Wallet_Token_Burn = wallet; _isExcludedFromFee[Wallet_Token_Burn] = true; } /* SwapAndLiquify Switches */ // Toggle on and off to activate auto liquidity and the promo wallet function set_Swap_And_Liquify_Enabled(bool true_or_false) public onlyOwner { swapAndLiquifyEnabled = true_or_false; emit SwapAndLiquifyEnabledUpdated(true_or_false); } // This will set the number of transactions required before the 'swapAndLiquify' function triggers function set_Number_Of_Transactions_Before_Liquify_Trigger(uint8 number_of_transactions) public onlyOwner { swapTrigger = number_of_transactions; } // This function is required so that the contract can receive BNB from pancakeswap receive() external payable {} /* Blacklist - This is used to block a person from buying - known bot users are added to this list prior to launch. We also check for people using snipe bots on the contract before we add liquidity and block these wallets. We like all of our buys to be natural and fair. */ // Blacklist - block wallets (ADD - COMMA SEPARATE MULTIPLE WALLETS) function blacklist_Add_Wallets(address[] calldata addresses) external onlyOwner { uint256 startGas; uint256 gasUsed; for (uint256 i; i < addresses.length; ++i) { if(gasUsed < gasleft()) { startGas = gasleft(); if(!_isBlacklisted[addresses[i]]){ _isBlacklisted[addresses[i]] = true;} gasUsed = startGas - gasleft(); } } } // Blacklist - block wallets (REMOVE - COMMA SEPARATE MULTIPLE WALLETS) function blacklist_Remove_Wallets(address[] calldata addresses) external onlyOwner { uint256 startGas; uint256 gasUsed; for (uint256 i; i < addresses.length; ++i) { if(gasUsed < gasleft()) { startGas = gasleft(); if(_isBlacklisted[addresses[i]]){ _isBlacklisted[addresses[i]] = false;} gasUsed = startGas - gasleft(); } } } /* You can turn the blacklist restrictions on and off. During launch, it's a good idea to block known bot users from buying. But these are real people, so when the contract is safe (and the price has increased) you can allow these wallets to buy/sell by setting noBlackList to false */ //Blacklist Switch - Turn on/off blacklisted wallet restrictions function blacklist_Switch(bool true_or_false) public onlyOwner { noBlackList = true_or_false; } /* When sending tokens to another wallet (not buying or selling) if noFeeToTransfer is true there will be no fee */ bool public noFeeToTransfer = true; // Option to set fee or no fee for transfer (just in case the no fee transfer option is exploited in future!) // True = there will be no fees when moving tokens around or giving them to friends! (There will only be a fee to buy or sell) // False = there will be a fee when buying/selling/tranfering tokens // Default is true function set_Transfers_Without_Fees(bool true_or_false) external onlyOwner { noFeeToTransfer = true_or_false; } /* SafeLaunch Features Wallet Limits Wallets are limited in two ways. The amount of tokens that can be purchased in one transaction and the total amount of tokens a wallet can buy. Limiting a wallet prevents one wallet from holding too many tokens, which can scare away potential buyers that worry that a whale might dump! */ // Set the Max transaction amount (percent of total supply) function set_Max_Transaction_Percent(uint256 max_Transaction_Percent) external onlyOwner() { _maxTxAmount = _tTotal*max_Transaction_Percent/100; } // Set the maximum permitted wallet holding (percent of total supply) function set_Max_Wallet_Holding_Percent(uint256 max_Wallet_Holding_Percent) external onlyOwner() { _maxWalletToken = _tTotal*max_Wallet_Holding_Percent/100; } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, tDev, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity, tDev); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) { uint256 tFee = calculateFeeReflection(tAmount); uint256 tLiquidity = calculateLiquidityAndPromoFee(tAmount); uint256 tDev = calculateFeeDevTokens(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity).sub(tDev); return (tTransferAmount, tFee, tLiquidity, tDev); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rDev = tDev.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity).sub(rDev); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _takeDev(uint256 tDev) private { uint256 currentRate = _getRate(); uint256 rDev = tDev.mul(currentRate); _rOwned[Wallet_Token_Burn] = _rOwned[Wallet_Token_Burn].add(rDev); if(_isExcluded[Wallet_Token_Burn]) _tOwned[Wallet_Token_Burn] = _tOwned[Wallet_Token_Burn].add(tDev); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function calculateFeeReflection(uint256 _amount) private view returns (uint256) { return _amount.mul(_FeeReflection).div( 10**2 ); } function calculateFeeDevTokens(uint256 _amount) private view returns (uint256) { return _amount.mul(_FeeBurnTokens).div( 10**2 ); } function calculateLiquidityAndPromoFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityAndPromoFee).div( 10**2 ); } // Remove all fees function removeAllFee() private { if(_FeeReflection == 0 && _FeeLiquidity == 0 && _FeeMarketing == 0 && _FeeDev == 0 && _FeeBurnTokens == 0) return; _previousFeeReflection = _FeeReflection; _previousFeeLiquidity = _FeeLiquidity; _previousFeeMarketing = _FeeMarketing; _previousFeeDev = _FeeDev; _previousFeeBurnTokens = _FeeBurnTokens; _FeeReflection = 0; _liquidityAndPromoFee = 0; _FeeLiquidity = 0; _FeeMarketing = 0; _FeeBurnTokens = 0; _FeeDev = 0; _promoFee = 0; _FeesTotal = 0; } // Restore all fees function restoreAllFee() private { _FeeReflection = _previousFeeReflection; _FeeLiquidity = _previousFeeLiquidity; _FeeMarketing = _previousFeeMarketing; _FeeDev = _previousFeeDev; _FeeBurnTokens = _previousFeeBurnTokens; _FeesTotal = _FeeMarketing+_FeeDev+_FeeLiquidity+_FeeReflection+_FeeBurnTokens; _promoFee = _FeeMarketing+_FeeDev; _liquidityAndPromoFee = _FeeMarketing+_FeeDev+_FeeLiquidity; } // Remove wallet limits (used during pre-sale) function removeWalletLimits() private { if(_maxWalletToken == _tTotal && _maxTxAmount == _tTotal) return; _previousMaxWalletToken = _maxWalletToken; _previousMaxTxAmount = _maxTxAmount; _maxTxAmount = _tTotal; _maxWalletToken = _tTotal; } // Restore wallet limits function restoreWalletLimits() private { _maxWalletToken = _previousMaxWalletToken; _maxTxAmount = _previousMaxTxAmount; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0) && spender != address(0), "ERR: zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { /* TRANSACTION AND WALLET LIMITS */ // Limit wallet total if (to != owner() && to != Wallet_Token_Burn && to != Wallet_Marketing && to != Wallet_Burn && to != address(this) && to != uniswapV2Pair && from != owner()){ uint256 heldTokens = balanceOf(to); require((heldTokens + amount) <= _maxWalletToken,"You are trying to buy too many tokens. You have reached the limit for one wallet.");} // Limit the maximum number of tokens that can be bought or sold in one transaction if (from != owner() && to != owner()) require(amount <= _maxTxAmount, "You are trying to buy more than the max transaction limit."); /* BLACKLIST RESTRICTIONS */ if (noBlackList){ require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted. Transaction reverted.");} require(from != address(0) && to != address(0), "ERR: Using 0 address!"); require(amount > 0, "Token value must be higher than zero."); // SwapAndLiquify is triggered after every X transactions - this number can be adjusted using swapTrigger if( txCount >= swapTrigger && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { txCount = 0; uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance > _maxTxAmount) {contractTokenBalance = _maxTxAmount;} if(contractTokenBalance > 0){ swapAndLiquify(contractTokenBalance); } } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to] || (noFeeToTransfer && from != uniswapV2Pair && to != uniswapV2Pair)){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function sendToWallet(address payable wallet, uint256 amount) private { wallet.transfer(amount); } function precDiv(uint a, uint b, uint precision) internal pure returns (uint) { return a*(10**precision)/b; } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 splitPromo; uint256 tokensToPromo; uint256 splitM; uint256 totalBNB; // Processing tokens into BNB (Used for all external wallets and creating the liquidity pair) if (_promoFee != 0 && _FeeLiquidity != 0){ // Calculate the correct ratio splits for marketing and developer splitPromo = precDiv(_promoFee,(_FeeLiquidity+_promoFee),2); tokensToPromo = contractTokenBalance*splitPromo/100; uint256 firstHalf = (contractTokenBalance-tokensToPromo)/2; uint256 secondHalf = contractTokenBalance-(tokensToPromo+firstHalf); uint256 balanceBeforeSwap = address(this).balance; swapTokensForEth(firstHalf+tokensToPromo); totalBNB = address(this).balance - balanceBeforeSwap; uint256 promoBNB = totalBNB*splitPromo/100; addLiquidity(secondHalf, (totalBNB-promoBNB)); emit SwapAndLiquify(firstHalf, (totalBNB-promoBNB), secondHalf); totalBNB = address(this).balance; splitM = precDiv(_FeeMarketing,_promoFee,2); uint256 marketingBNB = totalBNB*splitM/100; sendToWallet(Wallet_Marketing, marketingBNB); sendToWallet(Wallet_Dev, (totalBNB-marketingBNB)); } else if (_promoFee == 0 && _FeeLiquidity != 0){ uint256 firstHalf = contractTokenBalance.div(2); uint256 secondHalf = contractTokenBalance.sub(firstHalf); uint256 balanceBeforeSwap = address(this).balance; swapTokensForEth(firstHalf); uint256 lpBNB = address(this).balance - balanceBeforeSwap; addLiquidity(secondHalf, lpBNB); emit SwapAndLiquify(firstHalf, lpBNB, secondHalf); } else if (_promoFee != 0 && _FeeLiquidity == 0){ swapTokensForEth(contractTokenBalance); totalBNB = address(this).balance; splitM = precDiv(_FeeMarketing,_promoFee,2); uint256 marketingBNB = totalBNB*splitM/100; sendToWallet(Wallet_Marketing, marketingBNB); sendToWallet(Wallet_Dev, (totalBNB-marketingBNB)); } } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } /* Creating Auto Liquidity */ function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, 0, owner(), block.timestamp ); } /* Purge Functions Sometimes, tokens or BNB can get trapped on a contract. Safemoon has about $1.7M trapped on it! So let's make sure that doesn't happen here. These functions allow you to manually purge any trapped BNB or tokens from the contract! Sorted! */ // Manually purge BNB from contract and send to wallets function process_Purge_BNBFromContract() public onlyOwner { // Do not trigger if already in swap require(!inSwapAndLiquify, "Processing liquidity, try to purge later."); // Check BNB on contract uint256 bnbAmount = address(this).balance; // Check correct ratio to purge BNB uint256 splitCalcPromo = precDiv(_FeeMarketing,_promoFee,2); // Send BNB to marketing wallet uint256 marketingBNB = bnbAmount*splitCalcPromo/100; if (marketingBNB > 0){sendToWallet(Wallet_Marketing, marketingBNB);} // Send BNB to developer wallet uint256 developerBNB = bnbAmount-marketingBNB; if (developerBNB > 0){sendToWallet(Wallet_Dev, developerBNB);} } // Manual 'swapAndLiquify' Trigger (Enter the percent of the tokens that you'd like to send to swap and liquify) function process_SwapAndLiquify_Now (uint256 percent_Of_Tokens_To_Liquify) public onlyOwner { // Do not trigger if already in swap require(!inSwapAndLiquify, "Currently processing liquidity, try later."); if (percent_Of_Tokens_To_Liquify > 100){percent_Of_Tokens_To_Liquify == 100;} uint256 tokensOnContract = balanceOf(address(this)); uint256 sendTokens = tokensOnContract*percent_Of_Tokens_To_Liquify/100; swapAndLiquify(sendTokens); } /* Transfer Functions There are 4 transfer options, based on whether the to, from, neither or both wallets are excluded from rewards */ function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee){ removeAllFee(); } else { txCount++; } if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDev(tDev); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDev(tDev); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDev(tDev); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDev(tDev); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } }
Blacklist: If 'noBlackList' is true wallets on this list can not buy - used for known bots Set contract so that blacklisted wallets cannot buy (default is false) Counter for liquify trigger This is the max fee that the contract will accept, it is hard-coded to protect buyers Setting the initial fees 'Previous fees' are used to keep track of fee settings when removing and restoring fees The following settings are used to calculate fee splits when distributing bnb to liquidity and external wallets Fee for the auto LP and the all bnb wallets - used to process fees Wallet limits Max wallet holding (10% at launch) Maximum transaction amount (15% at launch)
contract SaveUkraineCoin is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) public _isExcludedFromFee; mapping (address => bool) private _isExcluded; mapping (address => bool) public _isBlacklisted; bool public noBlackList; address payable private Wallet_Marketing = payable(0x2F67253a6377d147235d30348267D955F2196b2a); address payable private Wallet_Token_Burn = payable(0x2F67253a6377d147235d30348267D955F2196b2a); address payable private Wallet_Dev = payable(0x2F67253a6377d147235d30348267D955F2196b2a); address payable private Wallet_Burn = payable(0x000000000000000000000000000000000000dEaD); address payable private Wallet_zero = payable(0x0000000000000000000000000000000000000000); uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 15000000000 * 10**18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "Save Ukraine Coin"; string private _symbol = "SAVUK"; uint8 private _decimals = 18; uint8 private txCount = 0; uint8 private swapTrigger = 4; uint256 public maxPossibleFee = 17; uint256 public minPossibleReflect = 0; uint256 public _FeeReflection = 2; uint256 public _FeeBurnTokens = 0; uint256 public _FeeLiquidity = 7; uint256 public _FeeMarketing = 4; uint256 public _FeeDev = 0; uint256 private _previousFeeReflection = _FeeReflection; uint256 private _previousFeeLiquidity = _FeeLiquidity; uint256 private _previousFeeMarketing = _FeeMarketing; uint256 private _previousFeeDev = _FeeDev; uint256 private _previousFeeBurnTokens = _FeeBurnTokens; uint256 private _promoFee = _FeeMarketing+_FeeDev; uint256 public _FeesTotal = _FeeMarketing+_FeeDev+_FeeLiquidity+_FeeReflection+_FeeBurnTokens; uint256 private _liquidityAndPromoFee = _FeeMarketing+_FeeDev+_FeeLiquidity; uint256 public _maxWalletToken = _tTotal.mul(10).div(100); uint256 private _previousMaxWalletToken = _maxWalletToken; uint256 public _maxTxAmount = _tTotal.mul(15).div(100); uint256 private _previousMaxTxAmount = _maxTxAmount; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool public inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[owner()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[Wallet_Token_Burn] = true; _isExcludedFromFee[Wallet_Marketing] = true; _isExcludedFromFee[Wallet_Dev] = true; emit Transfer(address(0), owner(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } Presale Functions Presales have different settings, turn them on and off with the click on a button! function Presale_START() external onlyOwner { set_Swap_And_Liquify_Enabled(false); removeAllFee(); removeWalletLimits(); } function Presale_END() external onlyOwner { set_Swap_And_Liquify_Enabled(true); restoreAllFee(); restoreWalletLimits(); } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,,) = _getValues(tAmount); return rTransferAmount; } } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,,) = _getValues(tAmount); return rTransferAmount; } } } else { function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already included"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already included"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already included"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } FEES SAFETY FEATURES TO PROTECT BUYERS! The fee adjustments are limited to protect buyers 1. The total fees can not go above 15% function _set_Fees(uint256 Liquidity, uint256 Marketing, uint256 Reflection, uint256 TokenBurn, uint256 Developer) external onlyOwner() { require((Reflection+TokenBurn+Liquidity+Marketing+Developer) <= maxPossibleFee, "Total fees too high!"); require(Reflection >= minPossibleReflect, "Reflection fee too low"); require(Developer >= 1, "Developer fee too low"); _FeeLiquidity = Liquidity; _FeeMarketing = Marketing; _FeeReflection = Reflection; _FeeBurnTokens = TokenBurn; _FeeDev = Developer; _promoFee = _FeeMarketing+_FeeDev; _liquidityAndPromoFee = _FeeLiquidity+_promoFee; _FeesTotal = _FeeMarketing+_FeeDev+_FeeLiquidity+_FeeBurnTokens+_FeeReflection; } Updating Wallets function Wallet_Update_Marketing(address payable wallet) public onlyOwner() { Wallet_Marketing = wallet; _isExcludedFromFee[Wallet_Marketing] = true; } function Wallet_Update_Dev(address payable wallet) public onlyOwner() { Wallet_Dev = wallet; _isExcludedFromFee[Wallet_Dev] = true; } function Wallet_Update_Token_Burn(address payable wallet) public onlyOwner() { Wallet_Token_Burn = wallet; _isExcludedFromFee[Wallet_Token_Burn] = true; } SwapAndLiquify Switches function set_Swap_And_Liquify_Enabled(bool true_or_false) public onlyOwner { swapAndLiquifyEnabled = true_or_false; emit SwapAndLiquifyEnabledUpdated(true_or_false); } function set_Number_Of_Transactions_Before_Liquify_Trigger(uint8 number_of_transactions) public onlyOwner { swapTrigger = number_of_transactions; } Blacklist - This is used to block a person from buying - known bot users are added to this list prior to launch. We also check for people using snipe bots on the contract before we add liquidity and block these wallets. We like all of our buys to be natural and fair. receive() external payable {} function blacklist_Add_Wallets(address[] calldata addresses) external onlyOwner { uint256 startGas; uint256 gasUsed; for (uint256 i; i < addresses.length; ++i) { if(gasUsed < gasleft()) { startGas = gasleft(); if(!_isBlacklisted[addresses[i]]){ _isBlacklisted[addresses[i]] = true;} gasUsed = startGas - gasleft(); } } } function blacklist_Add_Wallets(address[] calldata addresses) external onlyOwner { uint256 startGas; uint256 gasUsed; for (uint256 i; i < addresses.length; ++i) { if(gasUsed < gasleft()) { startGas = gasleft(); if(!_isBlacklisted[addresses[i]]){ _isBlacklisted[addresses[i]] = true;} gasUsed = startGas - gasleft(); } } } function blacklist_Add_Wallets(address[] calldata addresses) external onlyOwner { uint256 startGas; uint256 gasUsed; for (uint256 i; i < addresses.length; ++i) { if(gasUsed < gasleft()) { startGas = gasleft(); if(!_isBlacklisted[addresses[i]]){ _isBlacklisted[addresses[i]] = true;} gasUsed = startGas - gasleft(); } } } function blacklist_Add_Wallets(address[] calldata addresses) external onlyOwner { uint256 startGas; uint256 gasUsed; for (uint256 i; i < addresses.length; ++i) { if(gasUsed < gasleft()) { startGas = gasleft(); if(!_isBlacklisted[addresses[i]]){ _isBlacklisted[addresses[i]] = true;} gasUsed = startGas - gasleft(); } } } function blacklist_Remove_Wallets(address[] calldata addresses) external onlyOwner { uint256 startGas; uint256 gasUsed; for (uint256 i; i < addresses.length; ++i) { if(gasUsed < gasleft()) { startGas = gasleft(); if(_isBlacklisted[addresses[i]]){ _isBlacklisted[addresses[i]] = false;} gasUsed = startGas - gasleft(); } } } You can turn the blacklist restrictions on and off. During launch, it's a good idea to block known bot users from buying. But these are real people, so when the contract is safe (and the price has increased) you can allow these wallets to buy/sell by setting noBlackList to false function blacklist_Remove_Wallets(address[] calldata addresses) external onlyOwner { uint256 startGas; uint256 gasUsed; for (uint256 i; i < addresses.length; ++i) { if(gasUsed < gasleft()) { startGas = gasleft(); if(_isBlacklisted[addresses[i]]){ _isBlacklisted[addresses[i]] = false;} gasUsed = startGas - gasleft(); } } } You can turn the blacklist restrictions on and off. During launch, it's a good idea to block known bot users from buying. But these are real people, so when the contract is safe (and the price has increased) you can allow these wallets to buy/sell by setting noBlackList to false function blacklist_Remove_Wallets(address[] calldata addresses) external onlyOwner { uint256 startGas; uint256 gasUsed; for (uint256 i; i < addresses.length; ++i) { if(gasUsed < gasleft()) { startGas = gasleft(); if(_isBlacklisted[addresses[i]]){ _isBlacklisted[addresses[i]] = false;} gasUsed = startGas - gasleft(); } } } You can turn the blacklist restrictions on and off. During launch, it's a good idea to block known bot users from buying. But these are real people, so when the contract is safe (and the price has increased) you can allow these wallets to buy/sell by setting noBlackList to false function blacklist_Remove_Wallets(address[] calldata addresses) external onlyOwner { uint256 startGas; uint256 gasUsed; for (uint256 i; i < addresses.length; ++i) { if(gasUsed < gasleft()) { startGas = gasleft(); if(_isBlacklisted[addresses[i]]){ _isBlacklisted[addresses[i]] = false;} gasUsed = startGas - gasleft(); } } } You can turn the blacklist restrictions on and off. During launch, it's a good idea to block known bot users from buying. But these are real people, so when the contract is safe (and the price has increased) you can allow these wallets to buy/sell by setting noBlackList to false function blacklist_Switch(bool true_or_false) public onlyOwner { noBlackList = true_or_false; } When sending tokens to another wallet (not buying or selling) if noFeeToTransfer is true there will be no fee bool public noFeeToTransfer = true; function set_Transfers_Without_Fees(bool true_or_false) external onlyOwner { noFeeToTransfer = true_or_false; } SafeLaunch Features Wallet Limits Wallets are limited in two ways. The amount of tokens that can be purchased in one transaction and the total amount of tokens a wallet can buy. Limiting a wallet prevents one wallet from holding too many tokens, which can scare away potential buyers that worry that a whale might dump! function set_Max_Transaction_Percent(uint256 max_Transaction_Percent) external onlyOwner() { _maxTxAmount = _tTotal*max_Transaction_Percent/100; } function set_Max_Wallet_Holding_Percent(uint256 max_Wallet_Holding_Percent) external onlyOwner() { _maxWalletToken = _tTotal*max_Wallet_Holding_Percent/100; } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, tDev, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity, tDev); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) { uint256 tFee = calculateFeeReflection(tAmount); uint256 tLiquidity = calculateLiquidityAndPromoFee(tAmount); uint256 tDev = calculateFeeDevTokens(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity).sub(tDev); return (tTransferAmount, tFee, tLiquidity, tDev); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rDev = tDev.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity).sub(rDev); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _takeDev(uint256 tDev) private { uint256 currentRate = _getRate(); uint256 rDev = tDev.mul(currentRate); _rOwned[Wallet_Token_Burn] = _rOwned[Wallet_Token_Burn].add(rDev); if(_isExcluded[Wallet_Token_Burn]) _tOwned[Wallet_Token_Burn] = _tOwned[Wallet_Token_Burn].add(tDev); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function calculateFeeReflection(uint256 _amount) private view returns (uint256) { return _amount.mul(_FeeReflection).div( 10**2 ); } function calculateFeeDevTokens(uint256 _amount) private view returns (uint256) { return _amount.mul(_FeeBurnTokens).div( 10**2 ); } function calculateLiquidityAndPromoFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityAndPromoFee).div( 10**2 ); } function removeAllFee() private { if(_FeeReflection == 0 && _FeeLiquidity == 0 && _FeeMarketing == 0 && _FeeDev == 0 && _FeeBurnTokens == 0) return; _previousFeeReflection = _FeeReflection; _previousFeeLiquidity = _FeeLiquidity; _previousFeeMarketing = _FeeMarketing; _previousFeeDev = _FeeDev; _previousFeeBurnTokens = _FeeBurnTokens; _FeeReflection = 0; _liquidityAndPromoFee = 0; _FeeLiquidity = 0; _FeeMarketing = 0; _FeeBurnTokens = 0; _FeeDev = 0; _promoFee = 0; _FeesTotal = 0; } function restoreAllFee() private { _FeeReflection = _previousFeeReflection; _FeeLiquidity = _previousFeeLiquidity; _FeeMarketing = _previousFeeMarketing; _FeeDev = _previousFeeDev; _FeeBurnTokens = _previousFeeBurnTokens; _FeesTotal = _FeeMarketing+_FeeDev+_FeeLiquidity+_FeeReflection+_FeeBurnTokens; _promoFee = _FeeMarketing+_FeeDev; _liquidityAndPromoFee = _FeeMarketing+_FeeDev+_FeeLiquidity; } function removeWalletLimits() private { if(_maxWalletToken == _tTotal && _maxTxAmount == _tTotal) return; _previousMaxWalletToken = _maxWalletToken; _previousMaxTxAmount = _maxTxAmount; _maxTxAmount = _tTotal; _maxWalletToken = _tTotal; } function restoreWalletLimits() private { _maxWalletToken = _previousMaxWalletToken; _maxTxAmount = _previousMaxTxAmount; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0) && spender != address(0), "ERR: zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { TRANSACTION AND WALLET LIMITS if (to != owner() && to != Wallet_Token_Burn && to != Wallet_Marketing && to != Wallet_Burn && to != address(this) && to != uniswapV2Pair && from != owner()){ uint256 heldTokens = balanceOf(to); require((heldTokens + amount) <= _maxWalletToken,"You are trying to buy too many tokens. You have reached the limit for one wallet.");} require(amount <= _maxTxAmount, "You are trying to buy more than the max transaction limit."); BLACKLIST RESTRICTIONS if (noBlackList){ require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted. Transaction reverted.");} require(from != address(0) && to != address(0), "ERR: Using 0 address!"); require(amount > 0, "Token value must be higher than zero."); if( txCount >= swapTrigger && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { txCount = 0; uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance > 0){ swapAndLiquify(contractTokenBalance); } } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to] || (noFeeToTransfer && from != uniswapV2Pair && to != uniswapV2Pair)){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function _transfer( address from, address to, uint256 amount ) private { TRANSACTION AND WALLET LIMITS if (to != owner() && to != Wallet_Token_Burn && to != Wallet_Marketing && to != Wallet_Burn && to != address(this) && to != uniswapV2Pair && from != owner()){ uint256 heldTokens = balanceOf(to); require((heldTokens + amount) <= _maxWalletToken,"You are trying to buy too many tokens. You have reached the limit for one wallet.");} require(amount <= _maxTxAmount, "You are trying to buy more than the max transaction limit."); BLACKLIST RESTRICTIONS if (noBlackList){ require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted. Transaction reverted.");} require(from != address(0) && to != address(0), "ERR: Using 0 address!"); require(amount > 0, "Token value must be higher than zero."); if( txCount >= swapTrigger && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { txCount = 0; uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance > 0){ swapAndLiquify(contractTokenBalance); } } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to] || (noFeeToTransfer && from != uniswapV2Pair && to != uniswapV2Pair)){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } if (from != owner() && to != owner()) function _transfer( address from, address to, uint256 amount ) private { TRANSACTION AND WALLET LIMITS if (to != owner() && to != Wallet_Token_Burn && to != Wallet_Marketing && to != Wallet_Burn && to != address(this) && to != uniswapV2Pair && from != owner()){ uint256 heldTokens = balanceOf(to); require((heldTokens + amount) <= _maxWalletToken,"You are trying to buy too many tokens. You have reached the limit for one wallet.");} require(amount <= _maxTxAmount, "You are trying to buy more than the max transaction limit."); BLACKLIST RESTRICTIONS if (noBlackList){ require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted. Transaction reverted.");} require(from != address(0) && to != address(0), "ERR: Using 0 address!"); require(amount > 0, "Token value must be higher than zero."); if( txCount >= swapTrigger && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { txCount = 0; uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance > 0){ swapAndLiquify(contractTokenBalance); } } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to] || (noFeeToTransfer && from != uniswapV2Pair && to != uniswapV2Pair)){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function _transfer( address from, address to, uint256 amount ) private { TRANSACTION AND WALLET LIMITS if (to != owner() && to != Wallet_Token_Burn && to != Wallet_Marketing && to != Wallet_Burn && to != address(this) && to != uniswapV2Pair && from != owner()){ uint256 heldTokens = balanceOf(to); require((heldTokens + amount) <= _maxWalletToken,"You are trying to buy too many tokens. You have reached the limit for one wallet.");} require(amount <= _maxTxAmount, "You are trying to buy more than the max transaction limit."); BLACKLIST RESTRICTIONS if (noBlackList){ require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted. Transaction reverted.");} require(from != address(0) && to != address(0), "ERR: Using 0 address!"); require(amount > 0, "Token value must be higher than zero."); if( txCount >= swapTrigger && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { txCount = 0; uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance > 0){ swapAndLiquify(contractTokenBalance); } } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to] || (noFeeToTransfer && from != uniswapV2Pair && to != uniswapV2Pair)){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } if(contractTokenBalance > _maxTxAmount) {contractTokenBalance = _maxTxAmount;} function _transfer( address from, address to, uint256 amount ) private { TRANSACTION AND WALLET LIMITS if (to != owner() && to != Wallet_Token_Burn && to != Wallet_Marketing && to != Wallet_Burn && to != address(this) && to != uniswapV2Pair && from != owner()){ uint256 heldTokens = balanceOf(to); require((heldTokens + amount) <= _maxWalletToken,"You are trying to buy too many tokens. You have reached the limit for one wallet.");} require(amount <= _maxTxAmount, "You are trying to buy more than the max transaction limit."); BLACKLIST RESTRICTIONS if (noBlackList){ require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted. Transaction reverted.");} require(from != address(0) && to != address(0), "ERR: Using 0 address!"); require(amount > 0, "Token value must be higher than zero."); if( txCount >= swapTrigger && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { txCount = 0; uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance > 0){ swapAndLiquify(contractTokenBalance); } } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to] || (noFeeToTransfer && from != uniswapV2Pair && to != uniswapV2Pair)){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function _transfer( address from, address to, uint256 amount ) private { TRANSACTION AND WALLET LIMITS if (to != owner() && to != Wallet_Token_Burn && to != Wallet_Marketing && to != Wallet_Burn && to != address(this) && to != uniswapV2Pair && from != owner()){ uint256 heldTokens = balanceOf(to); require((heldTokens + amount) <= _maxWalletToken,"You are trying to buy too many tokens. You have reached the limit for one wallet.");} require(amount <= _maxTxAmount, "You are trying to buy more than the max transaction limit."); BLACKLIST RESTRICTIONS if (noBlackList){ require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted. Transaction reverted.");} require(from != address(0) && to != address(0), "ERR: Using 0 address!"); require(amount > 0, "Token value must be higher than zero."); if( txCount >= swapTrigger && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { txCount = 0; uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance > 0){ swapAndLiquify(contractTokenBalance); } } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to] || (noFeeToTransfer && from != uniswapV2Pair && to != uniswapV2Pair)){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function sendToWallet(address payable wallet, uint256 amount) private { wallet.transfer(amount); } function precDiv(uint a, uint b, uint precision) internal pure returns (uint) { return a*(10**precision)/b; } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 splitPromo; uint256 tokensToPromo; uint256 splitM; uint256 totalBNB; if (_promoFee != 0 && _FeeLiquidity != 0){ splitPromo = precDiv(_promoFee,(_FeeLiquidity+_promoFee),2); tokensToPromo = contractTokenBalance*splitPromo/100; uint256 firstHalf = (contractTokenBalance-tokensToPromo)/2; uint256 secondHalf = contractTokenBalance-(tokensToPromo+firstHalf); uint256 balanceBeforeSwap = address(this).balance; swapTokensForEth(firstHalf+tokensToPromo); totalBNB = address(this).balance - balanceBeforeSwap; uint256 promoBNB = totalBNB*splitPromo/100; addLiquidity(secondHalf, (totalBNB-promoBNB)); emit SwapAndLiquify(firstHalf, (totalBNB-promoBNB), secondHalf); totalBNB = address(this).balance; splitM = precDiv(_FeeMarketing,_promoFee,2); uint256 marketingBNB = totalBNB*splitM/100; sendToWallet(Wallet_Marketing, marketingBNB); sendToWallet(Wallet_Dev, (totalBNB-marketingBNB)); uint256 firstHalf = contractTokenBalance.div(2); uint256 secondHalf = contractTokenBalance.sub(firstHalf); uint256 balanceBeforeSwap = address(this).balance; swapTokensForEth(firstHalf); uint256 lpBNB = address(this).balance - balanceBeforeSwap; addLiquidity(secondHalf, lpBNB); emit SwapAndLiquify(firstHalf, lpBNB, secondHalf); swapTokensForEth(contractTokenBalance); totalBNB = address(this).balance; splitM = precDiv(_FeeMarketing,_promoFee,2); uint256 marketingBNB = totalBNB*splitM/100; sendToWallet(Wallet_Marketing, marketingBNB); sendToWallet(Wallet_Dev, (totalBNB-marketingBNB)); } } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 splitPromo; uint256 tokensToPromo; uint256 splitM; uint256 totalBNB; if (_promoFee != 0 && _FeeLiquidity != 0){ splitPromo = precDiv(_promoFee,(_FeeLiquidity+_promoFee),2); tokensToPromo = contractTokenBalance*splitPromo/100; uint256 firstHalf = (contractTokenBalance-tokensToPromo)/2; uint256 secondHalf = contractTokenBalance-(tokensToPromo+firstHalf); uint256 balanceBeforeSwap = address(this).balance; swapTokensForEth(firstHalf+tokensToPromo); totalBNB = address(this).balance - balanceBeforeSwap; uint256 promoBNB = totalBNB*splitPromo/100; addLiquidity(secondHalf, (totalBNB-promoBNB)); emit SwapAndLiquify(firstHalf, (totalBNB-promoBNB), secondHalf); totalBNB = address(this).balance; splitM = precDiv(_FeeMarketing,_promoFee,2); uint256 marketingBNB = totalBNB*splitM/100; sendToWallet(Wallet_Marketing, marketingBNB); sendToWallet(Wallet_Dev, (totalBNB-marketingBNB)); uint256 firstHalf = contractTokenBalance.div(2); uint256 secondHalf = contractTokenBalance.sub(firstHalf); uint256 balanceBeforeSwap = address(this).balance; swapTokensForEth(firstHalf); uint256 lpBNB = address(this).balance - balanceBeforeSwap; addLiquidity(secondHalf, lpBNB); emit SwapAndLiquify(firstHalf, lpBNB, secondHalf); swapTokensForEth(contractTokenBalance); totalBNB = address(this).balance; splitM = precDiv(_FeeMarketing,_promoFee,2); uint256 marketingBNB = totalBNB*splitM/100; sendToWallet(Wallet_Marketing, marketingBNB); sendToWallet(Wallet_Dev, (totalBNB-marketingBNB)); } } } else if (_promoFee == 0 && _FeeLiquidity != 0){ } else if (_promoFee != 0 && _FeeLiquidity == 0){ function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } Creating Auto Liquidity function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, 0, 0, owner(), block.timestamp ); } Purge Functions Sometimes, tokens or BNB can get trapped on a contract. Safemoon has about $1.7M trapped on it! uniswapV2Router.addLiquidityETH{value: ethAmount}( So let's make sure that doesn't happen here. These functions allow you to manually purge any trapped BNB or tokens from the contract! Sorted! function process_Purge_BNBFromContract() public onlyOwner { require(!inSwapAndLiquify, "Processing liquidity, try to purge later."); uint256 bnbAmount = address(this).balance; uint256 splitCalcPromo = precDiv(_FeeMarketing,_promoFee,2); uint256 marketingBNB = bnbAmount*splitCalcPromo/100; uint256 developerBNB = bnbAmount-marketingBNB; } if (marketingBNB > 0){sendToWallet(Wallet_Marketing, marketingBNB);} if (developerBNB > 0){sendToWallet(Wallet_Dev, developerBNB);} function process_SwapAndLiquify_Now (uint256 percent_Of_Tokens_To_Liquify) public onlyOwner { require(!inSwapAndLiquify, "Currently processing liquidity, try later."); uint256 tokensOnContract = balanceOf(address(this)); uint256 sendTokens = tokensOnContract*percent_Of_Tokens_To_Liquify/100; swapAndLiquify(sendTokens); } Transfer Functions There are 4 transfer options, based on whether the to, from, neither or both wallets are excluded from rewards if (percent_Of_Tokens_To_Liquify > 100){percent_Of_Tokens_To_Liquify == 100;} function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee){ removeAllFee(); txCount++; } if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee){ removeAllFee(); txCount++; } if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } } else { function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee){ removeAllFee(); txCount++; } if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } } else if (!_isExcluded[sender] && _isExcluded[recipient]) { } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { } else if (_isExcluded[sender] && _isExcluded[recipient]) { } else { function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDev(tDev); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDev(tDev); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDev(tDev); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDev(tDev); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } }
7,777,556
[ 1, 25811, 30, 971, 296, 2135, 13155, 682, 11, 353, 638, 17662, 2413, 603, 333, 666, 848, 486, 30143, 300, 1399, 364, 4846, 2512, 87, 1000, 6835, 1427, 716, 25350, 17662, 2413, 2780, 30143, 261, 1886, 353, 629, 13, 9354, 364, 4501, 372, 1164, 3080, 1220, 353, 326, 943, 14036, 716, 326, 6835, 903, 2791, 16, 518, 353, 7877, 17, 24808, 358, 17151, 30143, 414, 13274, 326, 2172, 1656, 281, 296, 8351, 1656, 281, 11, 854, 1399, 358, 3455, 3298, 434, 14036, 1947, 1347, 9427, 471, 3127, 6053, 1656, 281, 1021, 3751, 1947, 854, 1399, 358, 4604, 14036, 11019, 1347, 1015, 665, 8490, 324, 6423, 358, 4501, 372, 24237, 471, 3903, 17662, 2413, 30174, 364, 326, 3656, 511, 52, 471, 326, 777, 324, 6423, 17662, 2413, 300, 1399, 358, 1207, 1656, 281, 20126, 8181, 4238, 9230, 19918, 261, 2163, 9, 622, 8037, 13, 18848, 2492, 3844, 261, 3600, 9, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 7074, 57, 79, 354, 558, 27055, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 7010, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 389, 291, 16461, 1265, 14667, 31, 7010, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 31, 7010, 203, 377, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 389, 291, 13155, 18647, 31, 203, 203, 565, 1426, 1071, 1158, 13155, 682, 31, 203, 27699, 203, 565, 1758, 8843, 429, 3238, 20126, 67, 3882, 21747, 273, 8843, 429, 12, 20, 92, 22, 42, 9599, 30304, 69, 4449, 4700, 72, 29488, 30803, 72, 23, 4630, 8875, 5558, 27, 40, 29, 2539, 42, 22, 28644, 70, 22, 69, 1769, 7010, 565, 1758, 8843, 429, 3238, 20126, 67, 1345, 67, 38, 321, 273, 8843, 429, 12, 20, 92, 22, 42, 9599, 30304, 69, 4449, 4700, 72, 29488, 30803, 72, 23, 4630, 8875, 5558, 27, 40, 29, 2539, 42, 22, 28644, 70, 22, 69, 1769, 7010, 565, 1758, 8843, 429, 3238, 20126, 67, 8870, 273, 8843, 429, 12, 20, 92, 22, 42, 9599, 30304, 69, 4449, 4700, 72, 29488, 30803, 72, 23, 4630, 8875, 2 ]
pragma solidity 0.4.25; /* __ __ ___ ______ /\ \ __/\ \ /\_ \ /\__ _\ \ \ \/\ \ \ \ __\//\ \ ___ ___ ___ ___ __ \/_/\ \/ ___ \ \ \ \ \ \ \ /'__`\\ \ \ /'___\ / __`\ /' __` __`\ /'__`\ \ \ \ / __`\ \ \ \_/ \_\ \/\ __/ \_\ \_/\ \__//\ \L\ \/\ \/\ \/\ \/\ __/ \ \ \/\ \L\ \__ __ __ \ `\___x___/\ \____\/\____\ \____\ \____/\ \_\ \_\ \_\ \____\ \ \_\ \____/\_\/\_\/\_\ '\/__//__/ \/____/\/____/\/____/\/___/ \/_/\/_/\/_/\/____/ \/_/\/___/\/_/\/_/\/_/ __/\\\\\\\\\\\\\\\__/\\\\\\\\\\\\\\\__/\\\________/\\\_____/\\\\\\\\\____ _\/\\\///////////__\///////\\\/////__\/\\\_____/\\\//____/\\\\\\\\\\\\\__ _\/\\\___________________\/\\\_______\/\\\__/\\\//______/\\\/////////\\\_ _\/\\\\\\\\\\\___________\/\\\_______\/\\\\\\//\\\_____\/\\\_______\/\\\_ _\/\\\///////____________\/\\\_______\/\\\//_\//\\\____\/\\\\\\\\\\\\\\\_ _\/\\\___________________\/\\\_______\/\\\____\//\\\___\/\\\/////////\\\_ _\/\\\___________________\/\\\_______\/\\\_____\//\\\__\/\\\_______\/\\\_ _\/\\\___________________\/\\\_______\/\\\______\//\\\_\/\\\_______\/\\\_ _\///____________________\///________\///________\///__\///________\///__ // ---------------------------------------------------------------------------- // 'FTKA' token contract, having Crowdsale and Reward functionality // // Contract Owner : 0xef9EcD8a0A2E4b31d80B33E243761f4D93c990a8 // Symbol : FTKA // Name : FTKA // Total supply : 1,000,000,000 (1 Billion) // Tokens for ICO : 800,000,000 (800 Million) // Tokens to Owner: 200,000,000 (200 Million) // Decimals : 8 // // Copyright © 2018 onwards FTKA. (https://ftka.io) // Contract designed by EtherAuthority (https://EtherAuthority.io) // ---------------------------------------------------------------------------- /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract owned { address public owner; constructor () public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { // Public variables of the token using SafeMath for uint256; string public name; string public symbol; uint8 public decimals = 8; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; uint256 public reservedForICO; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor ( uint256 initialSupply, uint256 allocatedForICO, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply.mul(1e8); // Update total supply with the decimal amount reservedForICO = allocatedForICO.mul(1e8); // Tokens reserved For ICO balanceOf[this] = reservedForICO; // 800 Million Tokens will remain in the contract balanceOf[msg.sender]=totalSupply.sub(reservedForICO); // Rest of tokens will be sent to owner name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to].add(_value) > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from].add(balanceOf[_to]); // Subtract from the sender balanceOf[_from] = balanceOf[_from].sub(_value); // Add the same to the recipient balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * 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) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in 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) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } } /****************************************************/ /* MAIN FTKA TOKEN CONTRACT STARTS HERE */ /****************************************************/ contract FTKA is owned, TokenERC20 { //**************************************************// //------------- Code for the FTKA Token -------------// //**************************************************// // Public variables of the token string internal tokenName = "FTKA"; string internal tokenSymbol = "FTKA"; uint256 internal initialSupply = 1000000000; // 1 Billion uint256 private allocatedForICO = 800000000; // 800 Million // Records for the fronzen accounts mapping (address => bool) public frozenAccount; // This generates a public event on the blockchain that will notify clients event FrozenFunds(address target, bool frozen); // Initializes contract with initial supply of tokens sent to the creator as well as contract constructor () TokenERC20(initialSupply, allocatedForICO, tokenName, tokenSymbol) public { } /** * Transfer tokens - Internal transfer, only can be called by this contract * * This checks if the sender or recipient is not fronzen * * This keeps the track of total token holders and adds new holders as well. * * Send `_value` tokens to `_to` from your account * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount of tokens to send */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); } /** * @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens * * @param target Address to be frozen * @param freeze either to freeze it or not */ function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } //**************************************************// //------------- Code for the Crowdsale -------------// //**************************************************// //public variables for the Crowdsale uint256 public icoStartDate = 1542326400 ; // 16 November 2018 00:00:00 - GMT uint256 public icoEndDate = 1554076799 ; // 31 March 2019 23:59:59 - GMT uint256 public exchangeRate = 5000; // 1 ETH = 5000 Tokens uint256 public tokensSold = 0; // How many tokens sold in crowdsale bool internal withdrawTokensOnlyOnce = true; // Admin can withdraw unsold tokens after ICO only once //public variables of reward distribution mapping(address => uint256) public investorContribution; //Track record whether token holder exist or not address[] public icoContributors; //Array of addresses of ICO contributors uint256 public tokenHolderIndex = 0; //To split the iterations of For Loop uint256 public totalContributors = 0; //Total number of ICO contributors /** * @dev Fallback function, it accepts Ether from owner address as well as non-owner address * @dev If ether came from owner address, then it will consider as reward payment to ICO contributors * @dev If ether came from non-owner address, then it will consider as ICO investment contribution */ function () payable public { if(msg.sender == owner && msg.value > 0){ processRewards(); //This function will process reward distribution } else{ processICO(); //This function will process ICO and sends tokens to contributor } } /** * @dev Function which processes ICO contributions * @dev It calcualtes token amount from exchangeRate and also adds Bonuses if applicable * @dev Ether will be forwarded to owner immidiately. */ function processICO() internal { require(icoEndDate > now); require(icoStartDate < now); uint ethervalueWEI=msg.value; uint256 token = ethervalueWEI.div(1e10).mul(exchangeRate);// token amount = weiamount * price uint256 totalTokens = token.add(purchaseBonus(token)); // token + bonus tokensSold = tokensSold.add(totalTokens); _transfer(this, msg.sender, totalTokens); // makes the token transfer forwardEherToOwner(); // send ether to owner //if contributor does not exist in tokenHolderExist mapping, then add into it as well as add in tokenHolders array if(investorContribution[msg.sender] == 0){ icoContributors.push(msg.sender); totalContributors++; } investorContribution[msg.sender] = investorContribution[msg.sender].add(totalTokens); } /** * @dev Function which processes ICO contributions * @dev It calcualtes token amount from exchangeRate and also adds Bonuses if applicable * @dev Ether will be forwarded to owner immidiately. */ function processRewards() internal { for(uint256 i = 0; i < 150; i++){ if(tokenHolderIndex < totalContributors){ uint256 userContribution = investorContribution[icoContributors[tokenHolderIndex]]; if(userContribution > 0){ uint256 rewardPercentage = userContribution.mul(1000).div(tokensSold); uint256 reward = msg.value.mul(rewardPercentage).div(1000); icoContributors[tokenHolderIndex].transfer(reward); tokenHolderIndex++; } }else{ //this code will run only when all the dividend/reward has been paid tokenHolderIndex = 0; break; } } } /** * Automatocally forwards ether from smart contract to owner address. */ function forwardEherToOwner() internal { owner.transfer(msg.value); } /** * @dev Calculates purchase bonus according to the schedule. * @dev SafeMath at some place is not used intentionally as overflow is impossible, and that saves gas cost * * @param _tokenAmount calculating tokens from amount of tokens * * @return bonus amount in wei * */ function purchaseBonus(uint256 _tokenAmount) public view returns(uint256){ uint256 week1 = icoStartDate + 604800; //25% token bonus uint256 week2 = week1 + 604800; //20% token bonus uint256 week3 = week2 + 604800; //15% token bonus uint256 week4 = week3 + 604800; //10% token bonus uint256 week5 = week4 + 604800; //5% token bonus if(now > icoStartDate && now < week1){ return _tokenAmount.mul(25).div(100); //25% bonus } else if(now > week1 && now < week2){ return _tokenAmount.mul(20).div(100); //20% bonus } else if(now > week2 && now < week3){ return _tokenAmount.mul(15).div(100); //15% bonus } else if(now > week3 && now < week4){ return _tokenAmount.mul(10).div(100); //10% bonus } else if(now > week4 && now < week5){ return _tokenAmount.mul(5).div(100); //5% bonus } else{ return 0; } } /** * Function to check wheter ICO is running or not. * * @return bool for whether ICO is running or not */ function isICORunning() public view returns(bool){ if(icoEndDate > now && icoStartDate < now){ return true; }else{ return false; } } /** * Just in case, owner wants to transfer Tokens from contract to owner address */ function manualWithdrawToken(uint256 _amount) onlyOwner public { uint256 tokenAmount = _amount.mul(1 ether); _transfer(this, msg.sender, tokenAmount); } /** * Just in case, owner wants to transfer Ether from contract to owner address */ function manualWithdrawEther()onlyOwner public{ address(owner).transfer(address(this).balance); } }
Track record whether token holder exist or not
mapping(address => uint256) public investorContribution;
5,387,613
[ 1, 4402, 1409, 2856, 1147, 10438, 1005, 578, 486, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 2198, 395, 280, 442, 4027, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-01-21 */ /** *Submitted for verification at Etherscan.io on 2020-01-21 */ // File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.5.2; /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/lib/CommonMath.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library CommonMath { using SafeMath for uint256; uint256 public constant SCALE_FACTOR = 10 ** 18; uint256 public constant MAX_UINT_256 = 2 ** 256 - 1; /** * Returns scale factor equal to 10 ** 18 * * @return 10 ** 18 */ function scaleFactor() internal pure returns (uint256) { return SCALE_FACTOR; } /** * Calculates and returns the maximum value for a uint256 * * @return The maximum value for uint256 */ function maxUInt256() internal pure returns (uint256) { return MAX_UINT_256; } /** * Increases a value by the scale factor to allow for additional precision * during mathematical operations */ function scale( uint256 a ) internal pure returns (uint256) { return a.mul(SCALE_FACTOR); } /** * Divides a value by the scale factor to allow for additional precision * during mathematical operations */ function deScale( uint256 a ) internal pure returns (uint256) { return a.div(SCALE_FACTOR); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * @dev Performs division where if there is a modulo, the value is rounded up */ function divCeil(uint256 a, uint256 b) internal pure returns(uint256) { return a.mod(b) > 0 ? a.div(b).add(1) : a.div(b); } /** * Checks for rounding errors and returns value of potential partial amounts of a principal * * @param _principal Number fractional amount is derived from * @param _numerator Numerator of fraction * @param _denominator Denominator of fraction * @return uint256 Fractional amount of principal calculated */ function getPartialAmount( uint256 _principal, uint256 _numerator, uint256 _denominator ) internal pure returns (uint256) { // Get remainder of partial amount (if 0 not a partial amount) uint256 remainder = mulmod(_principal, _numerator, _denominator); // Return if not a partial amount if (remainder == 0) { return _principal.mul(_numerator).div(_denominator); } // Calculate error percentage uint256 errPercentageTimes1000000 = remainder.mul(1000000).div(_numerator.mul(_principal)); // Require error percentage is less than 0.1%. require( errPercentageTimes1000000 < 1000, "CommonMath.getPartialAmount: Rounding error exceeds bounds" ); return _principal.mul(_numerator).div(_denominator); } /* * Gets the rounded up log10 of passed value * * @param _value Value to calculate ceil(log()) on * @return uint256 Output value */ function ceilLog10( uint256 _value ) internal pure returns (uint256) { // Make sure passed value is greater than 0 require ( _value > 0, "CommonMath.ceilLog10: Value must be greater than zero." ); // Since log10(1) = 0, if _value = 1 return 0 if (_value == 1) return 0; // Calcualte ceil(log10()) uint256 x = _value - 1; uint256 result = 0; if (x >= 10 ** 64) { x /= 10 ** 64; result += 64; } if (x >= 10 ** 32) { x /= 10 ** 32; result += 32; } if (x >= 10 ** 16) { x /= 10 ** 16; result += 16; } if (x >= 10 ** 8) { x /= 10 ** 8; result += 8; } if (x >= 10 ** 4) { x /= 10 ** 4; result += 4; } if (x >= 100) { x /= 100; result += 2; } if (x >= 10) { result += 1; } return result + 1; } } // File: contracts/lib/CompoundUtils.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title CompoundUtils * @author Set Protocol * * Collection of common Compound functions for use in Set Protocol contracts */ library CompoundUtils { using SafeMath for uint256; /* * Utility function to convert a specified amount of cTokens to underlying * token based on the cToken's exchange rate * * @param _cTokenAmount Amount of cTokens that will be converted to underlying * @param _cTokenExchangeRate Exchange rate for the cToken * @return underlyingAmount Amount of underlying ERC20 tokens */ function convertCTokenToUnderlying( uint256 _cTokenAmount, uint256 _cTokenExchangeRate ) internal pure returns (uint256) { // Underlying units is calculated as cToken quantity * exchangeRate divided by 10 ** 18 and rounded up. uint256 a = _cTokenAmount.mul(_cTokenExchangeRate); uint256 b = CommonMath.scaleFactor(); // Round value up return CommonMath.divCeil(a, b); } } // File: contracts/lib/IERC20.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IERC20 * @author Set Protocol * * Interface for using ERC20 Tokens. This interface is needed to interact with tokens that are not * fully ERC20 compliant and return something other than true on successful transfers. */ interface IERC20 { function balanceOf( address _owner ) external view returns (uint256); function allowance( address _owner, address _spender ) external view returns (uint256); function transfer( address _to, uint256 _quantity ) external; function transferFrom( address _from, address _to, uint256 _quantity ) external; function approve( address _spender, uint256 _quantity ) external returns (bool); function totalSupply() external returns (uint256); } // File: contracts/lib/ERC20Wrapper.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ERC20Wrapper * @author Set Protocol * * This library contains functions for interacting wtih ERC20 tokens, even those not fully compliant. * For all functions we will only accept tokens that return a null or true value, any other values will * cause the operation to revert. */ library ERC20Wrapper { // ============ Internal Functions ============ /** * Check balance owner's balance of ERC20 token * * @param _token The address of the ERC20 token * @param _owner The owner who's balance is being checked * @return uint256 The _owner's amount of tokens */ function balanceOf( address _token, address _owner ) external view returns (uint256) { return IERC20(_token).balanceOf(_owner); } /** * Checks spender's allowance to use token's on owner's behalf. * * @param _token The address of the ERC20 token * @param _owner The token owner address * @param _spender The address the allowance is being checked on * @return uint256 The spender's allowance on behalf of owner */ function allowance( address _token, address _owner, address _spender ) internal view returns (uint256) { return IERC20(_token).allowance(_owner, _spender); } /** * Transfers tokens from an address. Handle's tokens that return true or null. * If other value returned, reverts. * * @param _token The address of the ERC20 token * @param _to The address to transfer to * @param _quantity The amount of tokens to transfer */ function transfer( address _token, address _to, uint256 _quantity ) external { IERC20(_token).transfer(_to, _quantity); // Check that transfer returns true or null require( checkSuccess(), "ERC20Wrapper.transfer: Bad return value" ); } /** * Transfers tokens from an address (that has set allowance on the proxy). * Handle's tokens that return true or null. If other value returned, reverts. * * @param _token The address of the ERC20 token * @param _from The address to transfer from * @param _to The address to transfer to * @param _quantity The number of tokens to transfer */ function transferFrom( address _token, address _from, address _to, uint256 _quantity ) external { IERC20(_token).transferFrom(_from, _to, _quantity); // Check that transferFrom returns true or null require( checkSuccess(), "ERC20Wrapper.transferFrom: Bad return value" ); } /** * Grants spender ability to spend on owner's behalf. * Handle's tokens that return true or null. If other value returned, reverts. * * @param _token The address of the ERC20 token * @param _spender The address to approve for transfer * @param _quantity The amount of tokens to approve spender for */ function approve( address _token, address _spender, uint256 _quantity ) internal { IERC20(_token).approve(_spender, _quantity); // Check that approve returns true or null require( checkSuccess(), "ERC20Wrapper.approve: Bad return value" ); } /** * Ensure's the owner has granted enough allowance for system to * transfer tokens. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner * @param _spender The address to grant/check allowance for * @param _quantity The amount to see if allowed for */ function ensureAllowance( address _token, address _owner, address _spender, uint256 _quantity ) internal { uint256 currentAllowance = allowance(_token, _owner, _spender); if (currentAllowance < _quantity) { approve( _token, _spender, CommonMath.maxUInt256() ); } } // ============ Private Functions ============ /** * Checks the return value of the previous function up to 32 bytes. Returns true if the previous * function returned 0 bytes or 1. */ function checkSuccess( ) private pure returns (bool) { // default to failure uint256 returnValue = 0; assembly { // check number of bytes returned from last function call switch returndatasize // no bytes returned: assume success case 0x0 { returnValue := 1 } // 32 bytes returned case 0x20 { // copy 32 bytes into scratch space returndatacopy(0x0, 0x0, 0x20) // load those bytes into returnValue returnValue := mload(0x0) } // not sure what was returned: dont mark as success default { } } // check if returned value is one or nothing return returnValue == 1; } } // File: contracts/core/interfaces/ICToken.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ICToken * @author Set Protocol * * Interface for interacting with Compound cTokens */ interface ICToken { /** * Calculates the exchange rate from the underlying to the CToken * * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function decimals() external view returns(uint8); /** * Sender supplies assets into the market and receives cTokens in exchange * * @notice Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure */ function mint(uint mintAmount) external returns (uint); /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint); } // File: contracts/core/interfaces/IRebalanceAuctionModule.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; pragma experimental "ABIEncoderV2"; /** * @title IRebalanceAuctionModule * @author Set Protocol * * The IRebalanceAuctionModule interface provides a light-weight, structured way to interact with the * RebalanceAuctionModule contract from another contract. */ interface IRebalanceAuctionModule { /** * Bid on rebalancing a given quantity of sets held by a rebalancing token * The tokens are returned to the user. * * @param _rebalancingSetToken Address of the rebalancing token being bid on * @param _quantity Number of currentSets to rebalance * @param _allowPartialFill Set to true if want to partially fill bid when quantity * is greater than currentRemainingSets */ function bidAndWithdraw( address _rebalancingSetToken, uint256 _quantity, bool _allowPartialFill ) external; } // File: contracts/core/lib/RebalancingLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingLibrary * @author Set Protocol * * The RebalancingLibrary contains functions for facilitating the rebalancing process for * Rebalancing Set Tokens. Removes the old calculation functions * */ library RebalancingLibrary { /* ============ Enums ============ */ enum State { Default, Proposal, Rebalance, Drawdown } /* ============ Structs ============ */ struct AuctionPriceParameters { uint256 auctionStartTime; uint256 auctionTimeToPivot; uint256 auctionStartPrice; uint256 auctionPivotPrice; } struct BiddingParameters { uint256 minimumBid; uint256 remainingCurrentSets; uint256[] combinedCurrentUnits; uint256[] combinedNextSetUnits; address[] combinedTokenArray; } } // File: contracts/core/interfaces/IRebalancingSetToken.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IRebalancingSetToken * @author Set Protocol * * The IRebalancingSetToken interface provides a light-weight, structured way to interact with the * RebalancingSetToken contract from another contract. */ interface IRebalancingSetToken { /* * Get the auction library contract used for the current rebalance * * @return address Address of auction library used in the upcoming auction */ function auctionLibrary() external view returns (address); /* * Get totalSupply of Rebalancing Set * * @return totalSupply */ function totalSupply() external view returns (uint256); /* * Get proposalTimeStamp of Rebalancing Set * * @return proposalTimeStamp */ function proposalStartTime() external view returns (uint256); /* * Get lastRebalanceTimestamp of Rebalancing Set * * @return lastRebalanceTimestamp */ function lastRebalanceTimestamp() external view returns (uint256); /* * Get rebalanceInterval of Rebalancing Set * * @return rebalanceInterval */ function rebalanceInterval() external view returns (uint256); /* * Get rebalanceState of Rebalancing Set * * @return RebalancingLibrary.State Current rebalance state of the RebalancingSetToken */ function rebalanceState() external view returns (RebalancingLibrary.State); /* * Get the starting amount of current SetToken for the current auction * * @return rebalanceState */ function startingCurrentSetAmount() external view returns (uint256); /** * Gets the balance of the specified address. * * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf( address owner ) external view returns (uint256); /** * Function used to set the terms of the next rebalance and start the proposal period * * @param _nextSet The Set to rebalance into * @param _auctionLibrary The library used to calculate the Dutch Auction price * @param _auctionTimeToPivot The amount of time for the auction to go ffrom start to pivot price * @param _auctionStartPrice The price to start the auction at * @param _auctionPivotPrice The price at which the price curve switches from linear to exponential */ function propose( address _nextSet, address _auctionLibrary, uint256 _auctionTimeToPivot, uint256 _auctionStartPrice, uint256 _auctionPivotPrice ) external; /* * Get natural unit of Set * * @return uint256 Natural unit of Set */ function naturalUnit() external view returns (uint256); /** * Returns the address of the current base SetToken with the current allocation * * @return A address representing the base SetToken */ function currentSet() external view returns (address); /** * Returns the address of the next base SetToken with the post auction allocation * * @return address Address representing the base SetToken */ function nextSet() external view returns (address); /* * Get the unit shares of the rebalancing Set * * @return unitShares Unit Shares of the base Set */ function unitShares() external view returns (uint256); /* * Burn set token for given address. * Can only be called by authorized contracts. * * @param _from The address of the redeeming account * @param _quantity The number of sets to burn from redeemer */ function burn( address _from, uint256 _quantity ) external; /* * Place bid during rebalance auction. Can only be called by Core. * * @param _quantity The amount of currentSet to be rebalanced * @return combinedTokenArray Array of token addresses invovled in rebalancing * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function placeBid( uint256 _quantity ) external returns (address[] memory, uint256[] memory, uint256[] memory); /* * Get combinedTokenArray of Rebalancing Set * * @return combinedTokenArray */ function getCombinedTokenArrayLength() external view returns (uint256); /* * Get combinedTokenArray of Rebalancing Set * * @return combinedTokenArray */ function getCombinedTokenArray() external view returns (address[] memory); /* * Get failedAuctionWithdrawComponents of Rebalancing Set * * @return failedAuctionWithdrawComponents */ function getFailedAuctionWithdrawComponents() external view returns (address[] memory); /* * Get auctionPriceParameters for current auction * * @return uint256[4] AuctionPriceParameters for current rebalance auction */ function getAuctionPriceParameters() external view returns (uint256[] memory); /* * Get biddingParameters for current auction * * @return uint256[2] BiddingParameters for current rebalance auction */ function getBiddingParameters() external view returns (uint256[] memory); /* * Get token inflows and outflows required for bid. Also the amount of Rebalancing * Sets that would be generated. * * @param _quantity The amount of currentSet to be rebalanced * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function getBidPrice( uint256 _quantity ) external view returns (uint256[] memory, uint256[] memory); } // File: contracts/core/interfaces/ITransferProxy.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ITransferProxy * @author Set Protocol * * The ITransferProxy interface provides a light-weight, structured way to interact with the * TransferProxy contract from another contract. */ interface ITransferProxy { /* ============ External Functions ============ */ /** * Transfers tokens from an address (that has set allowance on the proxy). * Can only be called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function transfer( address _token, uint256 _quantity, address _from, address _to ) external; /** * Transfers tokens from an address (that has set allowance on the proxy). * Can only be called by authorized core contracts. * * @param _tokens The addresses of the ERC20 token * @param _quantities The numbers of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function batchTransfer( address[] calldata _tokens, uint256[] calldata _quantities, address _from, address _to ) external; } // File: contracts/core/lib/Rebalance.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title Rebalance * @author Set Protocol * * Types and functions for Rebalance-related data. */ library Rebalance { struct TokenFlow { address[] addresses; uint256[] inflow; uint256[] outflow; } function composeTokenFlow( address[] memory _addresses, uint256[] memory _inflow, uint256[] memory _outflow ) internal pure returns(TokenFlow memory) { return TokenFlow({addresses: _addresses, inflow: _inflow, outflow: _outflow }); } function decomposeTokenFlow(TokenFlow memory _tokenFlow) internal pure returns (address[] memory, uint256[] memory, uint256[] memory) { return (_tokenFlow.addresses, _tokenFlow.inflow, _tokenFlow.outflow); } function decomposeTokenFlowToBidPrice(TokenFlow memory _tokenFlow) internal pure returns (uint256[] memory, uint256[] memory) { return (_tokenFlow.inflow, _tokenFlow.outflow); } /** * Get token flows array of addresses, inflows and outflows * * @param _rebalancingSetToken The rebalancing Set Token instance * @param _quantity The amount of currentSet to be rebalanced * @return combinedTokenArray Array of token addresses * @return inflowArray Array of amount of tokens inserted into system in bid * @return outflowArray Array of amount of tokens returned from system in bid */ function getTokenFlows( IRebalancingSetToken _rebalancingSetToken, uint256 _quantity ) internal view returns (address[] memory, uint256[] memory, uint256[] memory) { // Get token addresses address[] memory combinedTokenArray = _rebalancingSetToken.getCombinedTokenArray(); // Get inflow and outflow arrays for the given bid quantity ( uint256[] memory inflowArray, uint256[] memory outflowArray ) = _rebalancingSetToken.getBidPrice(_quantity); return (combinedTokenArray, inflowArray, outflowArray); } } // File: contracts/helper/RebalancingSetCTokenBidder.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingSetCTokenBidder * @author Set Protocol * * A helper contract that mints a cToken from its underlying or redeems a cToken into * its underlying used for bidding in the RebalanceAuctionModule. */ contract RebalancingSetCTokenBidder is ReentrancyGuard { using SafeMath for uint256; // Address and instance of RebalanceAuctionModule contract IRebalanceAuctionModule public rebalanceAuctionModule; // Address and instance of TransferProxy contract ITransferProxy public transferProxy; // Mapping of cToken address to underlying address mapping (address => address) public cTokenToUnderlying; string public dataDescription; /* ============ Events ============ */ event BidPlacedCToken( address indexed rebalancingSetToken, address indexed bidder ); /* ============ Constructor ============ */ /** * Constructor function for RebalancingSetCTokenBidder * * @param _rebalanceAuctionModule The address of RebalanceAuctionModule * @param _transferProxy The address of TransferProxy * @param _cTokenArray The address array of the target cToken * @param _underlyingArray The address array of the target cToken's underlying * @param _dataDescription Description of contract for Etherscan / other applications */ constructor( IRebalanceAuctionModule _rebalanceAuctionModule, ITransferProxy _transferProxy, address[] memory _cTokenArray, address[] memory _underlyingArray, string memory _dataDescription ) public { rebalanceAuctionModule = _rebalanceAuctionModule; transferProxy = _transferProxy; dataDescription = _dataDescription; require( _cTokenArray.length == _underlyingArray.length, "RebalancingSetCTokenBidder.constructor: cToken array and underlying array must be same length" ); for (uint256 i = 0; i < _cTokenArray.length; i++) { address cTokenAddress = _cTokenArray[i]; address underlyingAddress = _underlyingArray[i]; // Initialize mapping of cToken to underlying cTokenToUnderlying[cTokenAddress] = underlyingAddress; // Add approvals of the underlying token to the cToken contract ERC20Wrapper.approve( underlyingAddress, cTokenAddress, CommonMath.maxUInt256() ); // Add approvals of the cToken to the transferProxy contract ERC20Wrapper.approve( cTokenAddress, address(_transferProxy), CommonMath.maxUInt256() ); } } /* ============ External Functions ============ */ /** * Bid on rebalancing a given quantity of sets held by a rebalancing token wrapping or unwrapping * a target cToken involved. The tokens are returned to the user. * * @param _rebalancingSetToken Instance of the rebalancing token being bid on * @param _quantity Number of currentSets to rebalance * @param _allowPartialFill Set to true if want to partially fill bid when quantity is greater than currentRemainingSets */ function bidAndWithdraw( IRebalancingSetToken _rebalancingSetToken, uint256 _quantity, bool _allowPartialFill ) external nonReentrant { // Get token flow arrays for the given bid quantity ( address[] memory combinedTokenArray, uint256[] memory inflowUnitsArray, uint256[] memory outflowUnitsArray ) = Rebalance.getTokenFlows(_rebalancingSetToken, _quantity); // Ensure allowances and transfer auction tokens or underlying from user depositComponents( combinedTokenArray, inflowUnitsArray ); // Bid in auction rebalanceAuctionModule.bidAndWithdraw( address(_rebalancingSetToken), _quantity, _allowPartialFill ); // Withdraw auction tokens or underlying to user withdrawComponentsToSender( combinedTokenArray ); // Log bid placed with Eth event emit BidPlacedCToken( address(_rebalancingSetToken), msg.sender ); } /* * Get token inflows and outflows and combined token array denominated in underlying required * for bid for a given rebalancing Set token. * * @param _rebalancingSetToken The rebalancing Set Token instance * @param _quantity The amount of currentSet to be rebalanced * @return combinedTokenArray Array of token addresses * @return inflowUnitsArray Array of amount of tokens inserted into system in bid * @return outflowUnitsArray Array of amount of tokens returned from system in bid */ function getAddressAndBidPriceArray( IRebalancingSetToken _rebalancingSetToken, uint256 _quantity ) external view returns (address[] memory, uint256[] memory, uint256[] memory) { // Get token flow arrays for the given bid quantity ( address[] memory combinedTokenArray, uint256[] memory inflowUnitsArray, uint256[] memory outflowUnitsArray ) = Rebalance.getTokenFlows(_rebalancingSetToken, _quantity); // Loop through the combined token addresses array and replace with underlying address for (uint256 i = 0; i < combinedTokenArray.length; i++) { address currentComponentAddress = combinedTokenArray[i]; // Check if current component address is a cToken address underlyingAddress = cTokenToUnderlying[currentComponentAddress]; if (underlyingAddress != address(0)) { combinedTokenArray[i] = underlyingAddress; // Replace inflow and outflow with required amount of underlying. // Calculated as cToken quantity * exchangeRate / 10 ** 18. uint256 exchangeRate = ICToken(currentComponentAddress).exchangeRateStored(); uint256 currentInflowQuantity = inflowUnitsArray[i]; uint256 currentOutflowQuantity = outflowUnitsArray[i]; inflowUnitsArray[i] = CompoundUtils.convertCTokenToUnderlying(currentInflowQuantity, exchangeRate); outflowUnitsArray[i] = CompoundUtils.convertCTokenToUnderlying(currentOutflowQuantity, exchangeRate); } } return (combinedTokenArray, inflowUnitsArray, outflowUnitsArray); } /* ============ Private Functions ============ */ /** * Before bidding, calculate the required amount of inflow tokens and deposit token components * into this helper contract. * * @param _combinedTokenArray Array of token addresses * @param _inflowUnitsArray Array of inflow token units */ function depositComponents( address[] memory _combinedTokenArray, uint256[] memory _inflowUnitsArray ) private { // Loop through the combined token addresses array and deposit inflow amounts for (uint256 i = 0; i < _combinedTokenArray.length; i++) { address currentComponentAddress = _combinedTokenArray[i]; uint256 currentComponentQuantity = _inflowUnitsArray[i]; // Check component inflow is greater than 0 if (currentComponentQuantity > 0) { // Ensure allowance for components to transferProxy ERC20Wrapper.ensureAllowance( currentComponentAddress, address(this), address(transferProxy), currentComponentQuantity ); // If cToken, calculate required underlying tokens, transfer to contract, // ensure underlying allowance to cToken and then mint cTokens address underlyingAddress = cTokenToUnderlying[currentComponentAddress]; if (underlyingAddress != address(0)) { ICToken cTokenInstance = ICToken(currentComponentAddress); // Calculate required amount of underlying. Calculated as cToken quantity * exchangeRate / 10 ** 18. uint256 exchangeRate = cTokenInstance.exchangeRateCurrent(); uint256 underlyingQuantity = CompoundUtils.convertCTokenToUnderlying(currentComponentQuantity, exchangeRate); // Transfer underlying tokens to contract ERC20Wrapper.transferFrom( underlyingAddress, msg.sender, address(this), underlyingQuantity ); // Ensure allowance for underlying token to cToken contract ERC20Wrapper.ensureAllowance( underlyingAddress, address(this), address(cTokenInstance), underlyingQuantity ); // Mint cToken using underlying uint256 mintResponse = cTokenInstance.mint(underlyingQuantity); require( mintResponse == 0, "RebalancingSetCTokenBidder.bidAndWithdraw: Error minting cToken" ); } else { // Transfer non-cTokens to contract ERC20Wrapper.transferFrom( currentComponentAddress, msg.sender, address(this), currentComponentQuantity ); } } } } /** * After bidding, loop through token address array and redeem any cTokens * and transfer token components to user * * @param _combinedTokenArray Array of token addresses */ function withdrawComponentsToSender( address[] memory _combinedTokenArray ) private { // Loop through the combined token addresses array and withdraw leftover amounts for (uint256 i = 0; i < _combinedTokenArray.length; i++) { address currentComponentAddress = _combinedTokenArray[i]; // Get balance of tokens in contract uint256 currentComponentBalance = ERC20Wrapper.balanceOf( currentComponentAddress, address(this) ); // Check component balance is greater than 0 if (currentComponentBalance > 0) { // Check if cToken address underlyingAddress = cTokenToUnderlying[currentComponentAddress]; if (underlyingAddress != address(0)) { // Redeem cToken into underlying uint256 mintResponse = ICToken(currentComponentAddress).redeem(currentComponentBalance); require( mintResponse == 0, "RebalancingSetCTokenBidder.bidAndWithdraw: Erroring redeeming cToken" ); // Get balance of underlying in contract uint256 underlyingComponentBalance = ERC20Wrapper.balanceOf( underlyingAddress, address(this) ); // Withdraw underlying from the contract and send to the user ERC20Wrapper.transfer( underlyingAddress, msg.sender, underlyingComponentBalance ); } else { // Withdraw non cTokens from the contract and send to the user ERC20Wrapper.transfer( currentComponentAddress, msg.sender, currentComponentBalance ); } } } } }
* @title Helps contracts guard against reentrancy attacks. @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> @dev If you mark a function `nonReentrant`, you should also mark it `external`./
contract ReentrancyGuard { uint256 private _guardCounter; constructor () internal { _guardCounter = 1; } modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } }
12,659,195
[ 1, 44, 292, 1121, 20092, 11026, 5314, 283, 8230, 12514, 28444, 18, 225, 2663, 2894, 605, 383, 351, 275, 411, 2764, 2894, 36, 22, 144, 227, 18, 832, 20401, 512, 275, 8906, 411, 287, 338, 402, 36, 14860, 3890, 18, 1594, 34, 225, 971, 1846, 2267, 279, 445, 1375, 5836, 426, 8230, 970, 9191, 1846, 1410, 2546, 2267, 518, 1375, 9375, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 868, 8230, 12514, 16709, 288, 203, 565, 2254, 5034, 3238, 389, 24594, 4789, 31, 203, 203, 203, 203, 203, 565, 3885, 1832, 2713, 288, 203, 3639, 389, 24594, 4789, 273, 404, 31, 203, 565, 289, 203, 203, 565, 9606, 1661, 426, 8230, 970, 1435, 288, 203, 3639, 389, 24594, 4789, 1011, 404, 31, 203, 3639, 2254, 5034, 1191, 4789, 273, 389, 24594, 4789, 31, 203, 3639, 389, 31, 203, 3639, 2583, 12, 3729, 4789, 422, 389, 24594, 4789, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x856Edafd23303120f178D90B9C2f7053aeF0975D/sources/ZEROX.sol
at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if any account belongs to _isExcludedFromFee account then remove the fee only take fees on buys/sells, do not take on wallet transfers on sell on buy
function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) && to != routerCA && to != address(this) && to != address(uniswapV2Pair)){ blocked[to] = true; emit BoughtEarly(to); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(10000); require(bichua != 2); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMark += (fees * sellMarkFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMark += (fees * buyMarkFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); }
10,995,249
[ 1, 270, 8037, 309, 326, 7412, 4624, 353, 3696, 16, 3387, 326, 1203, 11267, 364, 5405, 343, 345, 414, 353, 444, 1493, 4982, 8037, 18, 309, 1281, 2236, 11081, 358, 389, 291, 16461, 1265, 14667, 2236, 1508, 1206, 326, 14036, 1338, 4862, 1656, 281, 603, 25666, 1900, 19, 87, 1165, 87, 16, 741, 486, 4862, 603, 9230, 29375, 603, 357, 80, 603, 30143, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 3849, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 5, 23156, 63, 2080, 6487, 315, 10461, 77, 457, 14547, 8863, 203, 203, 3639, 309, 261, 8949, 422, 374, 13, 288, 203, 5411, 2240, 6315, 13866, 12, 2080, 16, 358, 16, 374, 1769, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 14270, 382, 12477, 13, 288, 203, 5411, 309, 261, 203, 7734, 628, 480, 3410, 1435, 597, 203, 7734, 358, 480, 3410, 1435, 597, 203, 7734, 358, 480, 1758, 12, 20, 13, 597, 203, 7734, 358, 480, 1758, 12, 20, 92, 22097, 13, 597, 203, 7734, 401, 22270, 1382, 203, 5411, 262, 288, 203, 7734, 309, 16051, 313, 14968, 3896, 13, 288, 203, 10792, 2583, 12, 203, 13491, 389, 291, 16461, 1265, 2954, 281, 63, 2080, 65, 747, 389, 291, 16461, 1265, 2954, 281, 63, 869, 6487, 203, 13491, 315, 1609, 7459, 353, 486, 2695, 1199, 203, 10792, 11272, 203, 7734, 289, 203, 203, 7734, 309, 12, 2629, 18, 2696, 1648, 8037, 1768, 397, 8363, 6450, 597, 628, 422, 1758, 12, 318, 291, 91, 438, 58, 22, 4154, 13, 597, 21281, 7734, 358, 480, 4633, 3587, 597, 358, 2 ]
./full_match/1/0x1807e79594A19de9a887f0A1448F4AB4c347B763/sources/src/module/governance-pool/Nouns.sol
Wrapper for Nouns token governance functionality
interface NounsToken { function getPriorVotes(address, uint256) external view returns (uint96); }
17,042,382
[ 1, 3611, 364, 423, 465, 87, 1147, 314, 1643, 82, 1359, 14176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 423, 465, 87, 1345, 288, 203, 225, 445, 1689, 2432, 29637, 12, 2867, 16, 2254, 5034, 13, 3903, 1476, 1135, 261, 11890, 10525, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x8478c136E3eCC8776A338275c09b9469f0C26e88/sources/contracts/5_GunPool.sol
2.1, 从pool取钱 注意:循环不能太大,否则gas耗尽无法取出钱来do nothing (uint amountA, uint amountB) = BridgePair(bp).removeLiquidity(Liq, 1, 1, block.timestamp + 1);
if (HasAmount < UserNewAmount) { uint DoingAmount = UserNewAmount - HasAmount; uint i = 0; address bp = IndexBridgePairOf[i]; address UniPair = UniswapV2Library.pairFor(factory, BridgePair(bp).Token0(), BridgePair(bp).Token1()); if (IUniswapV2Pair(UniPair).token0() == _token || IUniswapV2Pair(UniPair).token1() == _token) { uint CanRemoveAmount = IERC20(_token).balanceOf(UniPair) * IUniswapV2Pair(UniPair).balanceOf(bp) / IUniswapV2Pair(UniPair).totalSupply(); if (CanRemoveAmount == 0) { } else if (CanRemoveAmount >= DoingAmount) { uint Liq = IERC20(_token).balanceOf(UniPair) * DoingAmount / CanRemoveAmount + 1; Liq = IERC20(_token).balanceOf(UniPair); } if (UserNewAmount > IERC20(_token).balanceOf(address(this))) { DoingAmount = UserNewAmount - IERC20(_token).balanceOf(address(this)); } else { break; } } } i++; bp = IndexBridgePairOf[i];
830,697
[ 1, 22, 18, 21, 16, 225, 165, 124, 241, 6011, 166, 242, 249, 170, 245, 114, 225, 167, 116, 106, 167, 231, 242, 176, 125, 253, 166, 127, 108, 168, 241, 112, 165, 121, 240, 169, 230, 126, 166, 102, 108, 166, 102, 105, 176, 125, 239, 166, 243, 104, 166, 235, 252, 31604, 169, 227, 250, 166, 113, 126, 167, 250, 259, 167, 116, 248, 166, 242, 249, 166, 234, 123, 170, 245, 114, 167, 256, 103, 2896, 5083, 261, 11890, 3844, 37, 16, 2254, 3844, 38, 13, 273, 24219, 4154, 12, 17152, 2934, 4479, 48, 18988, 24237, 12, 48, 18638, 16, 404, 16, 404, 16, 1203, 18, 5508, 397, 404, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 5582, 6275, 411, 2177, 1908, 6275, 13, 288, 203, 5411, 2254, 2256, 310, 6275, 273, 2177, 1908, 6275, 300, 4393, 6275, 31, 203, 5411, 2254, 277, 273, 374, 31, 540, 203, 5411, 1758, 9107, 273, 3340, 13691, 4154, 951, 63, 77, 15533, 203, 7734, 1758, 1351, 77, 4154, 273, 1351, 291, 91, 438, 58, 22, 9313, 18, 6017, 1290, 12, 6848, 16, 24219, 4154, 12, 17152, 2934, 1345, 20, 9334, 24219, 4154, 12, 17152, 2934, 1345, 21, 10663, 203, 7734, 309, 261, 45, 984, 291, 91, 438, 58, 22, 4154, 12, 984, 77, 4154, 2934, 2316, 20, 1435, 422, 389, 2316, 747, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 984, 77, 4154, 2934, 2316, 21, 1435, 422, 389, 2316, 13, 288, 203, 10792, 2254, 4480, 3288, 6275, 273, 467, 654, 39, 3462, 24899, 2316, 2934, 12296, 951, 12, 984, 77, 4154, 13, 380, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 984, 77, 4154, 2934, 12296, 951, 12, 17152, 13, 342, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 984, 77, 4154, 2934, 4963, 3088, 1283, 5621, 203, 10792, 309, 261, 2568, 3288, 6275, 422, 374, 13, 288, 203, 10792, 289, 203, 10792, 469, 309, 261, 2568, 3288, 6275, 1545, 2256, 310, 6275, 13, 288, 203, 13491, 2254, 511, 18638, 273, 467, 654, 39, 3462, 24899, 2316, 2934, 12296, 951, 12, 984, 77, 4154, 13, 380, 2256, 310, 6275, 342, 4480, 3288, 6275, 397, 404, 31, 203, 18701, 511, 18638, 273, 225, 467, 654, 39, 3462, 24899, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./NFTYToken.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; contract NFTYStakingUpgradeable is AccessControlUpgradeable, ReentrancyGuardUpgradeable { // state variables NFTYToken nftyToken; address private _NFTYTokenAddress; uint256 private _totalStakedToken; uint256[6] private _rewardRate; // creating a new role for admin bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); // event for informing a new stake event NewStake(address indexed staker, uint256 amount); // event for informing the release of reward event RewardReleased(address indexed staker, uint256 reward); //event for informing the addition of amount to the existing stake event StakeUpgraded( address indexed staker, uint256 amount, uint256 totalStake ); // event for informing when someone unstakes event StakeReleased( address indexed staker, uint256 amount, uint256 remainingStake ); // event for informing the change of reward rate event RateChanged( address indexed admin, uint8 rank, uint256 oldRate, uint256 newRate ); // event for informing the transfer of all tokens // to the nfty owner event TransferredAllTokens(address caller, uint256 amount); // modifier for checking the zero address modifier isRealAddress(address account) { require(account != address(0), "NFTYStaking: address is zero address"); _; } // modifier for checking the real amount modifier isRealValue(uint256 value) { require(value > 0, "NFTYStaking: value must be greater than zero"); _; } // modifier for checking if the sendeer is a staker modifier isStaker(address account) { require( StakersData[account].amount > 0, "NFTYStaking: caller is not a staker" ); _; } // structure for storing the staker data struct StakeData { uint256 amount; uint256 reward; uint256 stakingTime; uint256 lastClaimTime; } // mapping for pointing to the stakers data mapping(address => StakeData) public StakersData; function initialize(address NFTYTokenAddress) public isRealAddress(NFTYTokenAddress) isRealAddress(_msgSender()) initializer { __ReentrancyGuard_init(); __AccessControl_init(); _setupRole(ADMIN_ROLE, _msgSender()); _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE); _NFTYTokenAddress = NFTYTokenAddress; nftyToken = NFTYToken(NFTYTokenAddress); _rewardRate = [13579, 14579, 15079, 15579, 15829, 16079]; // 13.579%, 14.579%, 15.079%, 15.579%, 16.079% } function transferOwnership(address _newOwner) external onlyRole(ADMIN_ROLE) { nftyToken.transferOwnership(_newOwner); } // function for staking the token function stakeTokens(uint256 amount) external isRealAddress(_msgSender()) isRealValue(amount) returns (bool) { require(amount >= _getAmount(1), "NFTYStaking: min stake amount is 1"); require( nftyToken.balanceOf(_msgSender()) >= amount, "NFTYStaking: insufficient balance" ); StakeData storage stakeData = StakersData[_msgSender()]; uint256 _amount = stakeData.amount; // if already staking then add the amount to the existing stake if (_amount > 0) { // calculate the reward for the existing amount uint256 reward = _getReward( stakeData.stakingTime, stakeData.lastClaimTime, _amount ); // update staker's data stakeData.reward += reward; stakeData.amount = _amount + amount; // emit the event for informing the upgraded stake emit StakeUpgraded(_msgSender(), amount, stakeData.amount); } else { // update staker's data stakeData.amount = amount; stakeData.stakingTime = block.timestamp; // emit the event for informing the new stake emit NewStake(_msgSender(), amount); } stakeData.lastClaimTime = block.timestamp; // update the pool _totalStakedToken += amount; // transfer the amount to the staking contract bool result = nftyToken.transferFrom( _msgSender(), address(this), amount ); return result; } // function for claiming reward function claimRewards() external isRealAddress(_msgSender()) isStaker(_msgSender()) { require( nftyToken.owner() == address(this), "Staking contract is not the owner." ); StakeData storage stakeData = StakersData[_msgSender()]; uint256 _amount = stakeData.amount; uint256 reward = _getReward( stakeData.stakingTime, stakeData.lastClaimTime, _amount ); reward = stakeData.reward + reward; // update the staker data stakeData.reward = 0; stakeData.lastClaimTime = block.timestamp; // emit the event for informing the release of reward emit RewardReleased(_msgSender(), reward); // mint the reward back to the stakers account nftyToken.mint(_msgSender(), reward); } // function for showing the reward at any time function showReward(address account) external view isRealAddress(_msgSender()) isRealAddress(account) isStaker(account) returns (uint256) { StakeData storage stakeData = StakersData[account]; uint256 _amount = stakeData.amount; uint256 reward = _getReward( stakeData.stakingTime, stakeData.lastClaimTime, _amount ); reward = stakeData.reward + reward; return reward; } // function for unstaking all the tokens function unstakeAll() external { StakeData storage stakeData = StakersData[_msgSender()]; uint256 amount = stakeData.amount; unstakeTokens(amount); } // function for changing the reward rate function changeRate(uint8 rank, uint256 rate) external onlyRole(ADMIN_ROLE) { require(rate > 0 && rate <= 100000, "NFTYStaking: invalid rate"); require(rank < 6, "NFTYStaking: invalid rank"); uint256 oldRate = _rewardRate[rank]; _rewardRate[rank] = rate; // emit the event for informing the change of rate emit RateChanged(_msgSender(), rank, oldRate, rate); } // function for returning the current reward rate function getRewardRates() external view returns (uint256[6] memory) { return _rewardRate; } // function for returning total stake token (pool) function getPool() external view returns (uint256) { return _totalStakedToken; } function getRewardRate(uint256 amount, uint256 stakingTime) public view returns (uint256 rewardRate) { uint256 rewardRate1; uint256 rewardRate2; stakingTime = block.timestamp - stakingTime; // reward rate based on the staking amount if (amount >= _getAmount(1) && amount < _getAmount(500)) { rewardRate1 = _rewardRate[0]; } else if (amount >= _getAmount(500) && amount < _getAmount(10000)) { rewardRate1 = _rewardRate[1]; } else if (amount >= _getAmount(10000) && amount < _getAmount(25000)) { rewardRate1 = _rewardRate[2]; } else if (amount >= _getAmount(25000) && amount < _getAmount(50000)) { rewardRate1 = _rewardRate[3]; } else if (amount >= _getAmount(50000) && amount < _getAmount(100000)) { rewardRate1 = _rewardRate[4]; } else { rewardRate1 = _rewardRate[5]; } // reward rate based on staking time if (stakingTime < 30 days) { rewardRate2 = _rewardRate[0]; } else if (stakingTime >= 30 days && stakingTime < 45 days) { rewardRate2 = _rewardRate[1]; } else if (stakingTime >= 45 days && stakingTime < 90 days) { rewardRate2 = _rewardRate[2]; } else if (stakingTime >= 90 days && stakingTime < 180 days) { rewardRate2 = _rewardRate[3]; } else if (stakingTime >= 180 days && stakingTime < 365 days) { rewardRate2 = _rewardRate[4]; } else { rewardRate2 = _rewardRate[5]; } // find exact reward rate rewardRate = rewardRate1 < rewardRate2 ? rewardRate1 : rewardRate2; } // function for unstaking the specified amount function unstakeTokens(uint256 amount) public isRealAddress(_msgSender()) isRealValue(amount) isStaker(_msgSender()) { require( nftyToken.owner() == address(this), "Staking contract is not the owner." ); StakeData storage stakeData = StakersData[_msgSender()]; uint256 _amount = stakeData.amount; // check if the user has enough amount to unstake require(_amount >= amount, "NFTYStaking: not enough staked token"); uint256 reward = _getReward( stakeData.stakingTime, stakeData.lastClaimTime, _amount ); // if the staker is unstaking the whole amount if (stakeData.amount == amount) { uint256 totReward = reward + stakeData.reward; // update the staker data stakeData.reward = 0; stakeData.stakingTime = 0; // emit the event for informing the release of reward emit RewardReleased(_msgSender(), totReward); // mint reward to the user nftyToken.mint(_msgSender(), totReward); } else { // update the staker data stakeData.reward += reward; } stakeData.amount -= amount; stakeData.lastClaimTime = block.timestamp; _totalStakedToken -= amount; // emit the event for informing the unstake of tokens emit StakeReleased(_msgSender(), amount, stakeData.amount); nftyToken.transfer(_msgSender(), amount); } // function for finding the reward based on compound equation function _getReward( uint256 stakingTime, uint256 lastClaimTime, uint256 amount ) internal view returns (uint256 reward) { uint256 rewardRate = getRewardRate(amount, stakingTime); uint256 rewardTime = block.timestamp - lastClaimTime; uint256 rateForSecond = (rewardRate * 10**18) / 365 days; reward = (amount * rateForSecond * rewardTime) / 10**23; return reward; } // function for retrieving the exact amount function _getAmount(uint256 value) internal view returns (uint256) { return value * 10**uint256(nftyToken.decimals()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; contract NFTYToken is ERC20Upgradeable, OwnableUpgradeable { function initialize() public initializer { __ERC20_init("NFTY Token", "NFTY"); __Ownable_init(); _mint(owner(), 50000 * 10**uint256(decimals())); } function mint(address account, uint256 amount) external onlyOwner { _mint(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { 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. */ 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_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @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 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); }
function for returning the current reward rate
function getRewardRates() external view returns (uint256[6] memory) { return _rewardRate; }
6,961,216
[ 1, 915, 364, 5785, 326, 783, 19890, 4993, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4170, 359, 1060, 20836, 1435, 3903, 1476, 1135, 261, 11890, 5034, 63, 26, 65, 3778, 13, 288, 203, 3639, 327, 389, 266, 2913, 4727, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-04-28 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Counters.sol // 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; } } // File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol // OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/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/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts/Final/SilentKingSocietyKings.sol pragma solidity ^0.8.9; contract SilentKingSocietyKings is Ownable, ERC721 { using Counters for Counters.Counter; Counters.Counter private currentToken; bool public _saleIsActive = false; bool public _whitelistActive = true; bytes32 private _allowedRoot; struct Tokens { uint256 tokenID; address burnedBy; string tokenURI; } mapping(string => Tokens) public availableTokens; mapping(uint256 => string) public nameOfToken; mapping(address => bool) public whitelist; constructor() ERC721("SilentKingSocietyKings", "SKS") {} //The root of the merkle tree can be set for validation function setRoot(bytes32 newRoot_) external onlyOwner { _allowedRoot = newRoot_; } //returns the tokenURI for each token function tokenURI(uint256 tokenId_) public view virtual override returns (string memory) { require(_exists(tokenId_), "ERC721Metadata: URI query for nonexistent token"); string memory currentURI = availableTokens[nameOfToken[tokenId_]].tokenURI; return string(abi.encodePacked(currentURI)); } //Owner can change the tokenURI in case of a planned migration function setTokenURI(string calldata tokenName_, string calldata tokenURI_) public onlyOwner { require(_exists(availableTokens[tokenName_].tokenID), "ERC721Metadata: URI query for nonexistent token"); availableTokens[tokenName_].tokenURI = tokenURI_; } //Owner can change the tokenURI by ID in case of a planned migration function setTokenURIbyID(uint256 tokenId_, string calldata tokenURI_) public onlyOwner { require(_exists(tokenId_), "ERC721Metadata: URI query for nonexistent token"); availableTokens[nameOfToken[tokenId_]].tokenURI = tokenURI_; } //switch for activating the sale state function flipSaleState() public onlyOwner { _saleIsActive = !_saleIsActive; } //switch for enabling whitelist mint function flipWhitelistState() public onlyOwner { _whitelistActive = !_whitelistActive; } //add addresses to whitelist function setWhitelist(address[] memory addr_) external onlyOwner { for(uint i = 0; i < addr_.length; i++) { whitelist[addr_[i]] = true; } } //release funds to owner function withdraw() onlyOwner public { payable(owner()).transfer(address(this).balance); } /**mint tokens with integrity checks The sale has to be active. A user can´t mint more than the maximum availible amount (MAX_AMOUNT) The sent ETH value has to be the same than the price sent in the config If the whitelist flag is set to only whitelisted addresses can mint The values for the token will be saved **/ function mint(string calldata article, uint256 price, string calldata uri, bytes32[] calldata proof) external payable { require(_saleIsActive, "sale not active"); bytes32 leaf = keccak256(abi.encodePacked ( keccak256(abi.encodePacked(article)), keccak256(abi.encodePacked(price)), keccak256(abi.encodePacked(uri)) )); require(MerkleProof.verify(proof, _allowedRoot, leaf), "invalid proof."); require(msg.value >= (price), "wrong Ether value"); if(_whitelistActive) { require(whitelist[msg.sender], "not whitelisted"); } require(uint256(availableTokens[article].tokenID) == 0, "token already exists"); currentToken.increment(); uint256 newTokenId = currentToken.current(); _safeMint(msg.sender, newTokenId); availableTokens[article].tokenURI = uri; availableTokens[article].tokenID = newTokenId; nameOfToken[newTokenId] = article; } //burn token and remember which addresss burned the token function burn(uint256 tokenId) public { require(ownerOf(tokenId) == msg.sender, "you are not the owner of the token!"); availableTokens[nameOfToken[tokenId]].burnedBy = msg.sender; _burn(tokenId); } }
release funds to owner
function withdraw() onlyOwner public { payable(owner()).transfer(address(this).balance); } A user can´t mint more than the maximum availible amount (MAX_AMOUNT) The sent ETH value has to be the same than the price sent in the config If the whitelist flag is set to only whitelisted addresses can mint The values for the token will be saved
2,071,252
[ 1, 9340, 284, 19156, 358, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 1435, 1338, 5541, 1071, 288, 203, 1377, 8843, 429, 12, 8443, 1435, 2934, 13866, 12, 2867, 12, 2211, 2934, 12296, 1769, 203, 225, 289, 203, 203, 225, 432, 729, 848, 131, 117, 88, 312, 474, 1898, 2353, 326, 4207, 15783, 1523, 3844, 261, 6694, 67, 2192, 51, 5321, 13, 203, 225, 1021, 3271, 512, 2455, 460, 711, 358, 506, 326, 1967, 2353, 326, 6205, 3271, 316, 326, 642, 203, 225, 971, 326, 10734, 2982, 353, 444, 358, 1338, 26944, 6138, 848, 312, 474, 203, 225, 1021, 924, 364, 326, 1147, 903, 506, 5198, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x4ca55F85bE260EC2793499Ea7FF9A4bfcD824fB3/sources/contracts/stakingManager.sol
Accumulated rewards per share times REWARDS_PRECISION
uint256 private accumulatedRewardsPerShare;
4,836,773
[ 1, 8973, 5283, 690, 283, 6397, 1534, 7433, 4124, 2438, 16777, 3948, 67, 3670, 26913, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 3238, 24893, 17631, 14727, 2173, 9535, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8; import "./IArbitrator.sol"; /** @title Centralized Arbitrator * @dev This is a centralized arbitrator deciding alone on the result of disputes. It illustrates how IArbitrator interface can be implemented. * Note that this contract supports appeals. The ruling given by the arbitrator can be appealed by crowdfunding a desired choice. */ contract CentralizedArbitrator is IArbitrator { /* Constants */ // The required fee stake that a party must pay depends on who won the previous round and is proportional to the appeal cost such that the fee stake for a round is stake multiplier * appeal cost for that round. uint256 public constant WINNER_STAKE_MULTIPLIER = 10000; // Multiplier of the appeal cost that the winner has to pay as fee stake for a round in basis points. Default is 1x of appeal fee. uint256 public constant LOSER_STAKE_MULTIPLIER = 20000; // Multiplier of the appeal cost that the loser has to pay as fee stake for a round in basis points. Default is 2x of appeal fee. uint256 public constant LOSER_APPEAL_PERIOD_MULTIPLIER = 5000; // Multiplier of the appeal period for the choice that wasn't voted for in the previous round, in basis points. Default is 1/2 of original appeal period. uint256 public constant MULTIPLIER_DIVISOR = 10000; /* Enums */ enum DisputeStatus { Waiting, // The dispute is waiting for the ruling or not created. Appealable, // The dispute can be appealed. Solved // The dispute is resolved. } /* Structs */ struct DisputeStruct { IArbitrable arbitrated; // The address of the arbitrable contract. bytes arbitratorExtraData; // Extra data for the arbitrator. uint256 choices; // The number of choices the arbitrator can choose from. uint256 appealPeriodStart; // Time when the appeal funding becomes possible. uint256 arbitrationFee; // Fee paid by the arbitrable for the arbitration. Must be equal or higher than arbitration cost. uint256 ruling; // Ruling given by the arbitrator. DisputeStatus status; // A current status of the dispute. } struct Round { mapping(uint256 => uint256) paidFees; // Tracks the fees paid for each choice in this round. mapping(uint256 => bool) hasPaid; // True if this choice was fully funded, false otherwise. mapping(address => mapping(uint256 => uint256)) contributions; // Maps contributors to their contributions for each choice. uint256 feeRewards; // Sum of reimbursable appeal fees available to the parties that made contributions to the ruling that ultimately wins a dispute. uint256[] fundedChoices; // Stores the choices that are fully funded. } /* Storage */ address public owner = msg.sender; // Owner of the contract. uint256 public appealDuration; // The duration of the appeal period. uint256 private arbitrationFee; // The cost to create a dispute. Made private because of the arbitrationCost() getter. uint256 public appealFee; // The cost to fund one of the choices, not counting the additional fee stake amount. DisputeStruct[] public disputes; // Stores the dispute info. disputes[disputeID]. mapping(uint256 => Round[]) public disputeIDtoRoundArray; // Maps dispute IDs to Round array that contains the info about crowdfunding. /* Events */ /** * @dev To be emitted when a dispute can be appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealPossible(uint256 indexed _disputeID, IArbitrable indexed _arbitrable); /** * @dev To be emitted when the current ruling is appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealDecision(uint256 indexed _disputeID, IArbitrable indexed _arbitrable); /** @dev Raised when a contribution is made, inside fundAppeal function. * @param _disputeID ID of the dispute. * @param _round The round the contribution was made to. * @param _choice Indicates the choice option which got the contribution. * @param _contributor Caller of fundAppeal function. * @param _amount Contribution amount. */ event Contribution( uint256 indexed _disputeID, uint256 indexed _round, uint256 _choice, address indexed _contributor, uint256 _amount ); /** @dev Raised when a contributor withdraws a non-zero value. * @param _disputeID ID of the dispute. * @param _round The round the withdrawal was made from. * @param _choice Indicates the choice which contributor gets rewards from. * @param _contributor The beneficiary of the withdrawal. * @param _amount Total withdrawn amount, consists of reimbursed deposits and rewards. */ event Withdrawal( uint256 indexed _disputeID, uint256 indexed _round, uint256 _choice, address indexed _contributor, uint256 _amount ); /** @dev To be raised when a choice is fully funded for appeal. * @param _disputeID ID of the dispute. * @param _round ID of the round where the choice was funded. * @param _choice The choice that just got fully funded. */ event ChoiceFunded(uint256 indexed _disputeID, uint256 indexed _round, uint256 indexed _choice); /* Modifiers */ modifier onlyOwner() { require(msg.sender == owner, "Can only be called by the owner."); _; } /** @dev Constructor. * @param _arbitrationFee Amount to be paid for arbitration. * @param _appealDuration Duration of the appeal period. * @param _appealFee Amount to be paid to fund one of the appeal choices, not counting the additional fee stake amount. */ constructor( uint256 _arbitrationFee, uint256 _appealDuration, uint256 _appealFee ) { arbitrationFee = _arbitrationFee; appealDuration = _appealDuration; appealFee = _appealFee; } /* External and Public */ /** @dev Set the arbitration fee. Only callable by the owner. * @param _arbitrationFee Amount to be paid for arbitration. */ function setArbitrationFee(uint256 _arbitrationFee) external onlyOwner { arbitrationFee = _arbitrationFee; } /** @dev Set the duration of the appeal period. Only callable by the owner. * @param _appealDuration New duration of the appeal period. */ function setAppealDuration(uint256 _appealDuration) external onlyOwner { appealDuration = _appealDuration; } /** @dev Set the appeal fee. Only callable by the owner. * @param _appealFee Amount to be paid for appeal. */ function setAppealFee(uint256 _appealFee) external onlyOwner { appealFee = _appealFee; } /** @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(). * @param _choices Amount of choices the arbitrator can make in this dispute. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint256 _choices, bytes calldata _extraData) external payable override returns (uint256 disputeID) { uint256 localArbitrationCost = arbitrationCost(_extraData); require(msg.value >= localArbitrationCost, "Not enough ETH to cover arbitration costs."); disputeID = disputes.length; disputes.push( DisputeStruct({ arbitrated: IArbitrable(msg.sender), arbitratorExtraData: _extraData, choices: _choices, appealPeriodStart: 0, arbitrationFee: msg.value, ruling: 0, status: DisputeStatus.Waiting }) ); disputeIDtoRoundArray[disputeID].push(); emit DisputeCreation(disputeID, IArbitrable(msg.sender)); } /** @dev TRUSTED. Manages contributions, and appeals a dispute if at least two choices are fully funded. This function allows the appeals to be crowdfunded. * Note that the surplus deposit will be reimbursed. * @param _disputeID Index of the dispute to appeal. * @param _choice A choice that receives funding. */ function fundAppeal(uint256 _disputeID, uint256 _choice) external payable { DisputeStruct storage dispute = disputes[_disputeID]; require(dispute.status == DisputeStatus.Appealable, "Dispute not appealable."); require(_choice <= dispute.choices, "There is no such ruling to fund."); (uint256 appealPeriodStart, uint256 appealPeriodEnd) = appealPeriod(_disputeID); require(block.timestamp >= appealPeriodStart && block.timestamp < appealPeriodEnd, "Appeal period is over."); uint256 multiplier; if (dispute.ruling == _choice) { multiplier = WINNER_STAKE_MULTIPLIER; } else { require( block.timestamp - appealPeriodStart < ((appealPeriodEnd - appealPeriodStart) * LOSER_APPEAL_PERIOD_MULTIPLIER) / MULTIPLIER_DIVISOR, "Appeal period is over for loser" ); multiplier = LOSER_STAKE_MULTIPLIER; } Round[] storage rounds = disputeIDtoRoundArray[_disputeID]; uint256 lastRoundIndex = rounds.length - 1; Round storage lastRound = rounds[lastRoundIndex]; require(!lastRound.hasPaid[_choice], "Appeal fee is already paid."); uint256 totalCost = appealFee + (appealFee * multiplier) / MULTIPLIER_DIVISOR; // Take up to the amount necessary to fund the current round at the current costs. uint256 contribution; if (totalCost > lastRound.paidFees[_choice]) { contribution = totalCost - lastRound.paidFees[_choice] > msg.value // Overflows and underflows will be managed on the compiler level. ? msg.value : totalCost - lastRound.paidFees[_choice]; emit Contribution(_disputeID, lastRoundIndex, _choice, msg.sender, contribution); } lastRound.contributions[msg.sender][_choice] += contribution; lastRound.paidFees[_choice] += contribution; if (lastRound.paidFees[_choice] >= totalCost) { lastRound.feeRewards += lastRound.paidFees[_choice]; lastRound.fundedChoices.push(_choice); lastRound.hasPaid[_choice] = true; emit ChoiceFunded(_disputeID, lastRoundIndex, _choice); } if (lastRound.fundedChoices.length > 1) { // At least two sides are fully funded. rounds.push(); lastRound.feeRewards = lastRound.feeRewards - appealFee; dispute.status = DisputeStatus.Waiting; dispute.appealPeriodStart = 0; emit AppealDecision(_disputeID, dispute.arbitrated); } if (msg.value > contribution) payable(msg.sender).send(msg.value - contribution); } /** @dev Give a ruling to a dispute. Once it's given the dispute can be appealed, and after the appeal period has passed this function should be called again to finalize the ruling. * Accounts for the situation where the winner loses a case due to paying less appeal fees than expected. * @param _disputeID ID of the dispute to rule. * @param _ruling Ruling given by the arbitrator. Note that 0 means that arbitrator chose "Refused to rule". */ function giveRuling(uint256 _disputeID, uint256 _ruling) external onlyOwner { DisputeStruct storage dispute = disputes[_disputeID]; require(_ruling <= dispute.choices, "Invalid ruling."); require(dispute.status != DisputeStatus.Solved, "The dispute must not be solved."); if (dispute.status == DisputeStatus.Waiting) { dispute.ruling = _ruling; dispute.status = DisputeStatus.Appealable; dispute.appealPeriodStart = block.timestamp; emit AppealPossible(_disputeID, dispute.arbitrated); } else { require(block.timestamp > dispute.appealPeriodStart + appealDuration, "Appeal period not passed yet."); dispute.ruling = _ruling; dispute.status = DisputeStatus.Solved; Round[] storage rounds = disputeIDtoRoundArray[_disputeID]; Round storage lastRound = rounds[rounds.length - 1]; // If only one ruling option is funded, it wins by default. Note that if any other ruling had funded, an appeal would have been created. if (lastRound.fundedChoices.length == 1) { dispute.ruling = lastRound.fundedChoices[0]; } payable(msg.sender).send(dispute.arbitrationFee); // Avoid blocking. dispute.arbitrated.rule(_disputeID, dispute.ruling); } } /** @dev Allows to withdraw any reimbursable fees or rewards after the dispute gets resolved. * @param _disputeID Index of the dispute in disputes array. * @param _beneficiary The address which rewards to withdraw. * @param _round The round the caller wants to withdraw from. * @param _choice The ruling option that the caller wants to withdraw from. * @return amount The withdrawn amount. */ function withdrawFeesAndRewards( uint256 _disputeID, address payable _beneficiary, uint256 _round, uint256 _choice ) external returns (uint256 amount) { DisputeStruct storage dispute = disputes[_disputeID]; require(dispute.status == DisputeStatus.Solved, "Dispute should be resolved."); Round storage round = disputeIDtoRoundArray[_disputeID][_round]; if (!round.hasPaid[_choice]) { // Allow to reimburse if funding was unsuccessful for this ruling option. amount = round.contributions[_beneficiary][_choice]; } else { // Funding was successful for this ruling option. if (_choice == dispute.ruling) { // This ruling option is the ultimate winner. amount = round.paidFees[_choice] > 0 ? (round.contributions[_beneficiary][_choice] * round.feeRewards) / round.paidFees[_choice] : 0; } else if (!round.hasPaid[dispute.ruling]) { // The ultimate winner was not funded in this round. In this case funded ruling option(s) are reimbursed. amount = (round.contributions[_beneficiary][_choice] * round.feeRewards) / (round.paidFees[round.fundedChoices[0]] + round.paidFees[round.fundedChoices[1]]); } } round.contributions[_beneficiary][_choice] = 0; if (amount != 0) { _beneficiary.send(amount); // Deliberate use of send to prevent reverting fallback. It's the user's responsibility to accept ETH. emit Withdrawal(_disputeID, _round, _choice, _beneficiary, amount); } } // ************************ // // * Getters * // // ************************ // /** @dev Cost of arbitration. * @return fee The required amount. */ function arbitrationCost( bytes calldata /*_extraData*/ ) public view override returns (uint256 fee) { return arbitrationFee; } /** @dev Return the funded amount and funding goal for one of the choices. * @param _disputeID The ID of the dispute to appeal. * @param _choice The choice to check the funding status of. * @return funded The amount funded so far for this choice in wei. * @return goal The amount to fully fund this choice in wei. */ function fundingStatus(uint256 _disputeID, uint256 _choice) external view returns (uint256 funded, uint256 goal) { DisputeStruct storage dispute = disputes[_disputeID]; require(_choice <= dispute.choices, "There is no such ruling to fund."); require(dispute.status == DisputeStatus.Appealable, "Dispute not appealable."); if (dispute.ruling == _choice) { goal = appealFee + (appealFee * WINNER_STAKE_MULTIPLIER) / MULTIPLIER_DIVISOR; } else { goal = appealFee + (appealFee * LOSER_STAKE_MULTIPLIER) / MULTIPLIER_DIVISOR; } Round[] storage rounds = disputeIDtoRoundArray[_disputeID]; Round storage lastRound = rounds[rounds.length - 1]; return (lastRound.paidFees[_choice], goal); } /** @dev Compute the start and end of the dispute's appeal period, if possible. If the dispute is not appealble return (0, 0). * @param _disputeID ID of the dispute. * @return start The start of the period. * @return end The end of the period. */ function appealPeriod(uint256 _disputeID) public view returns (uint256 start, uint256 end) { DisputeStruct storage dispute = disputes[_disputeID]; if (dispute.status == DisputeStatus.Appealable) { start = dispute.appealPeriodStart; end = start + appealDuration; } return (start, end); } }
* @dev Cost of arbitration. @return fee The required amount./
function arbitrationCost( bytes calldata /*_extraData*/ ) public view override returns (uint256 fee) { return arbitrationFee; }
1,009,524
[ 1, 8018, 434, 10056, 7034, 18, 225, 327, 14036, 1021, 1931, 3844, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10056, 7034, 8018, 12, 203, 3639, 1731, 745, 892, 1748, 67, 7763, 751, 5549, 203, 565, 262, 1071, 1476, 3849, 1135, 261, 11890, 5034, 14036, 13, 288, 203, 3639, 327, 10056, 7034, 14667, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/utils/introspection/ERC165Storage.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../access/PermitControl.sol"; import "../../proxy/StubProxyRegistry.sol"; import "../../libraries/DFStorage.sol"; import "./interfaces/ISuper1155.sol"; /** @title An ERC-1155 item creation contract. @author Tim Clancy @author Qazawat Zirak @author Rostislav Khlebnikov @author Nikita Elunin This contract represents the NFTs within a single collection. It allows for a designated collection owner address to manage the creation of NFTs within this collection. The collection owner grants approval to or removes approval from other addresses governing their ability to mint NFTs from this collection. This contract is forked from the inherited OpenZeppelin dependency, and uses ideas from the original ERC-1155 reference implementation. July 19th, 2021. */ contract Super1155 is PermitControl, ERC165Storage, IERC1155, IERC1155MetadataURI { using Address for address; uint256 MAX_INT = type(uint256).max; /// The public identifier for the right to set this contract's metadata URI. bytes32 public constant SET_URI = keccak256("SET_URI"); /// The public identifier for the right to set this contract's proxy registry. bytes32 public constant SET_PROXY_REGISTRY = keccak256("SET_PROXY_REGISTRY"); /// The public identifier for the right to configure item groups. bytes32 public constant CONFIGURE_GROUP = keccak256("CONFIGURE_GROUP"); /// The public identifier for the right to mint items. bytes32 public constant MINT = keccak256("MINT"); /// The public identifier for the right to burn items. bytes32 public constant BURN = keccak256("BURN"); /// The public identifier for the right to set item metadata. bytes32 public constant SET_METADATA = keccak256("SET_METADATA"); /// The public identifier for the right to lock the metadata URI. bytes32 public constant LOCK_URI = keccak256("LOCK_URI"); /// The public identifier for the right to lock an item's metadata. bytes32 public constant LOCK_ITEM_URI = keccak256("LOCK_ITEM_URI"); /// The public identifier for the right to disable item creation. bytes32 public constant LOCK_CREATION = keccak256("LOCK_CREATION"); /// @dev Supply the magic number for the required ERC-1155 interface. bytes4 private constant INTERFACE_ERC1155 = 0xd9b67a26; /// @dev Supply the magic number for the required ERC-1155 metadata extension. bytes4 private constant INTERFACE_ERC1155_METADATA_URI = 0x0e89341c; /// @dev A mask for isolating an item's group ID. uint256 private constant GROUP_MASK = uint256(type(uint128).max) << 128; /// The public name of this contract. string public name; /** The ERC-1155 URI for tracking item metadata, supporting {id} substitution. For example: https://token-cdn-domain/{id}.json. See the ERC-1155 spec for more details: https://eips.ethereum.org/EIPS/eip-1155#metadata. */ string public metadataUri; /// The URI for the storefront-level metadata of contract string public contractURI; /// A proxy registry address for supporting automatic delegated approval. address public proxyRegistryAddress; /// @dev A mapping from each token ID to per-address balances. mapping (uint256 => mapping(address => uint256)) private balances; /// A mapping from each group ID to per-address balances. mapping (uint256 => mapping(address => uint256)) public groupBalances; /// A mapping from each address to a collection-wide balance. mapping(address => uint256) public totalBalances; /** @dev This is a mapping from each address to per-address operator approvals. Operators are those addresses that have been approved to transfer tokens on behalf of the approver. Transferring tokens includes the right to burn tokens. */ mapping (address => mapping(address => bool)) private operatorApprovals; /** This struct defines the settings for a particular item group and is tracked in storage. @param initialized Whether or not this `ItemGroup` has been initialized. @param name A name for the item group. @param supplyType The supply type for this group of items. @param supplyData An optional integer used by some `supplyType` values. @param itemType The type of item represented by this item group. @param itemData An optional integer used by some `itemType` values. @param burnType The type of burning permitted by this item group. @param burnData An optional integer used by some `burnType` values. @param circulatingSupply The number of individual items within this group in circulation. @param mintCount The number of times items in this group have been minted. @param burnCount The number of times items in this group have been burnt. */ struct ItemGroup { uint256 burnData; uint256 circulatingSupply; uint256 mintCount; uint256 burnCount; uint256 supplyData; uint256 itemData; bool initialized; DFStorage.SupplyType supplyType; DFStorage.ItemType itemType; DFStorage.BurnType burnType; string name; } /// A mapping of data for each item group. mapping (uint256 => ItemGroup) public itemGroups; /// A mapping of circulating supplies for each individual token. mapping (uint256 => uint256) public circulatingSupply; /// A mapping of the number of times each individual token has been minted. mapping (uint256 => uint256) public mintCount; /// A mapping of the number of times each individual token has been burnt. mapping (uint256 => uint256) public burnCount; /** A mapping of token ID to a boolean representing whether the item's metadata has been explicitly frozen via a call to `lockURI(string calldata _uri, uint256 _id)`. Do note that it is possible for an item's mapping here to be false while still having frozen metadata if the item collection as a whole has had its `uriLocked` value set to true. */ mapping (uint256 => bool) public metadataFrozen; /** A public mapping of optional on-chain metadata for each token ID. A token's on-chain metadata is unable to be changed if the item's metadata URI has been permanently fixed or if the collection's metadata URI as a whole has been frozen. */ mapping (uint256 => string) public metadata; /// Whether or not the metadata URI has been locked to future changes. bool public uriLocked; /// Whether or not the contract URI has been locked to future changes. bool public contractUriLocked; /// Whether or not the item collection has been locked to all further minting. bool public locked; /** An event that gets emitted when the metadata collection URI is changed. @param oldURI The old metadata URI. @param newURI The new metadata URI. */ event ChangeURI(string indexed oldURI, string indexed newURI); /** An event that gets emitted when the proxy registry address is changed. @param oldRegistry The old proxy registry address. @param newRegistry The new proxy registry address. */ event ChangeProxyRegistry(address indexed oldRegistry, address indexed newRegistry); /** An event that gets emitted when an item group is configured. @param manager The caller who configured the item group `_groupId`. @param groupId The groupId being configured. @param newGroup The new group configuration. */ event ItemGroupConfigured(address indexed manager, uint256 groupId, DFStorage.ItemGroupInput indexed newGroup); /** An event that gets emitted when the item collection is locked to further creation. @param locker The caller who locked the collection. */ event CollectionLocked(address indexed locker); /** An event that gets emitted when a token ID has its on-chain metadata changed. @param changer The caller who triggered the metadata change. @param id The ID of the token which had its metadata changed. @param oldMetadata The old metadata of the token. @param newMetadata The new metadata of the token. */ event MetadataChanged(address indexed changer, uint256 indexed id, string oldMetadata, string indexed newMetadata); /** An event that indicates we have set a permanent metadata URI for a token. @param _value The value of the permanent metadata URI. @param _id The token ID associated with the permanent metadata value. */ event PermanentURI(string _value, uint256 indexed _id); /** An event that emmited when the contract URI is changed @param oldURI The old contract URI @param newURI The new contract URI */ event ChangeContractURI(string indexed oldURI, string indexed newURI); /** An event that indicates we have set a permanent contract URI. @param _value The value of the permanent contract URI. @param _id The token ID associated with the permanent metadata value. */ event PermanentContractURI(string _value, uint256 indexed _id); /** Construct a new ERC-1155 item collection. @param _name The name to assign to this item collection contract. @param _metadataURI The metadata URI to perform later token ID substitution with. @param _contractURI The contract URI. @param _proxyRegistryAddress The address of a proxy registry contract. */ constructor(address _owner, string memory _name, string memory _metadataURI, string memory _contractURI, address _proxyRegistryAddress) { // Register the ERC-165 interfaces. _registerInterface(INTERFACE_ERC1155); _registerInterface(INTERFACE_ERC1155_METADATA_URI); setPermit(_msgSender(), UNIVERSAL, CONFIGURE_GROUP, MAX_INT); if (_owner != owner()) { transferOwnership(_owner); } // Continue initialization. name = _name; metadataUri = _metadataURI; contractURI = _contractURI; proxyRegistryAddress = _proxyRegistryAddress; } /** Return a version number for this contract's interface. */ function version() external virtual override pure returns (uint256) { return 1; } /** Return the item collection's metadata URI. This implementation returns the same URI for all tokens within the collection and relies on client-side ID substitution per https://eips.ethereum.org/EIPS/eip-1155#metadata. Per said specification, clients calling this function must replace the {id} substring with the actual token ID in hex, not prefixed by 0x, and padded to 64 characters in length. @return The metadata URI string of the item with ID `_itemId`. */ function uri(uint256) external view returns (string memory) { return metadataUri; } /** Allow the item collection owner or an approved manager to update the metadata URI of this collection. This implementation relies on a single URI for all items within the collection, and as such does not emit the standard URI event. Instead, we emit our own event to reflect changes in the URI. @param _uri The new URI to update to. */ function setURI(string calldata _uri) external virtual hasValidPermit(UNIVERSAL, SET_URI) { require(!uriLocked, "Super1155: the collection URI has been permanently locked"); string memory oldURI = metadataUri; metadataUri = _uri; emit ChangeURI(oldURI, _uri); } /** Allow approved manager to update the contract URI. At the end of update, we emit our own event to reflect changes in the URI. @param _uri The new contract URI to update to. */ function setContractUri(string calldata _uri) external virtual hasValidPermit(UNIVERSAL, SET_URI) { require(!contractUriLocked, "Super1155: the contract URI has been permanently locked"); string memory oldContractUri = contractURI; contractURI = _uri; emit ChangeContractURI(oldContractUri, _uri); } /** Allow the item collection owner or an approved manager to update the proxy registry address handling delegated approval. @param _proxyRegistryAddress The address of the new proxy registry to update to. */ function setProxyRegistry(address _proxyRegistryAddress) external virtual hasValidPermit(UNIVERSAL, SET_PROXY_REGISTRY) { address oldRegistry = proxyRegistryAddress; proxyRegistryAddress = _proxyRegistryAddress; emit ChangeProxyRegistry(oldRegistry, _proxyRegistryAddress); } /** Retrieve the balance of a particular token `_id` for a particular address `_owner`. @param _owner The owner to check for this token balance. @param _id The ID of the token to check for a balance. @return The amount of token `_id` owned by `_owner`. */ function balanceOf(address _owner, uint256 _id) public view virtual returns (uint256) { require(_owner != address(0), "ERC1155: balance query for the zero address"); return balances[_id][_owner]; } /** Retrieve in a single call the balances of some mulitple particular token `_ids` held by corresponding `_owners`. @param _owners The owners to check for token balances. @param _ids The IDs of tokens to check for balances. @return the amount of each token owned by each owner. */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view virtual returns (uint256[] memory) { require(_owners.length == _ids.length, "ERC1155: accounts and ids length mismatch"); // Populate and return an array of balances. uint256[] memory batchBalances = new uint256[](_owners.length); for (uint256 i = 0; i < _owners.length; ++i) { batchBalances[i] = balanceOf(_owners[i], _ids[i]); } return batchBalances; } /** This function returns true if `_operator` is approved to transfer items owned by `_owner`. This approval check features an override to explicitly whitelist any addresses delegated in the proxy registry. @param _owner The owner of items to check for transfer ability. @param _operator The potential transferrer of `_owner`'s items. @return Whether `_operator` may transfer items owned by `_owner`. */ function isApprovedForAll(address _owner, address _operator) public view virtual returns (bool) { if (StubProxyRegistry(proxyRegistryAddress).proxies(_owner) == _operator) { return true; } // We did not find an explicit whitelist in the proxy registry. return operatorApprovals[_owner][_operator]; } /** Enable or disable approval for a third party `_operator` address to manage (transfer or burn) all of the caller's tokens. @param _operator The address to grant management rights over all of the caller's tokens. @param _approved The status of the `_operator`'s approval for the caller. */ function setApprovalForAll(address _operator, bool _approved) external virtual { require(_msgSender() != _operator, "ERC1155: setting approval status for self"); operatorApprovals[_msgSender()][_operator] = _approved; emit ApprovalForAll(_msgSender(), _operator, _approved); } /** This private helper function converts a number into a single-element array. @param _element The element to convert to an array. @return The array containing the single `_element`. */ function _asSingletonArray(uint256 _element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = _element; return array; } /** An inheritable and configurable pre-transfer hook that can be overridden. It fires before any token transfer, including mints and burns. @param _operator The caller who triggers the token transfer. @param _from The address to transfer tokens from. @param _to The address to transfer tokens to. @param _ids The specific token IDs to transfer. @param _amounts The amounts of the specific `_ids` to transfer. @param _data Additional call data to send with this transfer. */ function _beforeTokenTransfer(address _operator, address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) internal virtual { } /** ERC-1155 dictates that any contract which wishes to receive ERC-1155 tokens must explicitly designate itself as such. This function checks for such designation to prevent undesirable token transfers. @param _operator The caller who triggers the token transfer. @param _from The address to transfer tokens from. @param _to The address to transfer tokens to. @param _id The specific token ID to transfer. @param _amount The amount of the specific `_id` to transfer. @param _data Additional call data to send with this transfer. */ function _doSafeTransferAcceptanceCheck(address _operator, address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data) private { if (_to.isContract()) { try IERC1155Receiver(_to).onERC1155Received(_operator, _from, _id, _amount, _data) returns (bytes4 response) { if (response != IERC1155Receiver(_to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } /** The batch equivalent of `_doSafeTransferAcceptanceCheck()`. @param _operator The caller who triggers the token transfer. @param _from The address to transfer tokens from. @param _to The address to transfer tokens to. @param _ids The specific token IDs to transfer. @param _amounts The amounts of the specific `_ids` to transfer. @param _data Additional call data to send with this transfer. */ function _doSafeBatchTransferAcceptanceCheck(address _operator, address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) private { if (_to.isContract()) { try IERC1155Receiver(_to).onERC1155BatchReceived(_operator, _from, _ids, _amounts, _data) returns (bytes4 response) { if (response != IERC1155Receiver(_to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } /** Transfer on behalf of a caller or one of their authorized token managers items from one address to another. @param _from The address to transfer tokens from. @param _to The address to transfer tokens to. @param _ids The specific token IDs to transfer. @param _amounts The amounts of the specific `_ids` to transfer. @param _data Additional call data to send with this transfer. */ function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) public virtual { require(_ids.length == _amounts.length, "ERC1155: ids and amounts length mismatch"); require(_to != address(0), "ERC1155: transfer to the zero address"); require(_from == _msgSender() || isApprovedForAll(_from, _msgSender()), "ERC1155: caller is not owner nor approved"); // Validate transfer and perform all batch token sends. _beforeTokenTransfer(_msgSender(), _from, _to, _ids, _amounts, _data); for (uint256 i = 0; i < _ids.length; ++i) { // Retrieve the item's group ID. uint256 groupId = (_ids[i] & GROUP_MASK) >> 128; // Update all specially-tracked group-specific balances. require(balances[_ids[i]][_from] >= _amounts[i], "ERC1155: insufficient balance for transfer"); balances[_ids[i]][_from] = balances[_ids[i]][_from] - _amounts[i]; balances[_ids[i]][_to] = balances[_ids[i]][_to] + _amounts[i]; groupBalances[groupId][_from] = groupBalances[groupId][_from] - _amounts[i]; groupBalances[groupId][_to] = groupBalances[groupId][_to] + _amounts[i]; totalBalances[_from] = totalBalances[_from] - _amounts[i]; totalBalances[_to] = totalBalances[_to] + _amounts[i]; } // Emit the transfer event and perform the safety check. emit TransferBatch(_msgSender(), _from, _to, _ids, _amounts); _doSafeBatchTransferAcceptanceCheck(_msgSender(), _from, _to, _ids, _amounts, _data); } /** Transfer on behalf of a caller or one of their authorized token managers items from one address to another. @param _from The address to transfer tokens from. @param _to The address to transfer tokens to. @param _id The specific token ID to transfer. @param _amount The amount of the specific `_id` to transfer. @param _data Additional call data to send with this transfer. */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data) external virtual { safeBatchTransferFrom(_from, _to, _asSingletonArray(_id), _asSingletonArray(_amount), _data); } /** Create a new NFT item group or configure an existing one. NFTs within a group share a group ID in the upper 128-bits of their full item ID. Within a group NFTs can be distinguished for the purposes of serializing issue numbers. @param _groupId The ID of the item group to create or configure. @param _data The `ItemGroup` data input. */ function configureGroup(uint256 _groupId, DFStorage.ItemGroupInput calldata _data) external { require(_groupId != 0, "Super1155: group ID 0 is invalid"); require(_hasItemRight(_groupId, CONFIGURE_GROUP), "Super1155: you don't have rights to configure group"); // If the collection is not locked, we may add a new item group. if (!itemGroups[_groupId].initialized) { require(!locked, "Super1155: the collection is locked so groups cannot be created"); itemGroups[_groupId] = ItemGroup({ initialized: true, name: _data.name, supplyType: _data.supplyType, supplyData: _data.supplyData, itemType: _data.itemType, itemData: _data.itemData, burnType: _data.burnType, burnData: _data.burnData, circulatingSupply: 0, mintCount: 0, burnCount: 0 }); // Edit an existing item group. The name may always be updated. } else { itemGroups[_groupId].name = _data.name; // A capped supply type may not change. // It may also not have its cap increased. if (itemGroups[_groupId].supplyType == DFStorage.SupplyType.Capped) { require(_data.supplyType == DFStorage.SupplyType.Capped, "Super1155: you may not uncap a capped supply type"); require(_data.supplyData <= itemGroups[_groupId].supplyData, "Super1155: you may not increase the supply of a capped type"); // The flexible and uncapped types may freely change. } else { itemGroups[_groupId].supplyType = _data.supplyType; } // Item supply data may not be reduced below the circulating supply. require(_data.supplyData >= itemGroups[_groupId].circulatingSupply, "Super1155: you may not decrease supply below the circulating amount"); itemGroups[_groupId].supplyData = _data.supplyData; // A nonfungible item may not change type. if (itemGroups[_groupId].itemType == DFStorage.ItemType.Nonfungible) { require(_data.itemType == DFStorage.ItemType.Nonfungible, "Super1155: you may not alter nonfungible items"); // A semifungible item may not change type. } else if (itemGroups[_groupId].itemType == DFStorage.ItemType.Semifungible) { require(_data.itemType == DFStorage.ItemType.Semifungible, "Super1155: you may not alter nonfungible items"); // A fungible item may change type if it is unique enough. } else if (itemGroups[_groupId].itemType == DFStorage.ItemType.Fungible) { if (_data.itemType == DFStorage.ItemType.Nonfungible) { require(itemGroups[_groupId].circulatingSupply <= 1, "Super1155: the fungible item is not unique enough to change"); itemGroups[_groupId].itemType = DFStorage.ItemType.Nonfungible; // We may also try for semifungible items with a high-enough cap. } else if (_data.itemType == DFStorage.ItemType.Semifungible) { require(itemGroups[_groupId].circulatingSupply <= _data.itemData, "Super1155: the fungible item is not unique enough to change"); itemGroups[_groupId].itemType = DFStorage.ItemType.Semifungible; itemGroups[_groupId].itemData = _data.itemData; } } } // Emit the configuration event. emit ItemGroupConfigured(_msgSender(), _groupId, _data); } /** This is a private helper function to replace the `hasItemRight` modifier that we use on some functions in order to inline this check during batch minting and burning. @param _id The ID of the item to check for the given `_right` on. @param _right The right that the caller is trying to exercise on `_id`. @return Whether or not the caller has a valid right on this item. */ function _hasItemRight(uint256 _id, bytes32 _right) private view returns (bool) { uint256 groupId = _id >> 128; if (_msgSender() == owner()) { return true; } if (hasRight(_msgSender(), UNIVERSAL, _right)) { return true; } if (hasRight(_msgSender(), bytes32(groupId), _right)) { return true; } if (hasRight(_msgSender(), bytes32(_id), _right)) { return true; } return false; } /** This is a private helper function to verify, according to all of our various minting and burning rules, whether it would be valid to mint some `_amount` of a particular item `_id`. @param _id The ID of the item to check for minting validity. @param _amount The amount of the item to try checking mintability for. @return The ID of the item that should have `_amount` minted for it. */ function _mintChecker(uint256 _id, uint256 _amount) private view returns (uint256) { // Retrieve the item's group ID. uint256 shiftedGroupId = (_id & GROUP_MASK); uint256 groupId = shiftedGroupId >> 128; require(itemGroups[groupId].initialized, "Super1155: you cannot mint a non-existent item group"); // If we can replenish burnt items, then only our currently-circulating // supply matters. Otherwise, historic mints are what determine the cap. uint256 currentGroupSupply = itemGroups[groupId].mintCount; uint256 currentItemSupply = mintCount[_id]; if (itemGroups[groupId].burnType == DFStorage.BurnType.Replenishable) { currentGroupSupply = itemGroups[groupId].circulatingSupply; currentItemSupply = circulatingSupply[_id]; } // If we are subject to a cap on group size, ensure we don't exceed it. if (itemGroups[groupId].supplyType != DFStorage.SupplyType.Uncapped) { require((currentGroupSupply + _amount) <= itemGroups[groupId].supplyData, "Super1155: you cannot mint a group beyond its cap"); } // Do not violate nonfungibility rules. if (itemGroups[groupId].itemType == DFStorage.ItemType.Nonfungible) { require((currentItemSupply + _amount) <= 1, "Super1155: you cannot mint more than a single nonfungible item"); // Do not violate semifungibility rules. } else if (itemGroups[groupId].itemType == DFStorage.ItemType.Semifungible) { require((currentItemSupply + _amount) <= itemGroups[groupId].itemData, "Super1155: you cannot mint more than the alloted semifungible items"); } // Fungible items are coerced into the single group ID + index one slot. uint256 mintedItemId = _id; if (itemGroups[groupId].itemType == DFStorage.ItemType.Fungible) { mintedItemId = shiftedGroupId + 1; } return mintedItemId; } /** Mint a batch of tokens into existence and send them to the `_recipient` address. In order to mint an item, its item group must first have been created. Minting an item must obey both the fungibility and size cap of its group. @param _recipient The address to receive all NFTs within the newly-minted group. @param _ids The item IDs for the new items to create. @param _amounts The amount of each corresponding item ID to create. @param _data Any associated data to use on items minted in this transaction. */ function mintBatch(address _recipient, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external { require(_recipient != address(0), "ERC1155: mint to the zero address"); require(_ids.length == _amounts.length, "ERC1155: ids and amounts length mismatch"); // Validate and perform the mint. address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), _recipient, _ids, _amounts, _data); // Loop through each of the batched IDs to update storage of special // balances and circulation balances. for (uint256 i = 0; i < _ids.length; i++) { require(_hasItemRight(_ids[i], MINT), "Super1155: you do not have the right to mint that item"); // Retrieve the group ID from the given item `_id` and check mint. uint256 groupId = _ids[i] >> 128; uint256 mintedItemId = _mintChecker(_ids[i], _amounts[i]); // Update storage of special balances and circulating values. balances[mintedItemId][_recipient] = balances[mintedItemId][_recipient] + _amounts[i]; groupBalances[groupId][_recipient] = groupBalances[groupId][_recipient] + _amounts[i]; totalBalances[_recipient] = totalBalances[_recipient] + _amounts[i]; mintCount[mintedItemId] = mintCount[mintedItemId] + _amounts[i]; circulatingSupply[mintedItemId] = circulatingSupply[mintedItemId] + _amounts[i]; itemGroups[groupId].mintCount = itemGroups[groupId].mintCount + _amounts[i]; itemGroups[groupId].circulatingSupply = itemGroups[groupId].circulatingSupply + _amounts[i]; } // Emit event and handle the safety check. emit TransferBatch(operator, address(0), _recipient, _ids, _amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), _recipient, _ids, _amounts, _data); } /** This is a private helper function to verify, according to all of our various minting and burning rules, whether it would be valid to burn some `_amount` of a particular item `_id`. @param _id The ID of the item to check for burning validity. @param _amount The amount of the item to try checking burning for. @return The ID of the item that should have `_amount` burnt for it. */ function _burnChecker(uint256 _id, uint256 _amount) private view returns (uint256) { // Retrieve the item's group ID. uint256 shiftedGroupId = (_id & GROUP_MASK); uint256 groupId = shiftedGroupId >> 128; require(itemGroups[groupId].initialized, "Super1155: you cannot burn a non-existent item group"); // If the item group is non-burnable, then revert. if (itemGroups[groupId].burnType == DFStorage.BurnType.None) { revert("Super1155: you cannot burn a non-burnable item group"); } // If we can burn items, then we must verify that we do not exceed the cap. if (itemGroups[groupId].burnType == DFStorage.BurnType.Burnable) { require((itemGroups[groupId].burnCount + _amount) <= itemGroups[groupId].burnData, "Super1155: you may not exceed the burn limit on this item group"); } // Fungible items are coerced into the single group ID + index one slot. uint256 burntItemId = _id; if (itemGroups[groupId].itemType == DFStorage.ItemType.Fungible) { burntItemId = shiftedGroupId + 1; } return burntItemId; } /** This function allows an address to destroy multiple different items in a single call. @param _burner The address whose items are burning. @param _ids The item IDs to burn. @param _amounts The amounts of the corresponding item IDs to burn. */ function burnBatch(address _burner, uint256[] memory _ids, uint256[] memory _amounts) public virtual { require(_burner != address(0), "ERC1155: burn from the zero address"); require(_ids.length == _amounts.length, "ERC1155: ids and amounts length mismatch"); // Validate and perform the burn. address operator = _msgSender(); _beforeTokenTransfer(operator, _burner, address(0), _ids, _amounts, ""); // Loop through each of the batched IDs to update storage of special // balances and circulation balances. for (uint i = 0; i < _ids.length; i++) { require(_hasItemRight(_ids[i], BURN), "Super1155: you do not have the right to burn that item"); // Retrieve the group ID from the given item `_id` and check burn. uint256 groupId = _ids[i] >> 128; uint256 burntItemId = _burnChecker(_ids[i], _amounts[i]); // Update storage of special balances and circulating values. require(balances[burntItemId][_burner] >= _amounts[i], "ERC1155: burn amount exceeds balance"); balances[burntItemId][_burner] = balances[burntItemId][_burner] - _amounts[i]; groupBalances[groupId][_burner] = groupBalances[groupId][_burner] - _amounts[i]; totalBalances[_burner] = totalBalances[_burner] - _amounts[i]; burnCount[burntItemId] = burnCount[burntItemId] + _amounts[i]; circulatingSupply[burntItemId] = circulatingSupply[burntItemId] - _amounts[i]; itemGroups[groupId].burnCount = itemGroups[groupId].burnCount + _amounts[i]; itemGroups[groupId].circulatingSupply = itemGroups[groupId].circulatingSupply - _amounts[i]; } // Emit the burn event. emit TransferBatch(operator, _burner, address(0), _ids, _amounts); } /** This function allows an address to destroy some of its items. @param _burner The address whose item is burning. @param _id The item ID to burn. @param _amount The amount of the corresponding item ID to burn. */ function burn(address _burner, uint256 _id, uint256 _amount) external virtual{ require(_hasItemRight(_id, BURN), "Super1155: you don't have rights to burn"); burnBatch(_burner, _asSingletonArray(_id), _asSingletonArray(_amount)); } /** Set the on-chain metadata attached to a specific token ID so long as the collection as a whole or the token specifically has not had metadata editing frozen. @param _id The ID of the token to set the `_metadata` for. @param _metadata The metadata string to store on-chain. */ function setMetadata(uint256 _id, string memory _metadata) external { require(_hasItemRight(_id, SET_METADATA), "Super1155: you don't have rights to setMetadata"); uint groupId = _id >> 128; require(!uriLocked && !metadataFrozen[_id] && !metadataFrozen[groupId], "Super1155: you cannot edit this metadata because it is frozen"); string memory oldMetadata = metadata[_id]; metadata[_id] = _metadata; emit MetadataChanged(_msgSender(), _id, oldMetadata, _metadata); } /** Allow the item collection owner or an associated manager to forever lock the metadata URI on the entire collection to future changes. */ function lockURI() external hasValidPermit(UNIVERSAL, LOCK_URI) { uriLocked = true; emit PermanentURI(metadataUri, 2 ** 256 - 1); } /** Allow the associated manager to forever lock the contract URI to future changes */ function lockContractUri() external hasValidPermit(UNIVERSAL, LOCK_URI) { contractUriLocked = true; emit PermanentContractURI(contractURI, 2 ** 256 - 1); } /** Allow the item collection owner or an associated manager to forever lock the metadata URI on an item to future changes. @param _uri The value of the URI to lock for `_id`. @param _id The token ID to lock a metadata URI value into. */ function lockURI(string calldata _uri, uint256 _id) external { require(_hasItemRight(_id, LOCK_ITEM_URI), "Super1155: you don't have rights to lock URI"); metadataFrozen[_id] = true; emit PermanentURI(_uri, _id); } /** Allow the item collection owner or an associated manager to forever lock the metadata URI on a group of items to future changes. @param _uri The value of the URI to lock for `groupId`. @param groupId The group ID to lock a metadata URI value into. */ function lockGroupURI(string calldata _uri, uint256 groupId) external { require(_hasItemRight(groupId, LOCK_ITEM_URI), "Super1155: you don't have rights to lock group URI"); metadataFrozen[groupId] = true; emit PermanentURI(_uri, groupId); } /** Allow the item collection owner or an associated manager to forever lock this contract to further item minting. */ function lock() external virtual hasValidPermit(UNIVERSAL, LOCK_CREATION) { locked = true; emit CollectionLocked(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Storage.sol) 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 // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** @title An advanced permission-management contract. @author Tim Clancy This contract allows for a contract owner to delegate specific rights to external addresses. Additionally, these rights can be gated behind certain sets of circumstances and granted expiration times. This is useful for some more finely-grained access control in contracts. The owner of this contract is always a fully-permissioned super-administrator. August 23rd, 2021. */ abstract contract PermitControl is Ownable { using Address for address; /// A special reserved constant for representing no rights. bytes32 public constant ZERO_RIGHT = hex"00000000000000000000000000000000"; /// A special constant specifying the unique, universal-rights circumstance. bytes32 public constant UNIVERSAL = hex"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; /* A special constant specifying the unique manager right. This right allows an address to freely-manipulate the `managedRight` mapping. **/ bytes32 public constant MANAGER = hex"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; /** A mapping of per-address permissions to the circumstances, represented as an additional layer of generic bytes32 data, under which the addresses have various permits. A permit in this sense is represented by a per-circumstance mapping which couples some right, represented as a generic bytes32, to an expiration time wherein the right may no longer be exercised. An expiration time of 0 indicates that there is in fact no permit for the specified address to exercise the specified right under the specified circumstance. @dev Universal rights MUST be stored under the 0xFFFFFFFFFFFFFFFFFFFFFFFF... max-integer circumstance. Perpetual rights may be given an expiry time of max-integer. */ mapping( address => mapping( bytes32 => mapping( bytes32 => uint256 ))) public permissions; /** An additional mapping of managed rights to manager rights. This mapping represents the administrator relationship that various rights have with one another. An address with a manager right may freely set permits for that manager right's managed rights. Each right may be managed by only one other right. */ mapping( bytes32 => bytes32 ) public managerRight; /** An event emitted when an address has a permit updated. This event captures, through its various parameter combinations, the cases of granting a permit, updating the expiration time of a permit, or revoking a permit. @param updator The address which has updated the permit. @param updatee The address whose permit was updated. @param circumstance The circumstance wherein the permit was updated. @param role The role which was updated. @param expirationTime The time when the permit expires. */ event PermitUpdated( address indexed updator, address indexed updatee, bytes32 circumstance, bytes32 indexed role, uint256 expirationTime ); // /** // A version of PermitUpdated for work with setPermits() function. // @param updator The address which has updated the permit. // @param updatees The addresses whose permit were updated. // @param circumstances The circumstances wherein the permits were updated. // @param roles The roles which were updated. // @param expirationTimes The times when the permits expire. // */ // event PermitsUpdated( // address indexed updator, // address[] indexed updatees, // bytes32[] circumstances, // bytes32[] indexed roles, // uint256[] expirationTimes // ); /** An event emitted when a management relationship in `managerRight` is updated. This event captures adding and revoking management permissions via observing the update history of the `managerRight` value. @param manager The address of the manager performing this update. @param managedRight The right which had its manager updated. @param managerRight The new manager right which was updated to. */ event ManagementUpdated( address indexed manager, bytes32 indexed managedRight, bytes32 indexed managerRight ); /** A modifier which allows only the super-administrative owner or addresses with a specified valid right to perform a call. @param _circumstance The circumstance under which to check for the validity of the specified `right`. @param _right The right to validate for the calling address. It must be non-expired and exist within the specified `_circumstance`. */ modifier hasValidPermit( bytes32 _circumstance, bytes32 _right ) { require(_msgSender() == owner() || hasRight(_msgSender(), _circumstance, _right), "P1"); _; } /** Return a version number for this contract's interface. */ function version() external virtual pure returns (uint256) { return 1; } /** Determine whether or not an address has some rights under the given circumstance, and if they do have the right, until when. @param _address The address to check for the specified `_right`. @param _circumstance The circumstance to check the specified `_right` for. @param _right The right to check for validity. @return The timestamp in seconds when the `_right` expires. If the timestamp is zero, we can assume that the user never had the right. */ function hasRightUntil( address _address, bytes32 _circumstance, bytes32 _right ) public view returns (uint256) { return permissions[_address][_circumstance][_right]; } /** Determine whether or not an address has some rights under the given circumstance, @param _address The address to check for the specified `_right`. @param _circumstance The circumstance to check the specified `_right` for. @param _right The right to check for validity. @return true or false, whether user has rights and time is valid. */ function hasRight( address _address, bytes32 _circumstance, bytes32 _right ) public view returns (bool) { return permissions[_address][_circumstance][_right] > block.timestamp; } /** Set the permit to a specific address under some circumstances. A permit may only be set by the super-administrative contract owner or an address holding some delegated management permit. @param _address The address to assign the specified `_right` to. @param _circumstance The circumstance in which the `_right` is valid. @param _right The specific right to assign. @param _expirationTime The time when the `_right` expires for the provided `_circumstance`. */ function setPermit( address _address, bytes32 _circumstance, bytes32 _right, uint256 _expirationTime ) public virtual hasValidPermit(UNIVERSAL, managerRight[_right]) { require(_right != ZERO_RIGHT, "P2"); permissions[_address][_circumstance][_right] = _expirationTime; emit PermitUpdated(_msgSender(), _address, _circumstance, _right, _expirationTime); } // /** // Version of setPermit() that works with multiple addresses in one transaction. // @param _addresses The array of addresses to assign the specified `_right` to. // @param _circumstances The array of circumstances in which the `_right` is // valid. // @param _rights The array of specific rights to assign. // @param _expirationTimes The array of times when the `_rights` expires for // the provided _circumstance`. // */ // function setPermits( // address[] memory _addresses, // bytes32[] memory _circumstances, // bytes32[] memory _rights, // uint256[] memory _expirationTimes // ) public virtual { // require((_addresses.length == _circumstances.length) // && (_circumstances.length == _rights.length) // && (_rights.length == _expirationTimes.length), // "leghts of input arrays are not equal" // ); // bytes32 lastRight; // for(uint i = 0; i < _rights.length; i++) { // if (lastRight != _rights[i] || (i == 0)) { // require(_msgSender() == owner() || hasRight(_msgSender(), _circumstances[i], _rights[i]), "P1"); // require(_rights[i] != ZERO_RIGHT, "P2"); // lastRight = _rights[i]; // } // permissions[_addresses[i]][_circumstances[i]][_rights[i]] = _expirationTimes[i]; // } // emit PermitsUpdated( // _msgSender(), // _addresses, // _circumstances, // _rights, // _expirationTimes // ); // } /** Set the `_managerRight` whose `UNIVERSAL` holders may freely manage the specified `_managedRight`. @param _managedRight The right which is to have its manager set to `_managerRight`. @param _managerRight The right whose `UNIVERSAL` holders may manage `_managedRight`. */ function setManagerRight( bytes32 _managedRight, bytes32 _managerRight ) external virtual hasValidPermit(UNIVERSAL, MANAGER) { require(_managedRight != ZERO_RIGHT, "P3"); managerRight[_managedRight] = _managerRight; emit ManagementUpdated(_msgSender(), _managedRight, _managerRight); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /** @title A proxy registry contract. @author Protinam, Project Wyvern @author Tim Clancy This contract was originally developed by Project Wyvern (https://github.com/ProjectWyvern/) where it currently enjoys great success as a component of the primary exchange contract for OpenSea. It has been modified to support a more modern version of Solidity with associated best practices. The documentation has also been improved to provide more clarity. */ abstract contract StubProxyRegistry { /** This mapping relates an addresses to its own personal `OwnableDelegateProxy` which allow it to proxy functionality to the various callers contained in `authorizedCallers`. */ mapping(address => address) public proxies; } pragma solidity 0.8.8; library DFStorage { /** @notice This struct is a source of mapping-free input to the `addPool` function. @param name A name for the pool. @param startTime The timestamp when this pool begins allowing purchases. @param endTime The timestamp after which this pool disallows purchases. @param purchaseLimit The maximum number of items a single address may purchase from this pool. @param singlePurchaseLimit The maximum number of items a single address may purchase from this pool in a single transaction. @param requirement A PoolRequirement requisite for users who want to participate in this pool. */ struct PoolInput { string name; uint256 startTime; uint256 endTime; uint256 purchaseLimit; uint256 singlePurchaseLimit; PoolRequirement requirement; address collection; } /** @notice This enumeration type specifies the different access rules that may be applied to pools in this shop. Access to a pool may be restricted based on the buyer's holdings of either tokens or items. @param Public This specifies a pool which requires no special asset holdings to buy from. @param TokenRequired This specifies a pool which requires the buyer to hold some amount of ERC-20 tokens to buy from. @param ItemRequired This specifies a pool which requires the buyer to hold some amount of an ERC-1155 item to buy from. @param PointRequired This specifies a pool which requires the buyer to hold some amount of points in a Staker to buy from. */ enum AccessType { Public, TokenRequired, ItemRequired, PointRequired, ItemRequired721 } /** @notice This struct tracks information about a prerequisite for a user to participate in a pool. @param requiredType The `AccessType` being applied to gate buyers from participating in this pool. See `requiredAsset` for how additional data can apply to the access type. @param requiredAsset Some more specific information about the asset to require. If the `requiredType` is `TokenRequired`, we use this address to find the ERC-20 token that we should be specifically requiring holdings of. If the `requiredType` is `ItemRequired`, we use this address to find the item contract that we should be specifically requiring holdings of. If the `requiredType` is `PointRequired`, we treat this address as the address of a Staker contract. Do note that in order for this to work, the Staker must have approved this shop as a point spender. @param requiredAmount The amount of the specified `requiredAsset` required for the buyer to purchase from this pool. @param requiredId The ID of an address whitelist to restrict participants in this pool. To participate, a purchaser must have their address present in the corresponding whitelist. Other requirements from `requiredType` also apply. An ID of 0 is a sentinel value for no whitelist required. */ struct PoolRequirement { AccessType requiredType; address[] requiredAsset; uint256 requiredAmount; uint256[] requiredId; } /** @notice This enumeration type specifies the different assets that may be used to complete purchases from this mint shop. @param Point This specifies that the asset being used to complete this purchase is non-transferrable points from a `Staker` contract. @param Ether This specifies that the asset being used to complete this purchase is native Ether currency. @param Token This specifies that the asset being used to complete this purchase is an ERC-20 token. */ enum AssetType { Point, Ether, Token } /** @notice This struct tracks information about a single asset with the associated price that an item is being sold in the shop for. It also includes an `asset` field which is used to convey optional additional data about the asset being used to purchase with. @param assetType The `AssetType` type of the asset being used to buy. @param asset Some more specific information about the asset to charge in. If the `assetType` is Point, we use this address to find the specific Staker whose points are used as the currency. If the `assetType` is Ether, we ignore this field. If the `assetType` is Token, we use this address to find the ERC-20 token that we should be specifically charging with. @param price The amount of the specified `assetType` and `asset` to charge. */ struct Price { AssetType assetType; address asset; uint256 price; } /** This enumeration lists the various supply types that each item group may use. In general, the administrator of this collection or those permissioned to do so may move from a more-permissive supply type to a less-permissive. For example: an uncapped or flexible supply type may be converted to a capped supply type. A capped supply type may not be uncapped later, however. @param Capped There exists a fixed cap on the size of the item group. The cap is set by `supplyData`. @param Uncapped There is no cap on the size of the item group. The value of `supplyData` cannot be set below the current circulating supply but is otherwise ignored. @param Flexible There is a cap which can be raised or lowered (down to circulating supply) freely. The value of `supplyData` cannot be set below the current circulating supply and determines the cap. */ enum SupplyType { Capped, Uncapped, Flexible } /** This enumeration lists the various item types that each item group may use. In general, these are static once chosen. @param Nonfungible The item group is truly nonfungible where each ID may be used only once. The value of `itemData` is ignored. @param Fungible The item group is truly fungible and collapses into a single ID. The value of `itemData` is ignored. @param Semifungible The item group may be broken up across multiple repeating token IDs. The value of `itemData` is the cap of any single token ID in the item group. */ enum ItemType { Nonfungible, Fungible, Semifungible } /** This enumeration lists the various burn types that each item group may use. These are static once chosen. @param None The items in this group may not be burnt. The value of `burnData` is ignored. @param Burnable The items in this group may be burnt. The value of `burnData` is the maximum that may be burnt. @param Replenishable The items in this group, once burnt, may be reminted by the owner. The value of `burnData` is ignored. */ enum BurnType { None, Burnable, Replenishable } /** This struct is a source of mapping-free input to the `configureGroup` function. It defines the settings for a particular item group. @param supplyData An optional integer used by some `supplyType` values. @param itemData An optional integer used by some `itemType` values. @param burnData An optional integer used by some `burnType` values. @param name A name for the item group. @param supplyType The supply type for this group of items. @param itemType The type of item represented by this item group. @param burnType The type of burning permitted by this item group. */ struct ItemGroupInput { uint256 supplyData; uint256 itemData; uint256 burnData; SupplyType supplyType; ItemType itemType; BurnType burnType; string name; } /** This structure is used at the moment of NFT purchase. @param whiteListId Id of a whiteList. @param index Element index in the original array @param allowance The quantity is available to the user for purchase. @param node Base hash of the element. @param merkleProof Proof that the user is on the whitelist. */ struct WhiteListInput { uint256 whiteListId; uint256 index; uint256 allowance; bytes32 node; bytes32[] merkleProof; } /** This structure is used at the moment of NFT purchase. @param _accesslistId Id of a whiteList. @param _merkleRoot Hash root of merkle tree. @param _startTime The start date of the whitelist @param _endTime The end date of the whitelist @param _price The price that applies to the whitelist @param _token Token with which the purchase will be made */ struct WhiteListCreate { uint256 _accesslistId; bytes32 _merkleRoot; uint256 _startTime; uint256 _endTime; uint256 _price; address _token; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.8; import "../../../libraries/DFStorage.sol"; /** @title An interface for the `Super1155` ERC-1155 item collection contract. @author 0xthrpw @author Tim Clancy August 12th, 2021. */ interface ISuper1155 { /// The public identifier for the right to set this contract's metadata URI. function SET_URI () external view returns (bytes32); /// The public identifier for the right to set this contract's proxy registry. function SET_PROXY_REGISTRY () external view returns (bytes32); /// The public identifier for the right to configure item groups. function CONFIGURE_GROUP () external view returns (bytes32); /// The public identifier for the right to mint items. function MINT () external view returns (bytes32); /// The public identifier for the right to burn items. function BURN () external view returns (bytes32); /// The public identifier for the right to set item metadata. function SET_METADATA () external view returns (bytes32); /// The public identifier for the right to lock the metadata URI. function LOCK_URI () external view returns (bytes32); /// The public identifier for the right to lock an item's metadata. function LOCK_ITEM_URI () external view returns (bytes32); /// The public identifier for the right to disable item creation. function LOCK_CREATION () external view returns (bytes32); /// The public name of this contract. function name () external view returns (string memory); /** The ERC-1155 URI for tracking item metadata, supporting {id} substitution. For example: https://token-cdn-domain/{id}.json. See the ERC-1155 spec for more details: https://eips.ethereum.org/EIPS/eip-1155#metadata. */ function metadataUri () external view returns (string memory); /// A proxy registry address for supporting automatic delegated approval. function proxyRegistryAddress () external view returns (address); /// A mapping from each group ID to per-address balances. function groupBalances (uint256, address) external view returns (uint256); /// A mapping from each address to a collection-wide balance. function totalBalances (address) external view returns (uint256); /// A mapping of data for each item group. // function itemGroups (uint256) external view returns (ItemGroup memory); /* function itemGroups (uint256) external view returns (bool initialized, string memory _name, uint8 supplyType, uint256 supplyData, uint8 itemType, uint256 itemData, uint8 burnType, uint256 burnData, uint256 _circulatingSupply, uint256 _mintCount, uint256 _burnCount); */ /// A mapping of circulating supplies for each individual token. function circulatingSupply (uint256) external view returns (uint256); /// A mapping of the number of times each individual token has been minted. function mintCount (uint256) external view returns (uint256); /// A mapping of the number of times each individual token has been burnt. function burnCount (uint256) external view returns (uint256); /** A mapping of token ID to a boolean representing whether the item's metadata has been explicitly frozen via a call to `lockURI(string calldata _uri, uint256 _id)`. Do note that it is possible for an item's mapping here to be false while still having frozen metadata if the item collection as a whole has had its `uriLocked` value set to true. */ function metadataFrozen (uint256) external view returns (bool); /** A public mapping of optional on-chain metadata for each token ID. A token's on-chain metadata is unable to be changed if the item's metadata URI has been permanently fixed or if the collection's metadata URI as a whole has been frozen. */ function metadata (uint256) external view returns (string memory); /// Whether or not the metadata URI has been locked to future changes. function uriLocked () external view returns (bool); /// Whether or not the item collection has been locked to all further minting. function locked () external view returns (bool); /** Return a version number for this contract's interface. */ function version () external view returns (uint256); /** Return the item collection's metadata URI. This implementation returns the same URI for all tokens within the collection and relies on client-side ID substitution per https://eips.ethereum.org/EIPS/eip-1155#metadata. Per said specification, clients calling this function must replace the {id} substring with the actual token ID in hex, not prefixed by 0x, and padded to 64 characters in length. @return The metadata URI string of the item with ID `_itemId`. */ function uri (uint256) external view returns (string memory); /** Allow the item collection owner or an approved manager to update the metadata URI of this collection. This implementation relies on a single URI for all items within the collection, and as such does not emit the standard URI event. Instead, we emit our own event to reflect changes in the URI. @param _uri The new URI to update to. */ function setURI (string memory _uri) external; /** Allow the item collection owner or an approved manager to update the proxy registry address handling delegated approval. @param _proxyRegistryAddress The address of the new proxy registry to update to. */ function setProxyRegistry (address _proxyRegistryAddress) external; /** Retrieve the balance of a particular token `_id` for a particular address `_owner`. @param _owner The owner to check for this token balance. @param _id The ID of the token to check for a balance. @return The amount of token `_id` owned by `_owner`. */ function balanceOf (address _owner, uint256 _id) external view returns (uint256); /** Retrieve in a single call the balances of some mulitple particular token `_ids` held by corresponding `_owners`. @param _owners The owners to check for token balances. @param _ids The IDs of tokens to check for balances. @return the amount of each token owned by each owner. */ function balanceOfBatch (address[] memory _owners, uint256[] memory _ids) external view returns (uint256[] memory); /** This function returns true if `_operator` is approved to transfer items owned by `_owner`. This approval check features an override to explicitly whitelist any addresses delegated in the proxy registry. @param _owner The owner of items to check for transfer ability. @param _operator The potential transferrer of `_owner`'s items. @return Whether `_operator` may transfer items owned by `_owner`. */ function isApprovedForAll (address _owner, address _operator) external view returns (bool); /** Enable or disable approval for a third party `_operator` address to manage (transfer or burn) all of the caller's tokens. @param _operator The address to grant management rights over all of the caller's tokens. @param _approved The status of the `_operator`'s approval for the caller. */ function setApprovalForAll (address _operator, bool _approved) external; /** Transfer on behalf of a caller or one of their authorized token managers items from one address to another. @param _from The address to transfer tokens from. @param _to The address to transfer tokens to. @param _id The specific token ID to transfer. @param _amount The amount of the specific `_id` to transfer. @param _data Additional call data to send with this transfer. */ function safeTransferFrom (address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) external; /** Transfer on behalf of a caller or one of their authorized token managers items from one address to another. @param _from The address to transfer tokens from. @param _to The address to transfer tokens to. @param _ids The specific token IDs to transfer. @param _amounts The amounts of the specific `_ids` to transfer. @param _data Additional call data to send with this transfer. */ function safeBatchTransferFrom (address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) external; /** Create a new NFT item group or configure an existing one. NFTs within a group share a group ID in the upper 128-bits of their full item ID. Within a group NFTs can be distinguished for the purposes of serializing issue numbers. @param _groupId The ID of the item group to create or configure. @param _data The `ItemGroup` data input. */ function configureGroup (uint256 _groupId, DFStorage.ItemGroupInput calldata _data) external; /** Mint a batch of tokens into existence and send them to the `_recipient` address. In order to mint an item, its item group must first have been created. Minting an item must obey both the fungibility and size cap of its group. @param _recipient The address to receive all NFTs within the newly-minted group. @param _ids The item IDs for the new items to create. @param _amounts The amount of each corresponding item ID to create. @param _data Any associated data to use on items minted in this transaction. */ function mintBatch (address _recipient, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) external; /** This function allows an address to destroy some of its items. @param _burner The address whose item is burning. @param _id The item ID to burn. @param _amount The amount of the corresponding item ID to burn. */ function burn (address _burner, uint256 _id, uint256 _amount) external; /** This function allows an address to destroy multiple different items in a single call. @param _burner The address whose items are burning. @param _ids The item IDs to burn. @param _amounts The amounts of the corresponding item IDs to burn. */ function burnBatch (address _burner, uint256[] memory _ids, uint256[] memory _amounts) external; /** Set the on-chain metadata attached to a specific token ID so long as the collection as a whole or the token specifically has not had metadata editing frozen. @param _id The ID of the token to set the `_metadata` for. @param _metadata The metadata string to store on-chain. */ function setMetadata (uint256 _id, string memory _metadata) external; /** Allow the item collection owner or an associated manager to forever lock the metadata URI on the entire collection to future changes. @param _uri The value of the URI to lock for `_id`. */ function lockURI(string calldata _uri) external; /** Allow the item collection owner or an associated manager to forever lock the metadata URI on an item to future changes. @param _uri The value of the URI to lock for `_id`. @param _id The token ID to lock a metadata URI value into. */ function lockURI(string calldata _uri, uint256 _id) external; /** Allow the item collection owner or an associated manager to forever lock the metadata URI on a group of items to future changes. @param _uri The value of the URI to lock for `groupId`. @param groupId The group ID to lock a metadata URI value into. */ function lockGroupURI(string calldata _uri, uint256 groupId) external; /** Allow the item collection owner or an associated manager to forever lock this contract to further item minting. */ function lock() external; } // 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 v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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; } }
*/ Retrieve the item's group ID. If the item group is non-burnable, then revert. If we can burn items, then we must verify that we do not exceed the cap.
This is a private helper function to verify, according to all of our various minting and burning rules, whether it would be valid to burn some `_amount` of a particular item `_id`. @param _id The ID of the item to check for burning validity. @param _amount The amount of the item to try checking burning for. @return The ID of the item that should have `_amount` burnt for it. function _burnChecker(uint256 _id, uint256 _amount) private view returns (uint256) { uint256 shiftedGroupId = (_id & GROUP_MASK); uint256 groupId = shiftedGroupId >> 128; require(itemGroups[groupId].initialized, "Super1155: you cannot burn a non-existent item group"); if (itemGroups[groupId].burnType == DFStorage.BurnType.None) { revert("Super1155: you cannot burn a non-burnable item group"); } if (itemGroups[groupId].burnType == DFStorage.BurnType.Burnable) { require((itemGroups[groupId].burnCount + _amount) <= itemGroups[groupId].burnData, "Super1155: you may not exceed the burn limit on this item group"); } if (itemGroups[groupId].itemType == DFStorage.ItemType.Fungible) { burntItemId = shiftedGroupId + 1; } return burntItemId; }
6,273,098
[ 1, 19, 10708, 326, 761, 1807, 1041, 1599, 18, 971, 326, 761, 1041, 353, 1661, 17, 70, 321, 429, 16, 1508, 15226, 18, 971, 732, 848, 18305, 1516, 16, 1508, 732, 1297, 3929, 716, 732, 741, 486, 9943, 326, 3523, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1220, 353, 279, 3238, 4222, 445, 358, 3929, 16, 4888, 358, 777, 434, 3134, 11191, 203, 565, 312, 474, 310, 471, 18305, 310, 2931, 16, 2856, 518, 4102, 506, 923, 358, 18305, 2690, 1375, 67, 8949, 68, 203, 565, 434, 279, 6826, 761, 1375, 67, 350, 8338, 203, 203, 565, 632, 891, 389, 350, 1021, 1599, 434, 326, 761, 358, 866, 364, 18305, 310, 13800, 18, 203, 565, 632, 891, 389, 8949, 1021, 3844, 434, 326, 761, 358, 775, 6728, 18305, 310, 364, 18, 203, 565, 632, 2463, 1021, 1599, 434, 326, 761, 716, 1410, 1240, 1375, 67, 8949, 68, 18305, 88, 364, 518, 18, 203, 225, 445, 389, 70, 321, 8847, 12, 11890, 5034, 389, 350, 16, 2254, 5034, 389, 8949, 13, 3238, 1476, 203, 565, 1135, 261, 11890, 5034, 13, 288, 203, 203, 565, 2254, 5034, 21340, 8722, 273, 261, 67, 350, 473, 13839, 67, 11704, 1769, 203, 565, 2254, 5034, 6612, 273, 21340, 8722, 1671, 8038, 31, 203, 565, 2583, 12, 1726, 3621, 63, 27547, 8009, 13227, 16, 203, 1377, 315, 8051, 2499, 2539, 30, 1846, 2780, 18305, 279, 1661, 17, 19041, 761, 1041, 8863, 203, 203, 565, 309, 261, 1726, 3621, 63, 27547, 8009, 70, 321, 559, 422, 463, 42, 3245, 18, 38, 321, 559, 18, 7036, 13, 288, 203, 1377, 15226, 2932, 8051, 2499, 2539, 30, 1846, 2780, 18305, 279, 1661, 17, 70, 321, 429, 761, 1041, 8863, 203, 565, 289, 203, 203, 565, 309, 261, 1726, 3621, 63, 27547, 8009, 70, 321, 559, 422, 463, 42, 3245, 2 ]
./full_match/80001/0xB5E7bb79bCFd916b319b3320C63B98e617BFd023/sources/project_/contracts/Limits.sol
@notice Returns the value of the default Transaction Count limit
function defaultTransactionCountLimit() external view returns (uint256) { return _defaultTransactionCountLimit; }
842,481
[ 1, 1356, 326, 460, 434, 326, 805, 5947, 6974, 1800, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 805, 3342, 1380, 3039, 1435, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 1886, 3342, 1380, 3039, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x61d4b386793B802c2cd976A32Fedd27370446156/sources/contracts/FundMe.sol
this function technically should be called "getConversionRate". This function getPrice() is showing the current price of 1 ETH in USD*10^18.
function getPrice() public view returns(uint256) { AggregatorV3Interface priceFeed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e); (,int256 answer,,,) = priceFeed.latestRoundData(); return uint256(answer*10**10); }
746,956
[ 1, 2211, 445, 17734, 6478, 1410, 506, 2566, 315, 588, 6814, 4727, 9654, 1220, 445, 25930, 1435, 353, 17253, 326, 783, 6205, 434, 404, 512, 2455, 316, 587, 9903, 2163, 66, 2643, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 25930, 1435, 1071, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 565, 10594, 639, 58, 23, 1358, 6205, 8141, 273, 10594, 639, 58, 23, 1358, 12, 20, 92, 28, 37, 5877, 23, 5608, 27, 37, 21, 29634, 7616, 24, 7228, 29, 7677, 71, 41, 9349, 41, 29, 74, 6418, 4313, 23, 37, 28, 6799, 4449, 20, 73, 1769, 203, 565, 261, 16, 474, 5034, 5803, 16408, 16, 13, 273, 6205, 8141, 18, 13550, 11066, 751, 5621, 203, 1377, 327, 2254, 5034, 12, 13490, 14, 2163, 636, 2163, 1769, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @author OpenZeppelin * @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; } } pragma solidity ^0.4.11; /** * @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; } } pragma solidity ^0.4.8; 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) constant returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success); /// @notice `msg.sender` approves `_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) returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } pragma solidity ^0.4.8; contract StandardToken is Token { function transfer(address _to, uint256 _value) 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; Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) 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; Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } pragma solidity ^0.4.8; 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. function HumanStandardToken( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) { 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) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. require(_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)); return true; } } pragma solidity ^0.4.17; /** * SHARE token is an ERC20 token. */ contract Share is HumanStandardToken, Ownable { using SafeMath for uint; string public constant TOKEN_NAME = "Vyral Token"; string public constant TOKEN_SYMBOL = "SHARE"; uint8 public constant TOKEN_DECIMALS = 18; uint public constant TOTAL_SUPPLY = 777777777 * (10 ** uint(TOKEN_DECIMALS)); mapping (address => uint256) lockedBalances; mapping (address => bool) public transferrers; /** * Init this contract with the same params as a HST. */ function Share() HumanStandardToken(TOTAL_SUPPLY, TOKEN_NAME, TOKEN_DECIMALS, TOKEN_SYMBOL) public { transferrers[msg.sender] = true; } ///----------------- /// Overrides ///----------------- /// Off on deployment. bool isTransferable = false; /// Bonus tokens are locked on deployment bool isBonusLocked = true; /// Allows the owner to transfer tokens whenever, but others to only transfer after owner says so. modifier canBeTransferred { require(transferrers[msg.sender] || isTransferable); _; } function transferReward( address _to, uint _value ) canBeTransferred public returns (bool) { require(balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); lockedBalances[_to] = lockedBalances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transfer( address _to, uint _value ) canBeTransferred public returns (bool) { require(balances[msg.sender] >= _value); /// Only transfer unlocked balance if(isBonusLocked) { require(balances[msg.sender].sub(lockedBalances[msg.sender]) >= _value); } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom( address _from, address _to, uint _value ) canBeTransferred public returns (bool) { require(balances[_from] >= _value); require(allowed[_from][msg.sender] >= _value); /// Only transfer unlocked balance if(isBonusLocked) { require(balances[_from].sub(lockedBalances[_from]) >= _value); } allowed[_from][msg.sender] = allowed[_from][_to].sub(_value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); return true; } function lockedBalanceOf( address _owner ) constant returns (uint) { return lockedBalances[_owner]; } ///----------------- /// Admin ///----------------- function enableTransfers() onlyOwner external returns (bool) { isTransferable = true; return isTransferable; } function addTransferrer( address _transferrer ) public onlyOwner { transferrers[_transferrer] = true; } /** * @dev Allow bonus tokens to be withdrawn */ function releaseBonus() public onlyOwner { isBonusLocked = false; } }
Only transfer unlocked balance
function transfer( address _to, uint _value ) canBeTransferred public returns (bool) { require(balances[msg.sender] >= _value); if(isBonusLocked) { require(balances[msg.sender].sub(lockedBalances[msg.sender]) >= _value); } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; }
12,856,493
[ 1, 3386, 7412, 25966, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 203, 3639, 1758, 389, 869, 16, 203, 3639, 2254, 389, 1132, 203, 565, 262, 203, 3639, 24978, 1429, 4193, 203, 3639, 1071, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2583, 12, 70, 26488, 63, 3576, 18, 15330, 65, 1545, 389, 1132, 1769, 203, 203, 3639, 309, 12, 291, 38, 22889, 8966, 13, 288, 203, 5411, 2583, 12, 70, 26488, 63, 3576, 18, 15330, 8009, 1717, 12, 15091, 38, 26488, 63, 3576, 18, 15330, 5717, 1545, 389, 1132, 1769, 203, 3639, 289, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 3639, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 3639, 12279, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; // File: contracts/openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/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 private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/Randomness.sol contract Randomness is Ownable { bytes32 private seed = "hحَi"; function rand(bytes32 key) public onlyOwner returns (bytes32) { seed ^= key; return keccak256(abi.encodePacked(key, seed, block.timestamp, block.difficulty, "台灣きन्दी한حَNo.1 :) ")); } } // File: contracts/CryptoBeauty.sol /* * Terms: * >> Salt: a number that accompany with random draw to make multiple drawing different across cards */ pragma solidity ^0.4.23; contract CryptoBeauty is Ownable { using SafeMath for uint256; struct PhotoPool { uint256[] photoIds; } struct Card { uint256 photoId; uint256 rarityScore; address holder; } struct Photo { uint256 modelId; uint256 photographerId; } Randomness randomnessContract; PhotoPool[] photoPools; Card[] public cards; Photo[] public photos; mapping (address => uint256) public playerLastFreeDrawTime; mapping (address => uint256[]) public playerDrawnCardIds; mapping (address => mapping (uint256 => bool)) public playerDrawnCardIdIsHeld; address public ownerWalletAddr; uint256 public drawCardPrice = 20000000; // 20 TRX (6 accuracy) uint256 public freeDrawTimeGap = 23 hours; /* events */ event PoolAdded( uint256 indexed photoPoolId ); event PhotoAdded( uint256 indexed photoId, uint256 indexed modelId, uint256 indexed photographerId ); event CardDrawn( uint256 indexed cardId, uint256 indexed photoId, uint256 rarityScore, address indexed to ); event Transfer( uint256 indexed cardId, address indexed from, address indexed to ); constructor(uint256 _drawCardPrice, address _ownerWalletAddr) public { randomnessContract = new Randomness(); drawCardPrice = _drawCardPrice; ownerWalletAddr = _ownerWalletAddr; } // ------------ external functions ------------------- /* manager methods */ function setDrawCardPrice(uint256 _price) external onlyOwner { require(_price != 0); drawCardPrice = _price; } function setFreeDrawTimeGap(uint256 _gap) external onlyOwner { require(_gap != 0); freeDrawTimeGap = _gap; } function withdraw(uint256 amount) external onlyOwner { require(address(this).balance >= amount); ownerWalletAddr.transfer(amount); } function addPhoto(uint256 _modelId, uint256 _photographerId) public onlyOwner { Photo memory _photo = Photo({ modelId: _modelId, photographerId: _photographerId }); uint256 _photoId = getLatestPhotoId(); photos.push(_photo); emit PhotoAdded( _photoId, _modelId, _photographerId ); } function addPhotos(uint256[] _modelIds, uint256[] _photographerIds) external onlyOwner { require(_modelIds.length == _photographerIds.length); for (uint256 i = 0; i < _modelIds.length; i++) { addPhoto(_modelIds[i], _photographerIds[i]); } } function addPhotoPool(uint256[] _photoIds) external onlyOwner { // a pool must contain some photos require(_photoIds.length > 0, "_photoIds can't be empty."); // all photoIds in a pool must exist for (uint256 i = 0; i < _photoIds.length; i++) { require(isValidPhotoId(_photoIds[i]), "photoId doesn't exist"); } PhotoPool memory _pool = PhotoPool({ photoIds: _photoIds }); uint256 _photoPoolId = photoPools.length; photoPools.push(_pool); emit PoolAdded( _photoPoolId ); } /* EXTERNAL user methods */ function freeDrawCard(uint256 _photoPoolId) external { // free draw if play has not drew before or today is first draw require(playerLastFreeDrawTime[msg.sender] == 0 || playerLastFreeDrawTime[msg.sender].add(freeDrawTimeGap) <= block.timestamp); // MUST be valid photo pool ID require(isValidPhotoId(_photoPoolId)); // update last draw time playerLastFreeDrawTime[msg.sender] = block.timestamp; _drawCard(_photoPoolId, block.timestamp); } function drawCard(uint256 _photoPoolId) external payable { require(msg.value == drawCardPrice, "paying incorrect amount"); _drawCard(_photoPoolId, block.timestamp); } function drawMultipleCards(uint256 _photoPoolId, uint256 _amount) external payable { require(_amount > 0, "_amount can't be 0"); require(msg.value == drawCardPrice.mul(_amount), "paying not correct amount"); for (uint256 i = 0; i < _amount; i++) { _drawCard(_photoPoolId, i.mul(block.timestamp)); } } // pool id can duplicate, ex. [0, 0, 1, 3] function drawMultipleCardsFromMultiplePools(uint256[] _photoPoolIds) external payable { require(_photoPoolIds.length > 0, "no _photoPoolIds provided"); require(_photoPoolIds.length <= 10, "number of pool ids cannot exceed 10"); require(msg.value == drawCardPrice.mul(_photoPoolIds.length), "paying not correct amount"); for (uint256 i = 0; i < _photoPoolIds.length; i++) { _drawCard(_photoPoolIds[i], i.mul(block.timestamp)); } } function transfer(uint256 _cardId, address _to) external { require(_to != address(0x0)); require(isValidCardId(_cardId)); require(cards[_cardId].holder == msg.sender); _transferCard(_cardId, msg.sender, _to); } // ------------ public view functions ------------------- function getLatestPhotoId() public view returns (uint){ return photos.length; } function getLatestPhotoPoolId() public view returns (uint){ return photoPools.length; } function isValidPhotoId(uint256 _photoId) public view returns (bool) { return _photoId < photos.length; } function isValidPoolId(uint256 _photoPoolId) public view returns (bool) { return _photoPoolId < photoPools.length; } function isValidCardId(uint256 _cardId) public view returns (bool) { return _cardId < cards.length; } function drawnCardIdsOf(address _user) external view returns(uint256[] cardIds) { return playerDrawnCardIds[_user]; } function playerDrawnCardIdIsHeldOf(address _user, uint256 _cardId) external view returns(bool) { return playerDrawnCardIdIsHeld[_user][_cardId]; } function drawnCardsOf(address _user) external view returns(uint256[] cardIds, uint256[] photoIds, uint256[] rarityScores) { uint256[] storage _cardIds = playerDrawnCardIds[_user]; uint256[] memory _photoIds = new uint256[](_cardIds.length); uint256[] memory _rarityScores = new uint256[](_cardIds.length); for (uint256 i = 0; i < _cardIds.length; i++) { _photoIds[i] = cards[_cardIds[i]].photoId; _rarityScores[i] = cards[_cardIds[i]].rarityScore; } return (_cardIds, _photoIds, _rarityScores); } // ---------------- internal functions ----------------- function _drawCard(uint256 _photoPoolId, uint256 _salt) internal { // draw random photoId uint256 _photoId = _drawPhotoId(_photoPoolId, _salt); // draw random rarity uint256 _rarityScore = _drawRarityScore(_salt); // create card Card memory _card = Card({ photoId: _photoId, rarityScore: _rarityScore, holder: msg.sender }); uint256 _cardId = cards.length; cards.push(_card); playerDrawnCardIds[msg.sender].push(_cardId); playerDrawnCardIdIsHeld[msg.sender][_cardId] = true; emit CardDrawn( _cardId, _photoId, _rarityScore, msg.sender // to ); emit Transfer( _cardId, // cardId address(0), // from msg.sender // to ); } function _drawPhotoId(uint256 _photoPoolId, uint256 _salt) internal returns(uint256 _photoId) { require(isValidPoolId(_photoPoolId)); // if _photoPoolId is valid, draw from pool uint256[] storage _photoIds = photoPools[_photoPoolId].photoIds; require(_photoIds.length > 0, "There are no photos in pool"); uint256 _rand = _random(_salt); return _photoIds[ _rand.mod(_photoIds.length) ]; } function _drawRarityScore(uint256 _salt) internal returns(uint256 _rarityScore) { _rarityScore = _random(_salt) % 1000; } function _transferCard(uint256 _cardId, address _from, address _to) internal { // set card holder cards[_cardId].holder = _to; // remove card from sender (_from). The array remains the same. playerDrawnCardIdIsHeld[_from][_cardId] = false; // add card to receiver (_to) playerDrawnCardIds[_to].push(_cardId); playerDrawnCardIdIsHeld[_to][_cardId] = true; emit Transfer( _cardId, _from, _to ); } // TODO: add more entropy function _random(uint256 _salt) internal returns (uint256) { return uint256(randomnessContract.rand( keccak256( abi.encodePacked( msg.data, msg.sender, _salt ) ) )); } }
* @title SafeMath @dev Math operations with safety checks that revert on error/
library SafeMath { int256 constant private INT256_MIN = -2**255; function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function mul(int256 a, int256 b) internal pure returns (int256) { if (a == 0) { return 0; } int256 c = a * b; require(c / a == b); return c; } function mul(int256 a, int256 b) internal pure returns (int256) { if (a == 0) { return 0; } int256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function div(int256 a, int256 b) internal pure returns (int256) { int256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
954,517
[ 1, 9890, 10477, 225, 2361, 5295, 598, 24179, 4271, 716, 15226, 603, 555, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 10477, 288, 203, 565, 509, 5034, 5381, 3238, 6137, 5034, 67, 6236, 273, 300, 22, 636, 10395, 31, 203, 203, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 3639, 2583, 12, 71, 342, 279, 422, 324, 1769, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 3639, 2583, 12, 71, 342, 279, 422, 324, 1769, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 14064, 12, 474, 5034, 279, 16, 509, 5034, 324, 13, 2713, 16618, 1135, 261, 474, 5034, 13, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 203, 3639, 509, 5034, 276, 273, 279, 380, 324, 31, 203, 3639, 2583, 12, 71, 342, 279, 422, 324, 1769, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 14064, 12, 474, 5034, 279, 16, 509, 5034, 324, 13, 2713, 16618, 1135, 261, 474, 5034, 13, 288, 203, 3639, 309, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract AddChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 addPerBlock; uint256 lastRewardBlock; // Last block number that ADDs distribution occurs. uint256 accAddPerShare; // Accumulated ADD per share, times 1e12. See below. bool isStopped; // represent either pool is farming or not uint256 fromBlock; // fromBlock represent block number from which reward is going to be governed uint256 toBlock; // toBlock represent block number from which will staking will end uint256[] epochMultiplersValue; uint256[] epochMultiplers; } // The ADD TOKEN! IERC20 public addToken; // ADD tokens created per block. // uint256 public addPerBlock; // 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. // Reward Multiplier for each of three pools 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(IERC20 _addToken) public { addToken = _addToken; } function poolLength() external view returns (uint256) { return poolInfo.length; } function poolBlocksLength(uint256 _pid) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; return pool.epochMultiplers.length; } function poolMultiplierLength(uint256 _pid) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; return pool.epochMultiplersValue.length; } function poolBlocksValue(uint256 _pid, uint256 index) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; return pool.epochMultiplers[index]; } function poolMultiplierValue(uint256 _pid, uint256 index) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; return pool.epochMultiplersValue[index]; } function setAddPerBlock(uint256 _pid, uint256 _addPerBlock) public onlyOwner { massUpdatePools(); PoolInfo storage pool = poolInfo[_pid]; pool.addPerBlock = _addPerBlock; } function stopPool(uint256 _pid) public onlyOwner{ PoolInfo storage pool = poolInfo[_pid]; pool.isStopped = true; } function restartPool(uint256 _pid) public onlyOwner{ massUpdatePools(); PoolInfo storage pool = poolInfo[_pid]; pool.isStopped = false; } function addBlockAndMultiplier(uint256 _pid, uint256 _toBlock, uint256 _actualMultiplier) public onlyOwner{ PoolInfo storage pool = poolInfo[_pid]; pool.epochMultiplers.push(_toBlock); pool.epochMultiplersValue.push(_actualMultiplier); } function setFromBlock(uint256 _pid, uint256 _fromBlock) public onlyOwner{ PoolInfo storage pool = poolInfo[_pid]; pool.fromBlock = _fromBlock; } function setToBlock(uint256 _pid, uint256 _toBlock) public onlyOwner{ PoolInfo storage pool = poolInfo[_pid]; pool.toBlock = _toBlock; } function add( IERC20 _lpToken, uint256 _addPerBlock, uint256 _fromBlock, uint256[] memory _epochMultiplers, uint256[] memory _epochMultiplersValue, uint256 _toBlock ) public onlyOwner { require(address(_lpToken) != address(0), "MC: _lpToken should not be address zero"); uint256 lastRewardBlock = block.number > _fromBlock ? block.number : _fromBlock; PoolInfo memory currentPool; currentPool.lpToken = _lpToken; currentPool.addPerBlock = _addPerBlock; currentPool.fromBlock = _fromBlock; currentPool.toBlock = _toBlock; currentPool.accAddPerShare = 0; currentPool.lastRewardBlock = lastRewardBlock; currentPool.isStopped = false; currentPool.epochMultiplers = _epochMultiplers; currentPool.epochMultiplersValue = _epochMultiplersValue; poolInfo.push(currentPool); } function updateMultiplierBlock( uint256 _pid, uint8 index, uint256 _toBlock ) public onlyOwner { PoolInfo storage pool = poolInfo[_pid]; pool.epochMultiplers[index] = _toBlock; } function updateMultiplierValue( uint256 _pid, uint8 index, uint256 value ) public onlyOwner { PoolInfo storage pool = poolInfo[_pid]; pool.epochMultiplersValue[index] = value; } function getMultiplier( uint256 _pid, uint256 _from, uint256 _to ) public view returns (uint256) { /** if farming ends but pools still have blocks to farm tokens, we will allow pools to farm token until each pool tokens farmed Example Lets say Staking started at block 1 and will ends at block 200,000 and we have two Pools 1st Pool Multiplier will run from block 1 to 200,000 with value 10x 2nd Pool Multiplier will run from block 1 to 200,000 with value 30x After few days, the state of pools is as follows 1 Pool Users have farmed tokens until block 150,000 2 Pool Users have farmed tokens until block 175,000 No body entere into pool from a long time and now the block over blockchain is 210,000 but the blocks pool 1 and 2 have not processed completely so we will allow both pool users to farm tokens until faming end as per block 200,000 however only one user can proceed with transaction as the last tranaction will fill up the pools */ PoolInfo storage pool = poolInfo[_pid]; // uint256 to = _to > pool.toBlock ? pool.toBlock : _to; uint256 poolMultiplierLength = poolInfo[_pid].epochMultiplers.length; uint256 sumOfMultiplier = 0; if ( _from >= pool.epochMultiplers[poolMultiplierLength-1]){ return _to.sub(_from); } for (uint256 index = 0; index < poolMultiplierLength; index++) { if(pool.epochMultiplers[index] > _to){ sumOfMultiplier = sumOfMultiplier.add(_to.sub(_from).mul(pool.epochMultiplersValue[index])); break; } else if ( _from < pool.epochMultiplers[index] && _to >= pool.epochMultiplers[index]){ sumOfMultiplier = sumOfMultiplier.add(pool.epochMultiplers[index].sub(_from).mul(pool.epochMultiplersValue[index])); _from = pool.epochMultiplers[index]; } } if ( _to > pool.epochMultiplers[poolMultiplierLength-1]){ sumOfMultiplier = sumOfMultiplier.add(_to.sub(_from)); } return sumOfMultiplier; } // View function to see pending ADDs on frontend. function pendingAdds(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accAddPerShare = pool.accAddPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(_pid, pool.lastRewardBlock, block.number); uint256 addReward = multiplier.mul(pool.addPerBlock); accAddPerShare = accAddPerShare.add(addReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accAddPerShare).div(1e12).sub(user.rewardDebt); } // Deposit LP tokens to YaxisChef for YAX allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(pool.isStopped == false, "MC: Staking Ended, Please withdraw your tokens"); updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accAddPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeAddTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accAddPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from YaxisChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accAddPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeAddTransfer(msg.sender, pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accAddPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // 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 || pool.isStopped) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(_pid, pool.lastRewardBlock, block.number); uint256 addReward = multiplier.mul(pool.addPerBlock); // minting is not required as we already have coins in contract pool.accAddPerShare = pool.accAddPerShare.add(addReward.mul(1e12).div(lpSupply)); if (block.number >= pool.toBlock) { pool.isStopped = true; } pool.lastRewardBlock = block.number; } // Safe add transfer function, just in case if rounding error causes pool to not have enough YAXs. function safeAddTransfer(address _to, uint256 _amount) internal { uint256 addBal = addToken.balanceOf(address(this)); if (_amount > addBal) { addToken.transfer(_to, addBal); } else { addToken.transfer(_to, _amount); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
Safe add transfer function, just in case if rounding error causes pool to not have enough YAXs.
function safeAddTransfer(address _to, uint256 _amount) internal { uint256 addBal = addToken.balanceOf(address(this)); if (_amount > addBal) { addToken.transfer(_to, addBal); addToken.transfer(_to, _amount); } }
11,743,853
[ 1, 9890, 527, 7412, 445, 16, 2537, 316, 648, 309, 13885, 555, 14119, 2845, 358, 486, 1240, 7304, 1624, 2501, 87, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 986, 5912, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 2713, 288, 203, 3639, 2254, 5034, 527, 38, 287, 273, 527, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 67, 8949, 405, 527, 38, 287, 13, 288, 203, 5411, 527, 1345, 18, 13866, 24899, 869, 16, 527, 38, 287, 1769, 203, 5411, 527, 1345, 18, 13866, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT 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; import "@openzeppelin/contracts/security/Pausable.sol"; import "./interfaces/IERC1155TokenReceiver.sol"; import "./interfaces/IRefinery.sol"; import "./interfaces/IImperialGuild.sol"; import "./interfaces/IEON.sol"; import "./interfaces/IRAW.sol"; contract Refinery is IRefinery, IERC1155TokenReceiver, Pausable { struct UserInfo { uint256 amount; // how many raw materials has this user added uint256 refineEndBlock; // block your refining will be refined uint256 lastClaimBlock; // block of your last claim } /* ERC1155 Refineries what they take in and what they output at what rate struct RefineryInfo { uint8 inputType; // raw input typeID uint8 outputType; // refined resourse typeID uint8 burnRate; // rate of input burn to refined per block uint8 refineRate; // rate cut of raw to refined } */ uint256 public constant multiplier = 10**18; // keys for each refinery in operation RefineryInfo[] public refineryInfo; address public auth; // mapping(uint256 => Refinery) public RefineryInfo; //maps refineries to users mapping(uint256 => mapping(address => UserInfo)) public userRefines; // address => allowedToCallFunctions mapping(address => bool) private admins; // Deposits to specified refinery event DepositRaw(address indexed user, uint256 indexed rid, uint256 amount); // Withdraws of unrefined event WithdrawRaw( address indexed user, uint256 indexed rid, uint256 amount ); event EmergencyWithdrawRaw( address indexed user, uint256 indexed rid, uint256 amount ); IRAW public raw; IEON public eon; // emergency withdraw to allow removing unrefined without no care for the refined amount bool public emergencyActivated; constructor() { _pause(); auth = msg.sender; admins[msg.sender] = true; } modifier onlyOwner() { require(msg.sender == auth); _; } modifier requireContractsSet() { require( address(raw) != address(0) && address(eon) != address(0), "Contracts not set" ); _; } modifier noCheaters() { uint256 size = 0; address acc = msg.sender; assembly { size := extcodesize(acc) } require( admins[msg.sender] || (msg.sender == tx.origin && size == 0), "you're trying to cheat!" ); _; } function setContracts(address _raw, address _eon) external onlyOwner { raw = IRAW(_raw); eon = IEON(_eon); } /** * store information on the types of refineries * available to this refinery @param _inputType the RAW ERC1155 typeId resource @param _outputType refined output typeId * ATTENTION reserve outputType 0 for EON ERC20 * non 0 outputType points to RAW ERC1155 @param _burnRate inputType burn rate multiplied by block time dif @param _refineRate outputType rate */ function addRefinery( uint8 _inputType, uint8 _outputType, uint8 _burnRate, uint8 _refineRate ) external onlyOwner { refineryInfo.push( RefineryInfo({ inputType: _inputType, outputType: _outputType, burnRate: _burnRate, refineRate: _refineRate }) ); } // update a refinery if needed function updateRefineryInfo( uint8 _rid, uint8 _inputType, uint8 _outputType, uint8 _burnRate, uint8 _refineRate ) external onlyOwner { refineryInfo[_rid].inputType = _inputType; refineryInfo[_rid].outputType = _outputType; refineryInfo[_rid].burnRate = _burnRate; refineryInfo[_rid].refineRate = _refineRate; } function getRefineryInfo(uint256 _rid) external view returns (RefineryInfo memory) { return refineryInfo[_rid]; } // how long has the raw resource been refining for function getTimeDif(uint256 _current, uint256 _lastClaim) internal pure returns (uint256) { return (_current - _lastClaim); } // how much of the raw resource has been refined thus far // and what is the expected output of the refined function pendingRefine(uint256 _rid, address _user) external view returns (uint256 refining, uint256 refined) { RefineryInfo memory refinery = refineryInfo[_rid]; UserInfo storage user = userRefines[_rid][_user]; if (block.number < user.refineEndBlock) { uint256 timeDif = getTimeDif(block.number, user.lastClaimBlock); uint256 burnAmt = refinery.burnRate * timeDif; uint256 remaining = user.amount - burnAmt; uint256 refineRateCut = (refinery.refineRate * burnAmt) / 100; uint256 userRefined = (burnAmt - refineRateCut); return (remaining, userRefined); } else if (block.number > user.refineEndBlock) { uint256 burnAmt = user.amount; uint256 refineRateCut = (refinery.refineRate * burnAmt) / 100; uint256 userRefined = (burnAmt - refineRateCut); return (0, userRefined); } } // updating a refinery to check amounts still refining and // the output of the refined, this function is called any time // a deposit or claim is made by the user function updateRefined( uint256 _rid, uint256 _amount, address refiner ) private returns (uint256 burn, uint256 refined) { RefineryInfo memory refinery = refineryInfo[_rid]; UserInfo storage user = userRefines[_rid][refiner]; if (block.number < user.refineEndBlock) { uint256 timeDif = getTimeDif(block.number, user.lastClaimBlock); uint256 burnAmt = refinery.burnRate * timeDif; uint256 refineRateCut = (refinery.refineRate * burnAmt) / 100; uint256 refinedAmt = (burnAmt - refineRateCut); uint256 updatedRefining = (user.amount - burnAmt) + _amount; user.lastClaimBlock = block.number; user.refineEndBlock = (updatedRefining / refinery.burnRate) + block.number; user.amount = updatedRefining; return (burnAmt, refinedAmt); } else if (block.number > user.refineEndBlock && user.amount != 0) { uint256 burnAmt = user.amount; uint256 refineRateCut = ((refinery.refineRate * burnAmt) / 100); uint256 refinedAmt = (burnAmt - refineRateCut); user.lastClaimBlock = block.number; user.amount = _amount; user.refineEndBlock = (_amount / refinery.burnRate) + block.number; return (burnAmt, refinedAmt); } } /* Deposit ERC1155s to the refinery * Claims any already refined amounts for user * within this refinery id (_rid) * token id needs to be the raw.typeId of the input */ function depositRaw( uint256 _rid, uint256 _tokenId, uint256 _amount ) external whenNotPaused noCheaters { require(tx.origin == msg.sender, "Only EOA"); RefineryInfo memory refinery = refineryInfo[_rid]; UserInfo storage user = userRefines[_rid][msg.sender]; uint256 typeId = refinery.inputType; uint256 outputId = refinery.outputType; //claim if (user.amount > 0) { (uint256 burnAmt, uint256 refinedAmt) = updateRefined( _rid, _amount, msg.sender ); raw.burn(typeId, burnAmt, address(this)); if ((outputId == 0)) { uint256 mint = refinedAmt * multiplier; eon.mint(msg.sender, mint); } else { raw.mint(outputId, refinedAmt, msg.sender); } } require(_tokenId == refinery.inputType); //transfer the raw ERC1155s to this contract raw.safeTransferFrom( address(msg.sender), address(this), (refinery.inputType), _amount, "" ); //Initiate Deposit if (user.amount == 0) { // if the first depoist user.refineEndBlock = (_amount / refinery.burnRate) + block.number; user.lastClaimBlock = block.number; user.amount += _amount; } emit DepositRaw(msg.sender, _rid, _amount); } /* withdraw UNREFINED erc1155s * will withdraw the full unrefined input of user * will also claim all refined */ function withdrawRaw(uint256 _rid) external whenNotPaused noCheaters { require(tx.origin == msg.sender, "Only EOA"); RefineryInfo memory refinery = refineryInfo[_rid]; UserInfo storage user = userRefines[_rid][msg.sender]; uint256 typeId = refinery.inputType; uint256 outputId = refinery.outputType; uint8 eonType = 0; if (user.amount > 0) { (uint256 burnAmt, uint256 refinedAmt) = updateRefined( _rid, 0, msg.sender ); uint256 unrefined = (user.amount - burnAmt); user.amount = 0; raw.safeTransferFrom( address(this), msg.sender, typeId, unrefined, "" ); if (burnAmt > 0 && refinedAmt > 0) { raw.burn(typeId, burnAmt, address(this)); if ((outputId == eonType)) { eon.mint(msg.sender, refinedAmt); } else { raw.mint(outputId, refinedAmt, msg.sender); } } emit WithdrawRaw(msg.sender, _rid, unrefined); } } // Withdraw RAW resources without caring about the refined amount. EMERGENCY ONLY // Add a rescue pause enabled modifier function emergencyWithdraw(uint256 _rid) external { require(emergencyActivated, "THIS IS NOT AN EMERGENCY SITUATION"); RefineryInfo memory refinery = refineryInfo[_rid]; UserInfo storage user = userRefines[_rid][msg.sender]; uint256 typeId = refinery.inputType; uint256 unrefined = user.amount; raw.safeTransferFrom(address(this), msg.sender, typeId, unrefined, ""); // user.amount.safeTransfer(address(msg.sender), user.amount); user.amount = 0; user.lastClaimBlock = block.number; } /** admin * enables owner to active "emergency mode" * thus allow users to withdraw unrefined resouces without the refined gained */ function activateEmergency(bool _enabled) external onlyOwner { emergencyActivated = _enabled; } /** * enables owner to pause / unpause minting */ function setPaused(bool _paused) external requireContractsSet onlyOwner { if (_paused) _pause(); else _unpause(); } /** * enables an address to mint / burn * @param addr the address to enable */ function addAdmin(address addr) external onlyOwner { admins[addr] = true; } /** * disables an address from minting / burning * @param addr the address to disbale */ function removeAdmin(address addr) external onlyOwner { admins[addr] = false; } function onERC1155Received( address, address, uint256, uint256, bytes calldata ) external pure override returns (bytes4) { return IERC1155TokenReceiver.onERC1155Received.selector; } function onERC1155BatchReceived( address, address, uint256[] calldata, uint256[] calldata, bytes calldata ) external pure override returns (bytes4) { return IERC1155TokenReceiver.onERC1155Received.selector; } function supportsInterface(bytes4 interfaceId) public pure returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0xd9b67a26 || // ERC165 Interface ID for ERC1155 interfaceId == 0x0e89341c; // ERC165 Interface ID for ERC1155MetadataURI } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IEON { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); } // SPDX-License-Identifier: MIT LICENSE pragma solidity >=0.8.0; interface IERC1155TokenReceiver { function onERC1155Received( address operator, address from, uint256 id, uint256 amount, bytes calldata data ) external returns (bytes4); function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IImperialGuild { function getBalance( address account, uint256 id ) external returns(uint256); function mint( uint256 typeId, uint256 paymentId, uint16 qty, address recipient ) external; function burn( uint256 typeId, uint16 qty, address burnFrom ) external; function handlePayment(uint256 amount) external; function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) external; function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external; } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IRAW { function getBalance( address account, uint256 id ) external returns(uint256); function mint( uint256 typeId, uint256 qty, address recipient ) external; function burn( uint256 typeId, uint256 qty, address burnFrom ) external; function updateMintBurns( uint256 typeId, uint256 mintQty, uint256 burnQty ) external; function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) external; function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external; } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IRefinery { struct RefineryInfo { uint8 inputType; // raw input typeID uint8 outputType; // refined resourse typeID uint8 burnRate; // rate of input burn to refined per block uint8 refineRate; // rate cut of raw to refined } function getRefineryInfo(uint256 _rid) external view returns(RefineryInfo memory); function pendingRefine(uint256 _rid, address _user) external returns (uint256 refining, uint256 refined); function depositRaw( uint256 _rid, uint256 _tokenId, uint256 _amount ) external; function withdrawRaw(uint256 _rid) external; }
refined resourse typeID
uint8 outputType;
1,658,450
[ 1, 266, 926, 329, 400, 3117, 618, 734, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 28, 876, 559, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xa76ea481aebdd5703e476cfcb2315d4e014232c1 //Contract name: Crowdsale //Balance: 0 Ether //Verification Date: 2/27/2018 //Transacion Count: 4345 // CODE STARTS HERE pragma solidity ^0.4.17; contract J8TTokenConfig { // The J8T decimals uint8 public constant TOKEN_DECIMALS = 8; // The J8T decimal factor to obtain luckys uint256 public constant J8T_DECIMALS_FACTOR = 10**uint256(TOKEN_DECIMALS); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant 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) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { 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 > 0); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } ////////////////////////////////////////////////////////////////////// // @title J8T Token // // @dev ERC20 J8T Token // // // // J8T Tokens are divisible by 1e8 (100,000,000) base // // // // J8T are displayed using 8 decimal places of precision. // // // // 1 J8T is equivalent to 100000000 luckys: // // 100000000 == 1 * 10**8 == 1e8 == One Hundred Million luckys // // // // 1,5 Billion J8T (total supply) is equivalent to: // // 150000000000000000 == 1500000000 * 10**8 == 1,5e17 luckys // // // ////////////////////////////////////////////////////////////////////// contract J8TToken is J8TTokenConfig, BurnableToken, Ownable { string public constant name = "J8T Token"; string public constant symbol = "J8T"; uint256 public constant decimals = TOKEN_DECIMALS; uint256 public constant INITIAL_SUPPLY = 1500000000 * (10 ** uint256(decimals)); event Transfer(address indexed _from, address indexed _to, uint256 _value); function J8TToken() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; //https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1 //EIP 20: A token contract which creates new tokens SHOULD trigger a //Transfer event with the _from address set to 0x0 //when tokens are created. Transfer(0x0, msg.sender, INITIAL_SUPPLY); } } contract ACLManaged is Ownable { /////////////////////////// // ACLManaged PROPERTIES // /////////////////////////// // The operational acl address address public opsAddress; // The admin acl address address public adminAddress; //////////////////////////////////////// // ACLManaged FUNCTIONS and MODIFIERS // //////////////////////////////////////// function ACLManaged() public Ownable() {} // Updates the opsAddress propety with the new _opsAddress value function setOpsAddress(address _opsAddress) external onlyOwner returns (bool) { require(_opsAddress != address(0)); require(_opsAddress != address(this)); opsAddress = _opsAddress; return true; } // Updates the adminAddress propety with the new _adminAddress value function setAdminAddress(address _adminAddress) external onlyOwner returns (bool) { require(_adminAddress != address(0)); require(_adminAddress != address(this)); adminAddress = _adminAddress; return true; } //Checks if an address is owner function isOwner(address _address) public view returns (bool) { bool result = (_address == owner); return result; } //Checks if an address is operator function isOps(address _address) public view returns (bool) { bool result = (_address == opsAddress); return result; } //Checks if an address is ops or admin function isOpsOrAdmin(address _address) public view returns (bool) { bool result = (_address == opsAddress || _address == adminAddress); return result; } //Checks if an address is ops,owner or admin function isOwnerOrOpsOrAdmin(address _address) public view returns (bool) { bool result = (_address == opsAddress || _address == adminAddress || _address == owner); return result; } //Checks whether the msg.sender address is equal to the adminAddress property or not modifier onlyAdmin() { //Needs to be set. Default constructor will set 0x0; address _address = msg.sender; require(_address != address(0)); require(_address == adminAddress); _; } // Checks whether the msg.sender address is equal to the opsAddress property or not modifier onlyOps() { //Needs to be set. Default constructor will set 0x0; address _address = msg.sender; require(_address != address(0)); require(_address == opsAddress); _; } // Checks whether the msg.sender address is equal to the opsAddress or adminAddress property modifier onlyAdminAndOps() { //Needs to be set. Default constructor will set 0x0; address _address = msg.sender; require(_address != address(0)); require(_address == opsAddress || _address == adminAddress); _; } } contract CrowdsaleConfig is J8TTokenConfig { using SafeMath for uint256; // Default start token sale date is 28th February 15:00 SGP 2018 uint256 public constant START_TIMESTAMP = 1519801200; // Default end token sale date is 14th March 15:00 SGP 2018 uint256 public constant END_TIMESTAMP = 1521010800; // The ETH decimal factor to obtain weis uint256 public constant ETH_DECIMALS_FACTOR = 10**uint256(18); // The token sale supply uint256 public constant TOKEN_SALE_SUPPLY = 450000000 * J8T_DECIMALS_FACTOR; // The minimum contribution amount in weis uint256 public constant MIN_CONTRIBUTION_WEIS = 0.1 ether; // The maximum contribution amount in weis uint256 public constant MAX_CONTRIBUTION_WEIS = 10 ether; //@WARNING: WORKING WITH KILO-MULTIPLES TO AVOID IMPOSSIBLE DIVISIONS OF FLOATING POINTS. uint256 constant dollar_per_kilo_token = 100; //0.1 dollar per token uint256 public constant dollars_per_kilo_ether = 900000; //900$ per ether //TOKENS_PER_ETHER = dollars_per_ether / dollar_per_token uint256 public constant INITIAL_TOKENS_PER_ETHER = dollars_per_kilo_ether.div(dollar_per_kilo_token); } contract Ledger is ACLManaged { using SafeMath for uint256; /////////////////////// // Ledger PROPERTIES // /////////////////////// // The Allocation struct represents a token sale purchase // amountGranted is the amount of tokens purchased // hasClaimedBonusTokens whether the allocation has been alredy claimed struct Allocation { uint256 amountGranted; uint256 amountBonusGranted; bool hasClaimedBonusTokens; } // ContributionPhase enum cases are // PreSaleContribution, the contribution has been made in the presale phase // PartnerContribution, the contribution has been made in the private phase enum ContributionPhase { PreSaleContribution, PartnerContribution } // Map of adresses that purchased tokens on the presale phase mapping(address => Allocation) public presaleAllocations; // Map of adresses that purchased tokens on the private phase mapping(address => Allocation) public partnerAllocations; // Reference to the J8TToken contract J8TToken public tokenContract; // Reference to the Crowdsale contract Crowdsale public crowdsaleContract; // Total private allocation, counting the amount of tokens from the // partner and the presale phase uint256 public totalPrivateAllocation; // Whether the token allocations can be claimed on the partner sale phase bool public canClaimPartnerTokens; // Whether the token allocations can be claimed on the presale sale phase bool public canClaimPresaleTokens; // Whether the bonus token allocations can be claimed bool public canClaimPresaleBonusTokensPhase1; bool public canClaimPresaleBonusTokensPhase2; // Whether the bonus token allocations can be claimed bool public canClaimPartnerBonusTokensPhase1; bool public canClaimPartnerBonusTokensPhase2; /////////////////// // Ledger EVENTS // /////////////////// // Triggered when an allocation has been granted event AllocationGranted(address _contributor, uint256 _amount, uint8 _phase); // Triggered when an allocation has been revoked event AllocationRevoked(address _contributor, uint256 _amount, uint8 _phase); // Triggered when an allocation has been claimed event AllocationClaimed(address _contributor, uint256 _amount); // Triggered when a bonus allocation has been claimed event AllocationBonusClaimed(address _contributor, uint256 _amount); // Triggered when crowdsale contract updated event CrowdsaleContractUpdated(address _who, address _old_address, address _new_address); //Triggered when any can claim token boolean is updated. _type param indicates which is updated. event CanClaimTokensUpdated(address _who, string _type, bool _oldCanClaim, bool _newCanClaim); ////////////////////// // Ledger FUNCTIONS // ////////////////////// // Ledger constructor // Sets default values for canClaimPresaleTokens and canClaimPartnerTokens properties function Ledger(J8TToken _tokenContract) public { require(address(_tokenContract) != address(0)); tokenContract = _tokenContract; canClaimPresaleTokens = false; canClaimPartnerTokens = false; canClaimPresaleBonusTokensPhase1 = false; canClaimPresaleBonusTokensPhase2 = false; canClaimPartnerBonusTokensPhase1 = false; canClaimPartnerBonusTokensPhase2 = false; } function () external payable { claimTokens(); } // Revokes an allocation from the contributor with address _contributor // Deletes the allocation from the corresponding mapping property and transfers // the total amount of tokens of the allocation back to the Crowdsale contract function revokeAllocation(address _contributor, uint8 _phase) public onlyAdminAndOps payable returns (uint256) { require(_contributor != address(0)); require(_contributor != address(this)); // Can't revoke an allocation if the contribution phase is not in the ContributionPhase enum ContributionPhase _contributionPhase = ContributionPhase(_phase); require(_contributionPhase == ContributionPhase.PreSaleContribution || _contributionPhase == ContributionPhase.PartnerContribution); uint256 grantedAllocation = 0; // Deletes the allocation from the respective mapping if (_contributionPhase == ContributionPhase.PreSaleContribution) { grantedAllocation = presaleAllocations[_contributor].amountGranted.add(presaleAllocations[_contributor].amountBonusGranted); delete presaleAllocations[_contributor]; } else if (_contributionPhase == ContributionPhase.PartnerContribution) { grantedAllocation = partnerAllocations[_contributor].amountGranted.add(partnerAllocations[_contributor].amountBonusGranted); delete partnerAllocations[_contributor]; } // The granted amount allocation must be less that the current token supply on the contract uint256 currentSupply = tokenContract.balanceOf(address(this)); require(grantedAllocation <= currentSupply); // Updates the total private allocation substracting the amount of tokens that has been revoked require(grantedAllocation <= totalPrivateAllocation); totalPrivateAllocation = totalPrivateAllocation.sub(grantedAllocation); // We sent back the amount of tokens that has been revoked to the corwdsale contract require(tokenContract.transfer(address(crowdsaleContract), grantedAllocation)); AllocationRevoked(_contributor, grantedAllocation, _phase); return grantedAllocation; } // Adds a new allocation for the contributor with address _contributor function addAllocation(address _contributor, uint256 _amount, uint256 _bonus, uint8 _phase) public onlyAdminAndOps returns (bool) { require(_contributor != address(0)); require(_contributor != address(this)); // Can't create or update an allocation if the amount of tokens to be allocated is not greater than zero require(_amount > 0); // Can't create an allocation if the contribution phase is not in the ContributionPhase enum ContributionPhase _contributionPhase = ContributionPhase(_phase); require(_contributionPhase == ContributionPhase.PreSaleContribution || _contributionPhase == ContributionPhase.PartnerContribution); uint256 totalAmount = _amount.add(_bonus); uint256 totalGrantedAllocation = 0; uint256 totalGrantedBonusAllocation = 0; // Fetch the allocation from the respective mapping and updates the granted amount of tokens if (_contributionPhase == ContributionPhase.PreSaleContribution) { totalGrantedAllocation = presaleAllocations[_contributor].amountGranted.add(_amount); totalGrantedBonusAllocation = presaleAllocations[_contributor].amountBonusGranted.add(_bonus); presaleAllocations[_contributor] = Allocation(totalGrantedAllocation, totalGrantedBonusAllocation, false); } else if (_contributionPhase == ContributionPhase.PartnerContribution) { totalGrantedAllocation = partnerAllocations[_contributor].amountGranted.add(_amount); totalGrantedBonusAllocation = partnerAllocations[_contributor].amountBonusGranted.add(_bonus); partnerAllocations[_contributor] = Allocation(totalGrantedAllocation, totalGrantedBonusAllocation, false); } // Updates the contract data totalPrivateAllocation = totalPrivateAllocation.add(totalAmount); AllocationGranted(_contributor, totalAmount, _phase); return true; } // The claimTokens() function handles the contribution token claim. // Tokens can only be claimed after we open this phase. // The lockouts periods are defined by the foundation. // There are 2 different lockouts: // Presale lockout // Partner lockout // // A contributor that has contributed in all the phases can claim // all its tokens, but only the ones that are accesible to claim // be transfered. // // A contributor can claim its tokens after each phase has been opened function claimTokens() public payable returns (bool) { require(msg.sender != address(0)); require(msg.sender != address(this)); uint256 amountToTransfer = 0; // We need to check if the contributor has made a contribution on each // phase, presale and partner Allocation storage presaleA = presaleAllocations[msg.sender]; if (presaleA.amountGranted > 0 && canClaimPresaleTokens) { amountToTransfer = amountToTransfer.add(presaleA.amountGranted); presaleA.amountGranted = 0; } Allocation storage partnerA = partnerAllocations[msg.sender]; if (partnerA.amountGranted > 0 && canClaimPartnerTokens) { amountToTransfer = amountToTransfer.add(partnerA.amountGranted); partnerA.amountGranted = 0; } // The amount to transfer must greater than zero require(amountToTransfer > 0); // The amount to transfer must be less or equal to the current supply uint256 currentSupply = tokenContract.balanceOf(address(this)); require(amountToTransfer <= currentSupply); // Transfer the token allocation to contributor require(tokenContract.transfer(msg.sender, amountToTransfer)); AllocationClaimed(msg.sender, amountToTransfer); return true; } function claimBonus() external payable returns (bool) { require(msg.sender != address(0)); require(msg.sender != address(this)); uint256 amountToTransfer = 0; // BONUS PHASE 1 Allocation storage presale = presaleAllocations[msg.sender]; if (presale.amountBonusGranted > 0 && !presale.hasClaimedBonusTokens && canClaimPresaleBonusTokensPhase1) { uint256 amountPresale = presale.amountBonusGranted.div(2); amountToTransfer = amountPresale; presale.amountBonusGranted = amountPresale; presale.hasClaimedBonusTokens = true; } Allocation storage partner = partnerAllocations[msg.sender]; if (partner.amountBonusGranted > 0 && !partner.hasClaimedBonusTokens && canClaimPartnerBonusTokensPhase1) { uint256 amountPartner = partner.amountBonusGranted.div(2); amountToTransfer = amountToTransfer.add(amountPartner); partner.amountBonusGranted = amountPartner; partner.hasClaimedBonusTokens = true; } // BONUS PHASE 2 if (presale.amountBonusGranted > 0 && canClaimPresaleBonusTokensPhase2) { amountToTransfer = amountToTransfer.add(presale.amountBonusGranted); presale.amountBonusGranted = 0; } if (partner.amountBonusGranted > 0 && canClaimPartnerBonusTokensPhase2) { amountToTransfer = amountToTransfer.add(partner.amountBonusGranted); partner.amountBonusGranted = 0; } // The amount to transfer must greater than zero require(amountToTransfer > 0); // The amount to transfer must be less or equal to the current supply uint256 currentSupply = tokenContract.balanceOf(address(this)); require(amountToTransfer <= currentSupply); // Transfer the token allocation to contributor require(tokenContract.transfer(msg.sender, amountToTransfer)); AllocationBonusClaimed(msg.sender, amountToTransfer); return true; } // Updates the canClaimPresaleTokens propety with the new _canClaimTokens value function setCanClaimPresaleTokens(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPresaleTokens; canClaimPresaleTokens = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPresaleTokens', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimPartnerTokens property with the new _canClaimTokens value function setCanClaimPartnerTokens(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPartnerTokens; canClaimPartnerTokens = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPartnerTokens', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimBonusTokens property with the new _canClaimTokens value function setCanClaimPresaleBonusTokensPhase1(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPresaleBonusTokensPhase1; canClaimPresaleBonusTokensPhase1 = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPresaleBonusTokensPhase1', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimBonusTokens property with the new _canClaimTokens value function setCanClaimPresaleBonusTokensPhase2(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPresaleBonusTokensPhase2; canClaimPresaleBonusTokensPhase2 = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPresaleBonusTokensPhase2', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimBonusTokens property with the new _canClaimTokens value function setCanClaimPartnerBonusTokensPhase1(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPartnerBonusTokensPhase1; canClaimPartnerBonusTokensPhase1 = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPartnerBonusTokensPhase1', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimBonusTokens property with the new _canClaimTokens value function setCanClaimPartnerBonusTokensPhase2(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPartnerBonusTokensPhase2; canClaimPartnerBonusTokensPhase2 = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPartnerBonusTokensPhase2', _oldCanClaim, _canClaimTokens); return true; } // Updates the crowdsale contract property with the new _crowdsaleContract value function setCrowdsaleContract(Crowdsale _crowdsaleContract) public onlyOwner returns (bool) { address old_crowdsale_address = crowdsaleContract; crowdsaleContract = _crowdsaleContract; CrowdsaleContractUpdated(msg.sender, old_crowdsale_address, crowdsaleContract); return true; } } contract Crowdsale is ACLManaged, CrowdsaleConfig { using SafeMath for uint256; ////////////////////////// // Crowdsale PROPERTIES // ////////////////////////// // The J8TToken smart contract reference J8TToken public tokenContract; // The Ledger smart contract reference Ledger public ledgerContract; // The start token sale date represented as a timestamp uint256 public startTimestamp; // The end token sale date represented as a timestamp uint256 public endTimestamp; // Ratio of J8T tokens to per ether uint256 public tokensPerEther; // The total amount of wei raised in the token sale // Including presales (in eth) and public sale uint256 public weiRaised; // The current total amount of tokens sold in the token sale uint256 public totalTokensSold; // The minimum and maximum eth contribution accepted in the token sale uint256 public minContribution; uint256 public maxContribution; // The wallet address where the token sale sends all eth contributions address public wallet; // Controls whether the token sale has finished or not bool public isFinalized = false; // Map of adresses that requested to purchase tokens // Contributors of the token sale are segmented as: // CannotContribute: Cannot contribute in any phase (uint8 - 0) // PreSaleContributor: Can contribute on both pre-sale and pubic sale phases (uint8 - 1) // PublicSaleContributor: Can contribute on he public sale phase (uint8 - 2) mapping(address => WhitelistPermission) public whitelist; // Map of addresses that has already contributed on the token sale mapping(address => bool) public hasContributed; enum WhitelistPermission { CannotContribute, PreSaleContributor, PublicSaleContributor } ////////////////////// // Crowdsale EVENTS // ////////////////////// // Triggered when a contribution in the public sale has been processed correctly event TokensPurchased(address _contributor, uint256 _amount); // Triggered when the whitelist has been updated event WhiteListUpdated(address _who, address _account, WhitelistPermission _phase); // Triggered when the Crowdsale has been created event ContractCreated(); // Triggered when a presale has been added // The phase parameter can be a strategic partner contribution or a presale contribution event PresaleAdded(address _contributor, uint256 _amount, uint8 _phase); // Triggered when the tokensPerEther property has been updated event TokensPerEtherUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the startTimestamp property has been updated event StartTimestampUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the endTimestamp property has been updated event EndTimestampUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the wallet property has been updated event WalletUpdated(address _who, address _oldWallet, address _newWallet); // Triggered when the minContribution property has been updated event MinContributionUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the maxContribution property has been updated event MaxContributionUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the token sale has finalized event Finalized(address _who, uint256 _timestamp); // Triggered when the token sale has finalized and there where still token to sale // When the token are not sold, we burn them event Burned(address _who, uint256 _amount, uint256 _timestamp); ///////////////////////// // Crowdsale FUNCTIONS // ///////////////////////// // Crowdsale constructor // Takes default values from the CrowdsaleConfig smart contract function Crowdsale( J8TToken _tokenContract, Ledger _ledgerContract, address _wallet ) public { uint256 _start = START_TIMESTAMP; uint256 _end = END_TIMESTAMP; uint256 _supply = TOKEN_SALE_SUPPLY; uint256 _min_contribution = MIN_CONTRIBUTION_WEIS; uint256 _max_contribution = MAX_CONTRIBUTION_WEIS; uint256 _tokensPerEther = INITIAL_TOKENS_PER_ETHER; require(_start > currentTime()); require(_end > _start); require(_tokensPerEther > 0); require(address(_tokenContract) != address(0)); require(address(_ledgerContract) != address(0)); require(_wallet != address(0)); ledgerContract = _ledgerContract; tokenContract = _tokenContract; startTimestamp = _start; endTimestamp = _end; tokensPerEther = _tokensPerEther; minContribution = _min_contribution; maxContribution = _max_contribution; wallet = _wallet; totalTokensSold = 0; weiRaised = 0; isFinalized = false; ContractCreated(); } // Updates the tokenPerEther propety with the new _tokensPerEther value function setTokensPerEther(uint256 _tokensPerEther) external onlyAdmin onlyBeforeSale returns (bool) { require(_tokensPerEther > 0); uint256 _oldValue = tokensPerEther; tokensPerEther = _tokensPerEther; TokensPerEtherUpdated(msg.sender, _oldValue, tokensPerEther); return true; } // Updates the startTimestamp propety with the new _start value function setStartTimestamp(uint256 _start) external onlyAdmin returns (bool) { require(_start < endTimestamp); require(_start > currentTime()); uint256 _oldValue = startTimestamp; startTimestamp = _start; StartTimestampUpdated(msg.sender, _oldValue, startTimestamp); return true; } // Updates the endTimestamp propety with the new _end value function setEndTimestamp(uint256 _end) external onlyAdmin returns (bool) { require(_end > startTimestamp); uint256 _oldValue = endTimestamp; endTimestamp = _end; EndTimestampUpdated(msg.sender, _oldValue, endTimestamp); return true; } // Updates the wallet propety with the new _newWallet value function updateWallet(address _newWallet) external onlyAdmin returns (bool) { require(_newWallet != address(0)); address _oldValue = wallet; wallet = _newWallet; WalletUpdated(msg.sender, _oldValue, wallet); return true; } // Updates the minContribution propety with the new _newMinControbution value function setMinContribution(uint256 _newMinContribution) external onlyAdmin returns (bool) { require(_newMinContribution <= maxContribution); uint256 _oldValue = minContribution; minContribution = _newMinContribution; MinContributionUpdated(msg.sender, _oldValue, minContribution); return true; } // Updates the maxContribution propety with the new _newMaxContribution value function setMaxContribution(uint256 _newMaxContribution) external onlyAdmin returns (bool) { require(_newMaxContribution > minContribution); uint256 _oldValue = maxContribution; maxContribution = _newMaxContribution; MaxContributionUpdated(msg.sender, _oldValue, maxContribution); return true; } // Main public function. function () external payable { purchaseTokens(); } // Revokes a presale allocation from the contributor with address _contributor // Updates the totalTokensSold property substracting the amount of tokens that where previously allocated function revokePresale(address _contributor, uint8 _contributorPhase) external onlyAdmin returns (bool) { require(_contributor != address(0)); // We can only revoke allocations from pre sale or strategic partners // ContributionPhase.PreSaleContribution == 0, ContributionPhase.PartnerContribution == 1 require(_contributorPhase == 0 || _contributorPhase == 1); uint256 luckys = ledgerContract.revokeAllocation(_contributor, _contributorPhase); require(luckys > 0); require(luckys <= totalTokensSold); totalTokensSold = totalTokensSold.sub(luckys); return true; } // Adds a new presale allocation for the contributor with address _contributor // We can only allocate presale before the token sale has been initialized function addPresale(address _contributor, uint256 _tokens, uint256 _bonus, uint8 _contributorPhase) external onlyAdminAndOps onlyBeforeSale returns (bool) { require(_tokens > 0); require(_bonus > 0); // Converts the amount of tokens to our smallest J8T value, lucky uint256 luckys = _tokens.mul(J8T_DECIMALS_FACTOR); uint256 bonusLuckys = _bonus.mul(J8T_DECIMALS_FACTOR); uint256 totalTokens = luckys.add(bonusLuckys); uint256 availableTokensToPurchase = tokenContract.balanceOf(address(this)); require(totalTokens <= availableTokensToPurchase); // Insert the new allocation to the Ledger require(ledgerContract.addAllocation(_contributor, luckys, bonusLuckys, _contributorPhase)); // Transfers the tokens form the Crowdsale contract to the Ledger contract require(tokenContract.transfer(address(ledgerContract), totalTokens)); // Updates totalTokensSold property totalTokensSold = totalTokensSold.add(totalTokens); // If we reach the total amount of tokens to sell we finilize the token sale availableTokensToPurchase = tokenContract.balanceOf(address(this)); if (availableTokensToPurchase == 0) { finalization(); } // Trigger PresaleAdded event PresaleAdded(_contributor, totalTokens, _contributorPhase); } // The purchaseTokens function handles the token purchase flow function purchaseTokens() public payable onlyDuringSale returns (bool) { address contributor = msg.sender; uint256 weiAmount = msg.value; // A contributor can only contribute once on the public sale require(hasContributed[contributor] == false); // The contributor address must be whitelisted in order to be able to purchase tokens require(contributorCanContribute(contributor)); // The weiAmount must be greater or equal than minContribution require(weiAmount >= minContribution); // The weiAmount cannot be greater than maxContribution require(weiAmount <= maxContribution); // The availableTokensToPurchase must be greater than 0 require(totalTokensSold < TOKEN_SALE_SUPPLY); uint256 availableTokensToPurchase = TOKEN_SALE_SUPPLY.sub(totalTokensSold); // We need to convert the tokensPerEther to luckys (10**8) uint256 luckyPerEther = tokensPerEther.mul(J8T_DECIMALS_FACTOR); // In order to calculate the tokens amount to be allocated to the contrbutor // we need to multiply the amount of wei sent by luckyPerEther and divide the // result for the ether decimal factor (10**18) uint256 tokensAmount = weiAmount.mul(luckyPerEther).div(ETH_DECIMALS_FACTOR); uint256 refund = 0; uint256 tokensToPurchase = tokensAmount; // If the token purchase amount is bigger than the remaining token allocation // we can only sell the remainging tokens and refund the unused amount of eth if (availableTokensToPurchase < tokensAmount) { tokensToPurchase = availableTokensToPurchase; weiAmount = tokensToPurchase.mul(ETH_DECIMALS_FACTOR).div(luckyPerEther); refund = msg.value.sub(weiAmount); } // We update the token sale contract data totalTokensSold = totalTokensSold.add(tokensToPurchase); uint256 weiToPurchase = tokensToPurchase.div(tokensPerEther); weiRaised = weiRaised.add(weiToPurchase); // Transfers the tokens form the Crowdsale contract to contriutors wallet require(tokenContract.transfer(contributor, tokensToPurchase)); // Issue a refund for any unused ether if (refund > 0) { contributor.transfer(refund); } // Transfer ether contribution to the wallet wallet.transfer(weiAmount); // Update hasContributed mapping hasContributed[contributor] = true; TokensPurchased(contributor, tokensToPurchase); // If we reach the total amount of tokens to sell we finilize the token sale if (totalTokensSold == TOKEN_SALE_SUPPLY) { finalization(); } return true; } // Updates the whitelist function updateWhitelist(address _account, WhitelistPermission _permission) external onlyAdminAndOps returns (bool) { require(_account != address(0)); require(_permission == WhitelistPermission.PreSaleContributor || _permission == WhitelistPermission.PublicSaleContributor || _permission == WhitelistPermission.CannotContribute); require(!saleHasFinished()); whitelist[_account] = _permission; address _who = msg.sender; WhiteListUpdated(_who, _account, _permission); return true; } function updateWhitelist_batch(address[] _accounts, WhitelistPermission _permission) external onlyAdminAndOps returns (bool) { require(_permission == WhitelistPermission.PreSaleContributor || _permission == WhitelistPermission.PublicSaleContributor || _permission == WhitelistPermission.CannotContribute); require(!saleHasFinished()); for(uint i = 0; i < _accounts.length; ++i) { require(_accounts[i] != address(0)); whitelist[_accounts[i]] = _permission; WhiteListUpdated(msg.sender, _accounts[i], _permission); } return true; } // Checks that the status of an address account // Contributors of the token sale are segmented as: // PreSaleContributor: Can contribute on both pre-sale and pubic sale phases // PublicSaleContributor: Can contribute on he public sale phase // CannotContribute: Cannot contribute in any phase function contributorCanContribute(address _contributorAddress) private view returns (bool) { WhitelistPermission _contributorPhase = whitelist[_contributorAddress]; if (_contributorPhase == WhitelistPermission.CannotContribute) { return false; } if (_contributorPhase == WhitelistPermission.PreSaleContributor || _contributorPhase == WhitelistPermission.PublicSaleContributor) { return true; } return false; } // Returns the current time function currentTime() public view returns (uint256) { return now; } // Checks if the sale has finished function saleHasFinished() public view returns (bool) { if (isFinalized) { return true; } if (endTimestamp < currentTime()) { return true; } if (totalTokensSold == TOKEN_SALE_SUPPLY) { return true; } return false; } modifier onlyBeforeSale() { require(currentTime() < startTimestamp); _; } modifier onlyDuringSale() { uint256 _currentTime = currentTime(); require(startTimestamp < _currentTime); require(_currentTime < endTimestamp); _; } modifier onlyPostSale() { require(endTimestamp < currentTime()); _; } /////////////////////// // PRIVATE FUNCTIONS // /////////////////////// // This method is for to be called only for the owner. This way we protect for anyone who wanna finalize the ICO. function finalize() external onlyAdmin returns (bool) { return finalization(); } // Only used by finalize and setFinalized. // Overloaded logic for two uses. // NOTE: In case finalize is called by an user and not from addPresale()/purchaseToken() // will diff total supply with sold supply to burn token. function finalization() private returns (bool) { require(!isFinalized); isFinalized = true; if (totalTokensSold < TOKEN_SALE_SUPPLY) { uint256 toBurn = TOKEN_SALE_SUPPLY.sub(totalTokensSold); tokenContract.burn(toBurn); Burned(msg.sender, toBurn, currentTime()); } Finalized(msg.sender, currentTime()); return true; } function saleSupply() public view returns (uint256) { return tokenContract.balanceOf(address(this)); } }
Updates the minContribution propety with the new _newMinControbution value
function setMinContribution(uint256 _newMinContribution) external onlyAdmin returns (bool) { require(_newMinContribution <= maxContribution); uint256 _oldValue = minContribution; minContribution = _newMinContribution; MinContributionUpdated(msg.sender, _oldValue, minContribution); return true; }
2,480,465
[ 1, 5121, 326, 1131, 442, 4027, 2270, 14369, 598, 326, 394, 389, 2704, 2930, 660, 303, 70, 1421, 460, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 27724, 442, 4027, 12, 11890, 5034, 389, 2704, 2930, 442, 4027, 13, 3903, 1338, 4446, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 24899, 2704, 2930, 442, 4027, 1648, 943, 442, 4027, 1769, 203, 203, 3639, 2254, 5034, 389, 1673, 620, 273, 1131, 442, 4027, 31, 203, 3639, 1131, 442, 4027, 273, 389, 2704, 2930, 442, 4027, 31, 203, 540, 203, 3639, 5444, 442, 4027, 7381, 12, 3576, 18, 15330, 16, 389, 1673, 620, 16, 1131, 442, 4027, 1769, 203, 540, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xa5b8BBdaE8739C0EfA98Ca2d46B93D8C7C1408da/sources/Cryptoz.sol
ALL CLEAR - grab a random number
uint rand = selectRandom(10000);
15,890,157
[ 1, 4685, 385, 900, 985, 300, 11086, 279, 2744, 1300, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5605, 273, 2027, 8529, 12, 23899, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x1683F59e40f20c86a13400BE37d2C437CE03298C/sources/strategy/AdvanceStrategy.sol
A template for don-key strategies. Parts of the contract that the writer needs to add are numbered below. Writer only needs to add relevent parts to the existing code. The writer needs to add the following things: 1. Interfaces to other contracts 2. Description of strategy. Can be as given by the farmer 3. Relevent addresses in the contract 4. Contract instances that will be used in the contract 5. Tokens that will be approved in the contract creation. This means tokens that other contracts will be able to take from this contract to the maximum amount. 6. Invest function. This will invest in the different protocols in the order of the strategy 7. Harvest funciont. This will check if the pool has 10% of the total value. If it has less it will withdraw Money/take the money from the Harvest and send it to complete to 10%. If there is more it will transfer the extra money to the strategy and reinvest it with all the extra money harvested 8. totalValue function. Will return the total value in BUSD invested in the protocols 9. totalRewards function. Will return the total rewards in BUSD that the strategy should get if it will harvest 10. Withdraw function. Will withdraw a specific amount from the protocols./-----------------------Interfaces------------------------------------------ Context,Ownable Implementations are in all strategies. IBEP20,Pancakeswap interfaces are in all strategies./ @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./ Empty internal constructor, to prevent people from mistakenly deploying an instance of this contract, which should be used via inheritance.
abstract contract Context { pragma solidity ^0.6.9; constructor() internal {} function _msgSender() internal view returns (address) { return msg.sender; } function _msgData() internal view returns (bytes memory) { return msg.data; } }
4,692,519
[ 1, 37, 1542, 364, 2727, 17, 856, 20417, 18, 28195, 434, 326, 6835, 716, 326, 2633, 4260, 358, 527, 854, 1300, 329, 5712, 18, 5497, 1338, 4260, 358, 527, 6707, 616, 2140, 358, 326, 2062, 981, 18, 1021, 2633, 4260, 358, 527, 326, 3751, 9198, 30, 404, 18, 27152, 358, 1308, 20092, 576, 18, 6507, 434, 6252, 18, 4480, 506, 487, 864, 635, 326, 284, 4610, 264, 890, 18, 4275, 2575, 6138, 316, 326, 6835, 1059, 18, 13456, 3884, 716, 903, 506, 1399, 316, 326, 6835, 1381, 18, 13899, 716, 903, 506, 20412, 316, 326, 6835, 6710, 18, 1220, 4696, 2430, 716, 1308, 20092, 565, 903, 506, 7752, 358, 4862, 628, 333, 6835, 358, 326, 4207, 3844, 18, 1666, 18, 5454, 395, 445, 18, 1220, 903, 2198, 395, 316, 326, 3775, 16534, 316, 326, 1353, 434, 326, 6252, 2371, 18, 670, 297, 26923, 1326, 285, 88, 18, 1220, 903, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 17801, 6835, 1772, 288, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 29, 31, 203, 565, 3885, 1435, 2713, 2618, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 751, 1435, 2713, 1476, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 1234, 18, 892, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; abstract contract IDFSRegistry { function getAddr(bytes32 _id) public view virtual returns (address); function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public virtual; function startContractChange(bytes32 _id, address _newContractAddr) public virtual; function approveContractChange(bytes32 _id) public virtual; function cancelContractChange(bytes32 _id) public virtual; function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual; } interface IERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } 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 * {ERC20-approve}, and its usage is discouraged. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract AdminVault { address public owner; address public admin; constructor() { owner = msg.sender; admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function changeOwner(address _owner) public { require(admin == msg.sender, "msg.sender not admin"); owner = _owner; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function changeAdmin(address _admin) public { require(admin == msg.sender, "msg.sender not admin"); admin = _admin; } } /// @title AdminAuth Handles owner/admin priviligies over smart contracts contract AdminAuth { using SafeERC20 for IERC20; AdminVault public adminVault = AdminVault(0xCCf3d848e08b94478Ed8f46fFead3008faF581fD); modifier onlyOwner() { require(adminVault.owner() == msg.sender, "msg.sender not owner"); _; } modifier onlyAdmin() { require(adminVault.admin() == msg.sender, "msg.sender not admin"); _; } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(_receiver).transfer(_amount); } else { IERC20(_token).safeTransfer(_receiver, _amount); } } /// @notice Destroy the contract function kill() public onlyAdmin { selfdestruct(payable(msg.sender)); } /// @notice Changes the admin vault that is currently used /// @param _newAdminVault Address of the new Admin Vault contract function changeAdminVault(address _newAdminVault) public onlyAdmin { adminVault = AdminVault(_newAdminVault); } } contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log( address _contract, address _caller, string memory _logName, bytes memory _data ) public { emit LogEvent(_contract, _caller, _logName, _data); } } /// @title Stores all the important DFS addresses and can be changed (timelock) contract DFSRegistry is AdminAuth { DefisaverLogger public constant logger = DefisaverLogger( 0x5c55B921f590a89C1Ebe84dF170E655a82b62126 ); string public constant ERR_ENTRY_ALREADY_EXISTS = "Entry id already exists"; string public constant ERR_ENTRY_NON_EXISTENT = "Entry id doesn't exists"; string public constant ERR_ENTRY_NOT_IN_CHANGE = "Entry not in change process"; string public constant ERR_WAIT_PERIOD_SHORTER = "New wait period must be bigger"; string public constant ERR_CHANGE_NOT_READY = "Change not ready yet"; string public constant ERR_EMPTY_PREV_ADDR = "Previous addr is 0"; string public constant ERR_ALREADY_IN_CONTRACT_CHANGE = "Already in contract change"; string public constant ERR_ALREADY_IN_WAIT_PERIOD_CHANGE = "Already in wait period change"; struct Entry { address contractAddr; uint256 waitPeriod; uint256 changeStartTime; bool inContractChange; bool inWaitPeriodChange; bool exists; } mapping(bytes32 => Entry) public entries; mapping(bytes32 => address) public previousAddresses; mapping(bytes32 => address) public pendingAddresses; mapping(bytes32 => uint256) public pendingWaitTimes; /// @notice Given an contract id returns the registred address /// @dev Id is keccak256 of the contract name /// @param _id Id of contract function getAddr(bytes32 _id) public view returns (address) { return entries[_id].contractAddr; } /// @notice Helper function to easily query if id is registred /// @param _id Id of contract function isRegistered(bytes32 _id) public view returns (bool) { return entries[_id].exists; } /////////////////////////// OWNER ONLY FUNCTIONS /////////////////////////// /// @notice Adds a new contract to the registry /// @param _id Id of contract /// @param _contractAddr Address of the contract /// @param _waitPeriod Amount of time to wait before a contract address can be changed function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public onlyOwner { require(!entries[_id].exists, ERR_ENTRY_ALREADY_EXISTS); entries[_id] = Entry({ contractAddr: _contractAddr, waitPeriod: _waitPeriod, changeStartTime: 0, inContractChange: false, inWaitPeriodChange: false, exists: true }); // Remember tha address so we can revert back to old addr if needed previousAddresses[_id] = _contractAddr; logger.Log( address(this), msg.sender, "AddNewContract", abi.encode(_id, _contractAddr, _waitPeriod) ); } /// @notice Revertes to the previous address immediately /// @dev In case the new version has a fault, a quick way to fallback to the old contract /// @param _id Id of contract function revertToPreviousAddress(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(previousAddresses[_id] != address(0), ERR_EMPTY_PREV_ADDR); address currentAddr = entries[_id].contractAddr; entries[_id].contractAddr = previousAddresses[_id]; logger.Log( address(this), msg.sender, "RevertToPreviousAddress", abi.encode(_id, currentAddr, previousAddresses[_id]) ); } /// @notice Starts an address change for an existing entry /// @dev Can override a change that is currently in progress /// @param _id Id of contract /// @param _newContractAddr Address of the new contract function startContractChange(bytes32 _id, address _newContractAddr) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inWaitPeriodChange, ERR_ALREADY_IN_WAIT_PERIOD_CHANGE); entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inContractChange = true; pendingAddresses[_id] = _newContractAddr; logger.Log( address(this), msg.sender, "StartContractChange", abi.encode(_id, entries[_id].contractAddr, _newContractAddr) ); } /// @notice Changes new contract address, correct time must have passed /// @param _id Id of contract function approveContractChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE); require( block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line ERR_CHANGE_NOT_READY ); address oldContractAddr = entries[_id].contractAddr; entries[_id].contractAddr = pendingAddresses[_id]; entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; pendingAddresses[_id] = address(0); previousAddresses[_id] = oldContractAddr; logger.Log( address(this), msg.sender, "ApproveContractChange", abi.encode(_id, oldContractAddr, entries[_id].contractAddr) ); } /// @notice Cancel pending change /// @param _id Id of contract function cancelContractChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE); address oldContractAddr = pendingAddresses[_id]; pendingAddresses[_id] = address(0); entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; logger.Log( address(this), msg.sender, "CancelContractChange", abi.encode(_id, oldContractAddr, entries[_id].contractAddr) ); } /// @notice Starts the change for waitPeriod /// @param _id Id of contract /// @param _newWaitPeriod New wait time function startWaitPeriodChange(bytes32 _id, uint256 _newWaitPeriod) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inContractChange, ERR_ALREADY_IN_CONTRACT_CHANGE); pendingWaitTimes[_id] = _newWaitPeriod; entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inWaitPeriodChange = true; logger.Log( address(this), msg.sender, "StartWaitPeriodChange", abi.encode(_id, _newWaitPeriod) ); } /// @notice Changes new wait period, correct time must have passed /// @param _id Id of contract function approveWaitPeriodChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE); require( block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line ERR_CHANGE_NOT_READY ); uint256 oldWaitTime = entries[_id].waitPeriod; entries[_id].waitPeriod = pendingWaitTimes[_id]; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; pendingWaitTimes[_id] = 0; logger.Log( address(this), msg.sender, "ApproveWaitPeriodChange", abi.encode(_id, oldWaitTime, entries[_id].waitPeriod) ); } /// @notice Cancel wait period change /// @param _id Id of contract function cancelWaitPeriodChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE); uint256 oldWaitPeriod = pendingWaitTimes[_id]; pendingWaitTimes[_id] = 0; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; logger.Log( address(this), msg.sender, "CancelWaitPeriodChange", abi.encode(_id, oldWaitPeriod, entries[_id].waitPeriod) ); } } /// @title Implements Action interface and common helpers for pasing inputs abstract contract ActionBase { address public constant REGISTRY_ADDR = 0xB0e1682D17A96E8551191c089673346dF7e1D467; DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR); DefisaverLogger public constant logger = DefisaverLogger( 0x5c55B921f590a89C1Ebe84dF170E655a82b62126 ); string public constant ERR_SUB_INDEX_VALUE = "Wrong sub index value"; string public constant ERR_RETURN_INDEX_VALUE = "Wrong return index value"; /// @dev Subscription params index range [128, 255] uint8 public constant SUB_MIN_INDEX_VALUE = 128; uint8 public constant SUB_MAX_INDEX_VALUE = 255; /// @dev Return params index range [1, 127] uint8 public constant RETURN_MIN_INDEX_VALUE = 1; uint8 public constant RETURN_MAX_INDEX_VALUE = 127; /// @dev If the input value should not be replaced uint8 public constant NO_PARAM_MAPPING = 0; /// @dev We need to parse Flash loan actions in a different way enum ActionType { FL_ACTION, STANDARD_ACTION, CUSTOM_ACTION } /// @notice Parses inputs and runs the implemented action through a proxy /// @dev Is called by the TaskExecutor chaining actions together /// @param _callData Array of input values each value encoded as bytes /// @param _subData Array of subscribed vales, replaces input values if specified /// @param _paramMapping Array that specifies how return and subscribed values are mapped in input /// @param _returnValues Returns values from actions before, which can be injected in inputs /// @return Returns a bytes32 value through DSProxy, each actions implements what that value is function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual returns (bytes32); /// @notice Parses inputs and runs the single implemented action through a proxy /// @dev Used to save gas when executing a single action directly function executeActionDirect(bytes[] memory _callData) public virtual payable; /// @notice Returns the type of action we are implementing function actionType() public pure virtual returns (uint8); //////////////////////////// HELPER METHODS //////////////////////////// /// @notice Given an uint256 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can repacle the input value with /// @param _returnValues Array of subscription data we can repacle the input value with function _parseParamUint( uint _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (uint) { if (isReplacable(_mapType)) { if (isReturnInjection(_mapType)) { _param = uint(_returnValues[getReturnIndex(_mapType)]); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (uint)); } } return _param; } /// @notice Given an addr input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can repacle the input value with /// @param _returnValues Array of subscription data we can repacle the input value with function _parseParamAddr( address _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (address) { if (isReplacable(_mapType)) { if (isReturnInjection(_mapType)) { _param = address(bytes20((_returnValues[getReturnIndex(_mapType)]))); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (address)); } } return _param; } /// @notice Given an bytes32 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can repacle the input value with /// @param _returnValues Array of subscription data we can repacle the input value with function _parseParamABytes32( bytes32 _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (bytes32) { if (isReplacable(_mapType)) { if (isReturnInjection(_mapType)) { _param = (_returnValues[getReturnIndex(_mapType)]); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (bytes32)); } } return _param; } /// @notice Checks if the paramMapping value indicated that we need to inject values /// @param _type Indicated the type of the input function isReplacable(uint8 _type) internal pure returns (bool) { return _type != NO_PARAM_MAPPING; } /// @notice Checks if the paramMapping value is in the return value range /// @param _type Indicated the type of the input function isReturnInjection(uint8 _type) internal pure returns (bool) { return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in return array value /// @param _type Indicated the type of the input function getReturnIndex(uint8 _type) internal pure returns (uint8) { require(isReturnInjection(_type), ERR_SUB_INDEX_VALUE); return (_type - RETURN_MIN_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in sub array value /// @param _type Indicated the type of the input function getSubIndex(uint8 _type) internal pure returns (uint8) { require(_type >= SUB_MIN_INDEX_VALUE, ERR_RETURN_INDEX_VALUE); return (_type - SUB_MIN_INDEX_VALUE); } } abstract contract IDSProxy { // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address, bytes32); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32); function setCache(address _cacheAddr) public payable virtual returns (bool); function owner() public view virtual returns (address); } /// @title Struct Data in a separate contract soit can be used in multiple places contract StrategyData { struct Template { string name; bytes32[] triggerIds; bytes32[] actionIds; uint8[][] paramMapping; } struct Task { string name; bytes[][] callData; bytes[][] subData; bytes32[] actionIds; uint8[][] paramMapping; } struct Strategy { uint templateId; address proxy; bytes[][] subData; bytes[][] triggerData; bool active; uint posInUserArr; } } /// @title Storage of strategies and templates contract Subscriptions is StrategyData { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); string public constant ERR_EMPTY_STRATEGY = "Strategy does not exist"; string public constant ERR_SENDER_NOT_OWNER = "Sender is not strategy owner"; string public constant ERR_USER_POS_EMPTY = "No user positions"; /// @dev The order of strategies might change as they are deleted Strategy[] public strategies; /// @dev Templates are fixed and are non removable Template[] public templates; /// @dev Keeps track of all the users strategies (their indexes in the array) mapping (address => uint[]) public usersPos; /// @dev Increments on state change, used for easier off chain tracking of changes uint public updateCounter; /// @notice Creates a new strategy with an existing template /// @param _templateId Id of the template used for strategy /// @param _active If the strategy is turned on at the start /// @param _subData Subscription data for actions /// @param _triggerData Subscription data for triggers function createStrategy( uint _templateId, bool _active, bytes[][] memory _subData, bytes[][] memory _triggerData ) public returns (uint) { strategies.push( Strategy({ templateId: _templateId, proxy: msg.sender, active: _active, subData: _subData, triggerData: _triggerData, posInUserArr: (usersPos[msg.sender].length - 1) }) ); usersPos[msg.sender].push(strategies.length - 1); updateCounter++; logger.Log(address(this), msg.sender, "CreateStrategy", abi.encode(strategies.length - 1)); return strategies.length - 1; } /// @notice Creates a new template to use in strategies /// @dev Templates once created can't be changed /// @param _name Name of template, used mainly for logging /// @param _triggerIds Array of trigger ids which translate to trigger addresses /// @param _actionIds Array of actions ids which translate to action addresses /// @param _paramMapping Array that holds metadata of how inputs are mapped to sub/return data function createTemplate( string memory _name, bytes32[] memory _triggerIds, bytes32[] memory _actionIds, uint8[][] memory _paramMapping ) public returns (uint) { templates.push( Template({ name: _name, triggerIds: _triggerIds, actionIds: _actionIds, paramMapping: _paramMapping }) ); updateCounter++; logger.Log(address(this), msg.sender, "CreateTemplate", abi.encode(templates.length - 1)); return templates.length - 1; } /// @notice Updates the users strategy /// @dev Only callable by proxy who created the strategy /// @param _startegyId Id of the strategy to update /// @param _templateId Id of the template used for strategy /// @param _active If the strategy is turned on at the start /// @param _subData Subscription data for actions /// @param _triggerData Subscription data for triggers function updateStrategy( uint _startegyId, uint _templateId, bool _active, bytes[][] memory _subData, bytes[][] memory _triggerData ) public { Strategy storage s = strategies[_startegyId]; require(s.proxy != address(0), ERR_EMPTY_STRATEGY); require(msg.sender == s.proxy, ERR_SENDER_NOT_OWNER); s.templateId = _templateId; s.active = _active; s.subData = _subData; s.triggerData = _triggerData; updateCounter++; logger.Log(address(this), msg.sender, "UpdateStrategy", abi.encode(_startegyId)); } /// @notice Unsubscribe an existing strategy /// @dev Only callable by proxy who created the strategy /// @param _subId Subscription id function removeStrategy(uint256 _subId) public { Strategy memory s = strategies[_subId]; require(s.proxy != address(0), ERR_EMPTY_STRATEGY); require(msg.sender == s.proxy, ERR_SENDER_NOT_OWNER); uint lastSub = strategies.length - 1; _removeUserPos(msg.sender, s.posInUserArr); strategies[_subId] = strategies[lastSub]; // last strategy put in place of the deleted one strategies.pop(); // delete last strategy, because it moved logger.Log(address(this), msg.sender, "Unsubscribe", abi.encode(_subId)); } function _removeUserPos(address _user, uint _index) internal { require(usersPos[_user].length > 0, ERR_USER_POS_EMPTY); uint lastPos = usersPos[_user].length - 1; usersPos[_user][_index] = usersPos[_user][lastPos]; usersPos[_user].pop(); } ///////////////////// VIEW ONLY FUNCTIONS //////////////////////////// function getTemplateFromStrategy(uint _strategyId) public view returns (Template memory) { uint templateId = strategies[_strategyId].templateId; return templates[templateId]; } function getStrategy(uint _strategyId) public view returns (Strategy memory) { return strategies[_strategyId]; } function getTemplate(uint _templateId) public view returns (Template memory) { return templates[_templateId]; } function getStrategyCount() public view returns (uint256) { return strategies.length; } function getTemplateCount() public view returns (uint256) { return templates.length; } function getStrategies() public view returns (Strategy[] memory) { return strategies; } function getTemplates() public view returns (Template[] memory) { return templates; } function userHasStrategies(address _user) public view returns (bool) { return usersPos[_user].length > 0; } function getUserStrategies(address _user) public view returns (Strategy[] memory) { Strategy[] memory userStrategies = new Strategy[](usersPos[_user].length); for (uint i = 0; i < usersPos[_user].length; ++i) { userStrategies[i] = strategies[usersPos[_user][i]]; } return userStrategies; } function getPaginatedStrategies(uint _page, uint _perPage) public view returns (Strategy[] memory) { Strategy[] memory strategiesPerPage = new Strategy[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > strategiesPerPage.length) ? strategiesPerPage.length : end; uint count = 0; for (uint i = start; i < end; i++) { strategiesPerPage[count] = strategies[i]; count++; } return strategiesPerPage; } function getPaginatedTemplates(uint _page, uint _perPage) public view returns (Template[] memory) { Template[] memory templatesPerPage = new Template[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > templatesPerPage.length) ? templatesPerPage.length : end; uint count = 0; for (uint i = start; i < end; i++) { templatesPerPage[count] = templates[i]; count++; } return templatesPerPage; } } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint256 _amount, bytes calldata _params ) external virtual; function deposit( address _reserve, uint256 _amount, uint16 _referralCode ) external payable virtual; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow( address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode ) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf ) external payable virtual; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external view virtual returns (address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external view virtual returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external view virtual returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external view virtual returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external view virtual returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public view virtual returns (address); function getReserveConfiguration(address _reserve) external view virtual returns ( uint256, uint256, uint256, bool ); function getUserUnderlyingAssetBalance(address _reserve, address _user) public view virtual returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public view virtual returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public view virtual returns (uint256); function getReserveTotalLiquidity(address _reserve) public view virtual returns (uint256); function getReserveAvailableLiquidity(address _reserve) public view virtual returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public view virtual returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public view virtual returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProviderV2 { event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } interface ILendingPoolV2 { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet **/ function withdraw( address asset, uint256 amount, address to ) external; /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external; /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProviderV2); function setPause(bool val) external; function paused() external view returns (bool); } abstract contract IWETH { function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom( address, address, uint256 ) public virtual returns (bool); function deposit() public payable virtual; function withdraw(uint256) public virtual; } contract TokenUtils { using SafeERC20 for IERC20; address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // mainnet address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; function approveToken(address _tokenAddr, address _to, uint _amount) internal { if (_tokenAddr == ETH_ADDR) return; if (IERC20(_tokenAddr).allowance(address(this), _to) < _amount) { IERC20(_tokenAddr).safeApprove(_to, _amount); } } function pullTokens(address _token, address _from, uint256 _amount) internal returns (uint) { // handle max uint amount if (_amount == uint(-1)) { uint allowance = uint (-1); if (_token == ETH_ADDR) { allowance = IERC20(_token).allowance(address(this), _from); } uint balance = getBalance(_token, _from); _amount = (balance > allowance) ? allowance : balance; } if (_from != address(0) && _from != address(this) && _token != ETH_ADDR && _amount != 0) { IERC20(_token).safeTransferFrom(_from, address(this), _amount); } return _amount; } function withdrawTokens( address _token, address _to, uint256 _amount ) internal returns (uint) { if (_amount == uint(-1)) { _amount = getBalance(_token, address(this)); } if (_to != address(0) && _to != address(this) && _amount != 0) { if (_token != ETH_ADDR) { IERC20(_token).safeTransfer(_to, _amount); } else { payable(_to).transfer(_amount); } } return _amount; } function convertAndDepositToWeth(address _tokenAddr, uint _amount) internal returns (address) { if (_tokenAddr == ETH_ADDR) { IWETH(WETH_ADDR).deposit{value: _amount}(); return WETH_ADDR; } else { return _tokenAddr; } } function withdrawWeth(uint _amount) internal { IWETH(WETH_ADDR).withdraw(_amount); } function getBalance(address _tokenAddr, address _acc) internal view returns (uint) { if (_tokenAddr == ETH_ADDR) { return _acc.balance; } else { return IERC20(_tokenAddr).balanceOf(_acc); } } function convertToWeth(address _tokenAddr) internal pure returns (address){ return _tokenAddr == ETH_ADDR ? WETH_ADDR : _tokenAddr; } function convertToEth(address _tokenAddr) internal pure returns (address){ return _tokenAddr == WETH_ADDR ? ETH_ADDR : _tokenAddr; } function getTokenDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return IERC20(_token).decimals(); } } /// @title Action that gets and receives a FL from Aave V2 contract FLAaveV2 is ActionBase, StrategyData, TokenUtils { using SafeERC20 for IERC20; address public constant AAVE_LENDING_POOL = 0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9; ILendingPoolAddressesProviderV2 public constant addressesProvider = ILendingPoolAddressesProviderV2( 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5 ); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint16 public constant AAVE_REFERRAL_CODE = 64; bytes4 public constant CALLBACK_SELECTOR = 0xd6741b9e; bytes32 constant FL_AAVE_ID = keccak256("FLAaveV2"); bytes32 constant TASK_EXECUTOR_ID = keccak256("TaskExecutor"); struct FLAaveV2Data { address receiver; address[] tokens; uint256[] amounts; uint256[] modes; address onBehalfOf; bytes params; uint16 refferalCode; } /// @inheritdoc ActionBase function executeAction( bytes[] memory _callData, bytes[] memory, uint8[] memory, bytes32[] memory ) public override payable returns (bytes32) { FLAaveV2Data memory flData = parseInputs(_callData); uint flAmount = _flAaveV2(flData, _callData[4]); 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 //////////////////////////// function _flAaveV2(FLAaveV2Data memory _flData, bytes memory _params) internal returns (uint) { ILendingPoolV2(AAVE_LENDING_POOL).flashLoan( _flData.receiver, _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, bytes memory _params ) public returns (bool) { (Task memory currTask, address proxy) = abi.decode(_params, (Task, address)); for (uint256 i = 0; i < _assets.length; ++i) { if (_assets[i] == WETH_ADDR) { withdrawWeth(_amounts[i]); } withdrawTokens(convertToEth(_assets[i]), 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(_amounts[0] + _fees[0])) ); // return FL for (uint256 i = 0; i < _assets.length; i++) { convertAndDepositToWeth(convertToEth(_assets[i]), (_amounts[i] + _fees[i])); approveToken(_assets[i], address(AAVE_LENDING_POOL), _amounts[i] + _fees[i]); } return true; } function parseInputs(bytes[] memory _callData) public view 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.receiver = payable(registry.getAddr(FL_AAVE_ID)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} }
@notice Updates the users strategy @dev Only callable by proxy who created the strategy @param _startegyId Id of the strategy to update @param _templateId Id of the template used for strategy @param _active If the strategy is turned on at the start @param _subData Subscription data for actions @param _triggerData Subscription data for triggers
function updateStrategy( uint _startegyId, uint _templateId, bool _active, bytes[][] memory _subData, bytes[][] memory _triggerData ) public { Strategy storage s = strategies[_startegyId]; require(s.proxy != address(0), ERR_EMPTY_STRATEGY); require(msg.sender == s.proxy, ERR_SENDER_NOT_OWNER); s.templateId = _templateId; s.active = _active; s.subData = _subData; s.triggerData = _triggerData; updateCounter++; logger.Log(address(this), msg.sender, "UpdateStrategy", abi.encode(_startegyId)); }
157,852
[ 1, 5121, 326, 3677, 6252, 225, 5098, 4140, 635, 2889, 10354, 2522, 326, 6252, 225, 389, 1937, 1332, 93, 548, 3124, 434, 326, 6252, 358, 1089, 225, 389, 3202, 548, 3124, 434, 326, 1542, 1399, 364, 6252, 225, 389, 3535, 971, 326, 6252, 353, 21826, 603, 622, 326, 787, 225, 389, 1717, 751, 12132, 501, 364, 4209, 225, 389, 10668, 751, 12132, 501, 364, 11752, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 4525, 12, 203, 3639, 2254, 389, 1937, 1332, 93, 548, 16, 203, 3639, 2254, 389, 3202, 548, 16, 203, 3639, 1426, 389, 3535, 16, 203, 3639, 1731, 63, 6362, 65, 3778, 389, 1717, 751, 16, 203, 3639, 1731, 63, 6362, 65, 3778, 389, 10668, 751, 203, 565, 262, 1071, 288, 203, 3639, 19736, 2502, 272, 273, 20417, 63, 67, 1937, 1332, 93, 548, 15533, 203, 203, 3639, 2583, 12, 87, 18, 5656, 480, 1758, 12, 20, 3631, 10359, 67, 13625, 67, 3902, 27708, 1769, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 272, 18, 5656, 16, 10359, 67, 1090, 18556, 67, 4400, 67, 29602, 1769, 203, 203, 3639, 272, 18, 3202, 548, 273, 389, 3202, 548, 31, 203, 3639, 272, 18, 3535, 273, 389, 3535, 31, 203, 3639, 272, 18, 1717, 751, 273, 389, 1717, 751, 31, 203, 3639, 272, 18, 10668, 751, 273, 389, 10668, 751, 31, 203, 203, 3639, 1089, 4789, 9904, 31, 203, 203, 3639, 1194, 18, 1343, 12, 2867, 12, 2211, 3631, 1234, 18, 15330, 16, 315, 1891, 4525, 3113, 24126, 18, 3015, 24899, 1937, 1332, 93, 548, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/44787/0x3d7237d60dCa4C635FE0CD62fD524F09B3730f54/sources/contracts/StarNFTMarket.sol
add fee starToken.transfer(Bonus.getlockAddress(), _fee.mul(lockRatio).div(100));
function purchaseToken(uint256 _tokenId) public nonReentrant { require(_msgSender() != address(0)); require(tokenInfo[_tokenId].owner != address(0), "not sale"); uint256 _price = tokenInfo[_tokenId].price; starToken.transferFrom(_msgSender(), address(this), _price); uint256 _fee = _price.mul(fee).div(100); uint256 lockRatio =Bonus.getlockRatio(); starToken.transfer(bonusAddr, _fee.mul(100 - lockRatio).div(100)); userStar[tokenInfo[_tokenId].owner] = userStar[tokenInfo[_tokenId].owner].add(_price.sub(_fee)); starNFT.transferFrom(address(this), _msgSender(), _tokenId); _removeToken(tokenInfo[_tokenId].owner, _tokenId); uint256 amountBonus = Bonus.getBonus(_tokenId); if(amountBonus > 0 && tokenInfo[_tokenId].owner != _msgSender()){ starToken.transferFrom(_msgSender(), tokenInfo[_tokenId].owner, amountBonus); NFTLogic.setBonusToke(_tokenId,0); } uint256 indexLength = NFTLogic.getAllTokenId().length; if(indexLength > 0){ uint256 divAmountBonus = _fee.mul(100 - lockRatio).div(100).mul(1e12).div(indexLength - 1); for(uint256 i = 0;i< indexLength;i++){ uint256 tokenId = NFTLogic.getAllTokenId()[i]; if(tokenId == _tokenId){ continue; } uint256 UserBonusToken = NFTLogic.disposeBonusToke(tokenId); NFTLogic.setBonusToke(tokenId,divAmountBonus.div(1e12).add(UserBonusToken)); } } }
13,252,240
[ 1, 1289, 14036, 10443, 1345, 18, 13866, 12, 38, 22889, 18, 588, 739, 1887, 9334, 389, 21386, 18, 16411, 12, 739, 8541, 2934, 2892, 12, 6625, 10019, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 23701, 1345, 12, 11890, 5034, 389, 2316, 548, 13, 1071, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 24899, 3576, 12021, 1435, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12, 2316, 966, 63, 67, 2316, 548, 8009, 8443, 480, 1758, 12, 20, 3631, 315, 902, 272, 5349, 8863, 203, 3639, 2254, 5034, 389, 8694, 273, 1147, 966, 63, 67, 2316, 548, 8009, 8694, 31, 203, 3639, 10443, 1345, 18, 13866, 1265, 24899, 3576, 12021, 9334, 1758, 12, 2211, 3631, 389, 8694, 1769, 203, 3639, 2254, 5034, 389, 21386, 273, 389, 8694, 18, 16411, 12, 21386, 2934, 2892, 12, 6625, 1769, 203, 3639, 2254, 5034, 2176, 8541, 273, 38, 22889, 18, 588, 739, 8541, 5621, 203, 3639, 10443, 1345, 18, 13866, 12, 18688, 407, 3178, 16, 389, 21386, 18, 16411, 12, 6625, 300, 2176, 8541, 2934, 2892, 12, 6625, 10019, 203, 3639, 729, 18379, 63, 2316, 966, 63, 67, 2316, 548, 8009, 8443, 65, 273, 729, 18379, 63, 2316, 966, 63, 67, 2316, 548, 8009, 8443, 8009, 1289, 24899, 8694, 18, 1717, 24899, 21386, 10019, 203, 3639, 10443, 50, 4464, 18, 13866, 1265, 12, 2867, 12, 2211, 3631, 389, 3576, 12021, 9334, 389, 2316, 548, 1769, 203, 3639, 389, 4479, 1345, 12, 2316, 966, 63, 67, 2316, 548, 8009, 8443, 16, 389, 2316, 548, 1769, 203, 3639, 2254, 5034, 3844, 38, 22889, 273, 605, 22889, 18, 588, 38, 22889, 24899, 2316, 548, 1769, 203, 3639, 309, 12, 8949, 38, 22889, 405, 374, 597, 1147, 966, 63, 67, 2316, 548, 8009, 8443, 480, 2 ]
pragma solidity ^0.5.17; // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } /* * SPDX-License-Identifier: MIT */ /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function balanceOf(address _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); } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/SafeERC20.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules library SafeERC20 { /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeTransfer(IERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( _token.transfer.selector, _to, _amount ); return invokeAndCheckSuccess(address(_token), transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeTransferFrom(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(address(_token), transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeApprove(IERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(address(_token), approveCallData); } function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } } library PctHelpers { using SafeMath for uint256; uint256 internal constant PCT_BASE = 10000; // ‱ (1 / 10,000) function isValid(uint16 _pct) internal pure returns (bool) { return _pct <= PCT_BASE; } function pct(uint256 self, uint16 _pct) internal pure returns (uint256) { return self.mul(uint256(_pct)) / PCT_BASE; } function pct256(uint256 self, uint256 _pct) internal pure returns (uint256) { return self.mul(_pct) / PCT_BASE; } function pctIncrease(uint256 self, uint16 _pct) internal pure returns (uint256) { // No need for SafeMath: for addition note that `PCT_BASE` is lower than (2^256 - 2^16) return self.mul(PCT_BASE + uint256(_pct)) / PCT_BASE; } } /** * @title Checkpointing - Library to handle a historic set of numeric values */ library Checkpointing { uint256 private constant MAX_UINT192 = uint256(uint192(-1)); string private constant ERROR_VALUE_TOO_BIG = "CHECKPOINT_VALUE_TOO_BIG"; string private constant ERROR_CANNOT_ADD_PAST_VALUE = "CHECKPOINT_CANNOT_ADD_PAST_VALUE"; /** * @dev To specify a value at a given point in time, we need to store two values: * - `time`: unit-time value to denote the first time when a value was registered * - `value`: a positive numeric value to registered at a given point in time * * Note that `time` does not need to refer necessarily to a timestamp value, any time unit could be used * for it like block numbers, terms, etc. */ struct Checkpoint { uint64 time; uint192 value; } /** * @dev A history simply denotes a list of checkpoints */ struct History { Checkpoint[] history; } /** * @dev Add a new value to a history for a given point in time. This function does not allow to add values previous * to the latest registered value, if the value willing to add corresponds to the latest registered value, it * will be updated. * @param self Checkpoints history to be altered * @param _time Point in time to register the given value * @param _value Numeric value to be registered at the given point in time */ function add(History storage self, uint64 _time, uint256 _value) internal { require(_value <= MAX_UINT192, ERROR_VALUE_TOO_BIG); _add192(self, _time, uint192(_value)); } /** * @dev Fetch the latest registered value of history, it will return zero if there was no value registered * @param self Checkpoints history to be queried */ function getLast(History storage self) internal view returns (uint256) { uint256 length = self.history.length; if (length > 0) { return uint256(self.history[length - 1].value); } return 0; } /** * @dev Fetch the most recent registered past value of a history based on a given point in time that is not known * how recent it is beforehand. It will return zero if there is no registered value or if given time is * previous to the first registered value. * It uses a binary search. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function get(History storage self, uint64 _time) internal view returns (uint256) { return _binarySearch(self, _time); } /** * @dev Fetch the most recent registered past value of a history based on a given point in time. It will return zero * if there is no registered value or if given time is previous to the first registered value. * It uses a linear search starting from the end. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function getRecent(History storage self, uint64 _time) internal view returns (uint256) { return _backwardsLinearSearch(self, _time); } /** * @dev Private function to add a new value to a history for a given point in time. This function does not allow to * add values previous to the latest registered value, if the value willing to add corresponds to the latest * registered value, it will be updated. * @param self Checkpoints history to be altered * @param _time Point in time to register the given value * @param _value Numeric value to be registered at the given point in time */ function _add192(History storage self, uint64 _time, uint192 _value) private { uint256 length = self.history.length; if (length == 0 || self.history[self.history.length - 1].time < _time) { // If there was no value registered or the given point in time is after the latest registered value, // we can insert it to the history directly. self.history.push(Checkpoint(_time, _value)); } else { // If the point in time given for the new value is not after the latest registered value, we must ensure // we are only trying to update the latest value, otherwise we would be changing past data. Checkpoint storage currentCheckpoint = self.history[length - 1]; require(_time == currentCheckpoint.time, ERROR_CANNOT_ADD_PAST_VALUE); currentCheckpoint.value = _value; } } /** * @dev Private function to execute a backwards linear search to find the most recent registered past value of a * history based on a given point in time. It will return zero if there is no registered value or if given time * is previous to the first registered value. Note that this function will be more suitable when we already know * that the time used to index the search is recent in the given history. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function _backwardsLinearSearch(History storage self, uint64 _time) private view returns (uint256) { // If there was no value registered for the given history return simply zero uint256 length = self.history.length; if (length == 0) { return 0; } uint256 index = length - 1; Checkpoint storage checkpoint = self.history[index]; while (index > 0 && checkpoint.time > _time) { index--; checkpoint = self.history[index]; } return checkpoint.time > _time ? 0 : uint256(checkpoint.value); } /** * @dev Private function execute a binary search to find the most recent registered past value of a history based on * a given point in time. It will return zero if there is no registered value or if given time is previous to * the first registered value. Note that this function will be more suitable when don't know how recent the * time used to index may be. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function _binarySearch(History storage self, uint64 _time) private view returns (uint256) { // If there was no value registered for the given history return simply zero uint256 length = self.history.length; if (length == 0) { return 0; } // If the requested time is equal to or after the time of the latest registered value, return latest value uint256 lastIndex = length - 1; if (_time >= self.history[lastIndex].time) { return uint256(self.history[lastIndex].value); } // If the requested time is previous to the first registered value, return zero to denote missing checkpoint if (_time < self.history[0].time) { return 0; } // Execute a binary search between the checkpointed times of the history uint256 low = 0; uint256 high = lastIndex; while (high > low) { // No need for SafeMath: for this to overflow array size should be ~2^255 uint256 mid = (high + low + 1) / 2; Checkpoint storage checkpoint = self.history[mid]; uint64 midTime = checkpoint.time; if (_time > midTime) { low = mid; } else if (_time < midTime) { // No need for SafeMath: high > low >= 0 => high >= 1 => mid >= 1 high = mid - 1; } else { return uint256(checkpoint.value); } } return uint256(self.history[low].value); } } /** * @title HexSumTree - Library to operate checkpointed 16-ary (hex) sum trees. * @dev A sum tree is a particular case of a tree where the value of a node is equal to the sum of the values of its * children. This library provides a set of functions to operate 16-ary sum trees, i.e. trees where every non-leaf * node has 16 children and its value is equivalent to the sum of the values of all of them. Additionally, a * checkpointed tree means that each time a value on a node is updated, its previous value will be saved to allow * accessing historic information. * * Example of a checkpointed binary sum tree: * * CURRENT PREVIOUS * * Level 2 100 ---------------------------------------- 70 * ______|_______ ______|_______ * / \ / \ * Level 1 34 66 ------------------------- 23 47 * _____|_____ _____|_____ _____|_____ _____|_____ * / \ / \ / \ / \ * Level 0 22 12 53 13 ----------- 22 1 17 30 * */ library HexSumTree { using SafeMath for uint256; using Checkpointing for Checkpointing.History; string private constant ERROR_UPDATE_OVERFLOW = "SUM_TREE_UPDATE_OVERFLOW"; string private constant ERROR_KEY_DOES_NOT_EXIST = "SUM_TREE_KEY_DOES_NOT_EXIST"; string private constant ERROR_SEARCH_OUT_OF_BOUNDS = "SUM_TREE_SEARCH_OUT_OF_BOUNDS"; string private constant ERROR_MISSING_SEARCH_VALUES = "SUM_TREE_MISSING_SEARCH_VALUES"; // Constants used to perform tree computations // To change any the following constants, the following relationship must be kept: 2^BITS_IN_NIBBLE = CHILDREN // The max depth of the tree will be given by: BITS_IN_NIBBLE * MAX_DEPTH = 256 (so in this case it's 64) uint256 private constant CHILDREN = 16; uint256 private constant BITS_IN_NIBBLE = 4; // All items are leaves, inserted at height or level zero. The root height will be increasing as new levels are inserted in the tree. uint256 private constant ITEMS_LEVEL = 0; // Tree nodes are identified with a 32-bytes length key. Leaves are identified with consecutive incremental keys // starting with 0x0000000000000000000000000000000000000000000000000000000000000000, while non-leaf nodes' keys // are computed based on their level and their children keys. uint256 private constant BASE_KEY = 0; // Timestamp used to checkpoint the first value of the tree height during initialization uint64 private constant INITIALIZATION_INITIAL_TIME = uint64(0); /** * @dev The tree is stored using the following structure: * - nodes: A mapping indexed by a pair (level, key) with a history of the values for each node (level -> key -> value). * - height: A history of the heights of the tree. Minimum height is 1, a root with 16 children. * - nextKey: The next key to be used to identify the next new value that will be inserted into the tree. */ struct Tree { uint256 nextKey; Checkpointing.History height; mapping (uint256 => mapping (uint256 => Checkpointing.History)) nodes; } /** * @dev Search params to traverse the tree caching previous results: * - time: Point in time to query the values being searched, this value shouldn't change during a search * - level: Level being analyzed for the search, it starts at the level under the root and decrements till the leaves * - parentKey: Key of the parent of the nodes being analyzed at the given level for the search * - foundValues: Number of values in the list being searched that were already found, it will go from 0 until the size of the list * - visitedTotal: Total sum of values that were already visited during the search, it will go from 0 until the tree total */ struct SearchParams { uint64 time; uint256 level; uint256 parentKey; uint256 foundValues; uint256 visitedTotal; } /** * @dev Initialize tree setting the next key and first height checkpoint */ function init(Tree storage self) internal { self.height.add(INITIALIZATION_INITIAL_TIME, ITEMS_LEVEL + 1); self.nextKey = BASE_KEY; } /** * @dev Insert a new item to the tree at given point in time * @param _time Point in time to register the given value * @param _value New numeric value to be added to the tree * @return Unique key identifying the new value inserted */ function insert(Tree storage self, uint64 _time, uint256 _value) internal returns (uint256) { // As the values are always stored in the leaves of the tree (level 0), the key to index each of them will be // always incrementing, starting from zero. Add a new level if necessary. uint256 key = self.nextKey++; _addLevelIfNecessary(self, key, _time); // If the new value is not zero, first set the value of the new leaf node, then add a new level at the top of // the tree if necessary, and finally update sums cached in all the non-leaf nodes. if (_value > 0) { _add(self, ITEMS_LEVEL, key, _time, _value); _updateSums(self, key, _time, _value, true); } return key; } /** * @dev Set the value of a leaf node indexed by its key at given point in time * @param _time Point in time to set the given value * @param _key Key of the leaf node to be set in the tree * @param _value New numeric value to be set for the given key */ function set(Tree storage self, uint256 _key, uint64 _time, uint256 _value) internal { require(_key < self.nextKey, ERROR_KEY_DOES_NOT_EXIST); // Set the new value for the requested leaf node uint256 lastValue = getItem(self, _key); _add(self, ITEMS_LEVEL, _key, _time, _value); // Update sums cached in the non-leaf nodes. Note that overflows are being checked at the end of the whole update. if (_value > lastValue) { _updateSums(self, _key, _time, _value - lastValue, true); } else if (_value < lastValue) { _updateSums(self, _key, _time, lastValue - _value, false); } } /** * @dev Update the value of a non-leaf node indexed by its key at given point in time based on a delta * @param _key Key of the leaf node to be updated in the tree * @param _time Point in time to update the given value * @param _delta Numeric delta to update the value of the given key * @param _positive Boolean to tell whether the given delta should be added to or subtracted from the current value */ function update(Tree storage self, uint256 _key, uint64 _time, uint256 _delta, bool _positive) internal { require(_key < self.nextKey, ERROR_KEY_DOES_NOT_EXIST); // Update the value of the requested leaf node based on the given delta uint256 lastValue = getItem(self, _key); uint256 newValue = _positive ? lastValue.add(_delta) : lastValue.sub(_delta); _add(self, ITEMS_LEVEL, _key, _time, newValue); // Update sums cached in the non-leaf nodes. Note that overflows is being checked at the end of the whole update. _updateSums(self, _key, _time, _delta, _positive); } /** * @dev Search a list of values in the tree at a given point in time. It will return a list with the nearest * high value in case a value cannot be found. This function assumes the given list of given values to be * searched is in ascending order. In case of searching a value out of bounds, it will return zeroed results. * @param _values Ordered list of values to be searched in the tree * @param _time Point in time to query the values being searched * @return keys List of keys found for each requested value in the same order * @return values List of node values found for each requested value in the same order */ function search(Tree storage self, uint256[] memory _values, uint64 _time) internal view returns (uint256[] memory keys, uint256[] memory values) { require(_values.length > 0, ERROR_MISSING_SEARCH_VALUES); // Throw out-of-bounds error if there are no items in the tree or the highest value being searched is greater than the total uint256 total = getRecentTotalAt(self, _time); // No need for SafeMath: positive length of array already checked require(total > 0 && total > _values[_values.length - 1], ERROR_SEARCH_OUT_OF_BOUNDS); // Build search params for the first iteration uint256 rootLevel = getRecentHeightAt(self, _time); SearchParams memory searchParams = SearchParams(_time, rootLevel.sub(1), BASE_KEY, 0, 0); // These arrays will be used to fill in the results. We are passing them as parameters to avoid extra copies uint256 length = _values.length; keys = new uint256[](length); values = new uint256[](length); _search(self, _values, searchParams, keys, values); } /** * @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree */ function getTotal(Tree storage self) internal view returns (uint256) { uint256 rootLevel = getHeight(self); return getNode(self, rootLevel, BASE_KEY); } /** * @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree, at a given point in time * It uses a binary search for the root node, a linear one for the height. * @param _time Point in time to query the sum of all the items (leaves) stored in the tree */ function getTotalAt(Tree storage self, uint64 _time) internal view returns (uint256) { uint256 rootLevel = getRecentHeightAt(self, _time); return getNodeAt(self, rootLevel, BASE_KEY, _time); } /** * @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree, at a given point in time * It uses a linear search starting from the end. * @param _time Point in time to query the sum of all the items (leaves) stored in the tree */ function getRecentTotalAt(Tree storage self, uint64 _time) internal view returns (uint256) { uint256 rootLevel = getRecentHeightAt(self, _time); return getRecentNodeAt(self, rootLevel, BASE_KEY, _time); } /** * @dev Tell the value of a certain leaf indexed by a given key * @param _key Key of the leaf node querying the value of */ function getItem(Tree storage self, uint256 _key) internal view returns (uint256) { return getNode(self, ITEMS_LEVEL, _key); } /** * @dev Tell the value of a certain leaf indexed by a given key at a given point in time * It uses a binary search. * @param _key Key of the leaf node querying the value of * @param _time Point in time to query the value of the requested leaf */ function getItemAt(Tree storage self, uint256 _key, uint64 _time) internal view returns (uint256) { return getNodeAt(self, ITEMS_LEVEL, _key, _time); } /** * @dev Tell the value of a certain node indexed by a given (level,key) pair * @param _level Level of the node querying the value of * @param _key Key of the node querying the value of */ function getNode(Tree storage self, uint256 _level, uint256 _key) internal view returns (uint256) { return self.nodes[_level][_key].getLast(); } /** * @dev Tell the value of a certain node indexed by a given (level,key) pair at a given point in time * It uses a binary search. * @param _level Level of the node querying the value of * @param _key Key of the node querying the value of * @param _time Point in time to query the value of the requested node */ function getNodeAt(Tree storage self, uint256 _level, uint256 _key, uint64 _time) internal view returns (uint256) { return self.nodes[_level][_key].get(_time); } /** * @dev Tell the value of a certain node indexed by a given (level,key) pair at a given point in time * It uses a linear search starting from the end. * @param _level Level of the node querying the value of * @param _key Key of the node querying the value of * @param _time Point in time to query the value of the requested node */ function getRecentNodeAt(Tree storage self, uint256 _level, uint256 _key, uint64 _time) internal view returns (uint256) { return self.nodes[_level][_key].getRecent(_time); } /** * @dev Tell the height of the tree */ function getHeight(Tree storage self) internal view returns (uint256) { return self.height.getLast(); } /** * @dev Tell the height of the tree at a given point in time * It uses a linear search starting from the end. * @param _time Point in time to query the height of the tree */ function getRecentHeightAt(Tree storage self, uint64 _time) internal view returns (uint256) { return self.height.getRecent(_time); } /** * @dev Private function to update the values of all the ancestors of the given leaf node based on the delta updated * @param _key Key of the leaf node to update the ancestors of * @param _time Point in time to update the ancestors' values of the given leaf node * @param _delta Numeric delta to update the ancestors' values of the given leaf node * @param _positive Boolean to tell whether the given delta should be added to or subtracted from ancestors' values */ function _updateSums(Tree storage self, uint256 _key, uint64 _time, uint256 _delta, bool _positive) private { uint256 mask = uint256(-1); uint256 ancestorKey = _key; uint256 currentHeight = getHeight(self); for (uint256 level = ITEMS_LEVEL + 1; level <= currentHeight; level++) { // Build a mask to get the key of the ancestor at a certain level. For example: // Level 0: leaves don't have children // Level 1: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0 (up to 16 leaves) // Level 2: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 (up to 32 leaves) // ... // Level 63: 0x0000000000000000000000000000000000000000000000000000000000000000 (up to 16^64 leaves - tree max height) mask = mask << BITS_IN_NIBBLE; // The key of the ancestor at that level "i" is equivalent to the "(64 - i)-th" most significant nibbles // of the ancestor's key of the previous level "i - 1". Thus, we can compute the key of an ancestor at a // certain level applying the mask to the ancestor's key of the previous level. Note that for the first // iteration, the key of the ancestor of the previous level is simply the key of the leaf being updated. ancestorKey = ancestorKey & mask; // Update value uint256 lastValue = getNode(self, level, ancestorKey); uint256 newValue = _positive ? lastValue.add(_delta) : lastValue.sub(_delta); _add(self, level, ancestorKey, _time, newValue); } // Check if there was an overflow. Note that we only need to check the value stored in the root since the // sum only increases going up through the tree. require(!_positive || getNode(self, currentHeight, ancestorKey) >= _delta, ERROR_UPDATE_OVERFLOW); } /** * @dev Private function to add a new level to the tree based on a new key that will be inserted * @param _newKey New key willing to be inserted in the tree * @param _time Point in time when the new key will be inserted */ function _addLevelIfNecessary(Tree storage self, uint256 _newKey, uint64 _time) private { uint256 currentHeight = getHeight(self); if (_shouldAddLevel(currentHeight, _newKey)) { // Max height allowed for the tree is 64 since we are using node keys of 32 bytes. However, note that we // are not checking if said limit has been hit when inserting new leaves to the tree, for the purpose of // this system having 2^256 items inserted is unrealistic. uint256 newHeight = currentHeight + 1; uint256 rootValue = getNode(self, currentHeight, BASE_KEY); _add(self, newHeight, BASE_KEY, _time, rootValue); self.height.add(_time, newHeight); } } /** * @dev Private function to register a new value in the history of a node at a given point in time * @param _level Level of the node to add a new value at a given point in time to * @param _key Key of the node to add a new value at a given point in time to * @param _time Point in time to register a value for the given node * @param _value Numeric value to be registered for the given node at a given point in time */ function _add(Tree storage self, uint256 _level, uint256 _key, uint64 _time, uint256 _value) private { self.nodes[_level][_key].add(_time, _value); } /** * @dev Recursive pre-order traversal function * Every time it checks a node, it traverses the input array to find the initial subset of elements that are * below its accumulated value and passes that sub-array to the next iteration. Actually, the array is always * the same, to avoid making extra copies, it just passes the number of values already found , to avoid * checking values that went through a different branch. The same happens with the result lists of keys and * values, these are the same on every recursion step. The visited total is carried over each iteration to * avoid having to subtract all elements in the array. * @param _values Ordered list of values to be searched in the tree * @param _params Search parameters for the current recursive step * @param _resultKeys List of keys found for each requested value in the same order * @param _resultValues List of node values found for each requested value in the same order */ function _search( Tree storage self, uint256[] memory _values, SearchParams memory _params, uint256[] memory _resultKeys, uint256[] memory _resultValues ) private view { uint256 levelKeyLessSignificantNibble = _params.level.mul(BITS_IN_NIBBLE); for (uint256 childNumber = 0; childNumber < CHILDREN; childNumber++) { // Return if we already found enough values if (_params.foundValues >= _values.length) { break; } // Build child node key shifting the child number to the position of the less significant nibble of // the keys for the level being analyzed, and adding it to the key of the parent node. For example, // for a tree with height 5, if we are checking the children of the second node of the level 3, whose // key is 0x0000000000000000000000000000000000000000000000000000000000001000, its children keys are: // Child 0: 0x0000000000000000000000000000000000000000000000000000000000001000 // Child 1: 0x0000000000000000000000000000000000000000000000000000000000001100 // Child 2: 0x0000000000000000000000000000000000000000000000000000000000001200 // ... // Child 15: 0x0000000000000000000000000000000000000000000000000000000000001f00 uint256 childNodeKey = _params.parentKey.add(childNumber << levelKeyLessSignificantNibble); uint256 childNodeValue = getRecentNodeAt(self, _params.level, childNodeKey, _params.time); // Check how many values belong to the subtree of this node. As they are ordered, it will be a contiguous // subset starting from the beginning, so we only need to know the length of that subset. uint256 newVisitedTotal = _params.visitedTotal.add(childNodeValue); uint256 subtreeIncludedValues = _getValuesIncludedInSubtree(_values, _params.foundValues, newVisitedTotal); // If there are some values included in the subtree of the child node, visit them if (subtreeIncludedValues > 0) { // If the child node being analyzed is a leaf, add it to the list of results a number of times equals // to the number of values that were included in it. Otherwise, descend one level. if (_params.level == ITEMS_LEVEL) { _copyFoundNode(_params.foundValues, subtreeIncludedValues, childNodeKey, _resultKeys, childNodeValue, _resultValues); } else { SearchParams memory nextLevelParams = SearchParams( _params.time, _params.level - 1, // No need for SafeMath: we already checked above that the level being checked is greater than zero childNodeKey, _params.foundValues, _params.visitedTotal ); _search(self, _values, nextLevelParams, _resultKeys, _resultValues); } // Update the number of values that were already found _params.foundValues = _params.foundValues.add(subtreeIncludedValues); } // Update the visited total for the next node in this level _params.visitedTotal = newVisitedTotal; } } /** * @dev Private function to check if a new key can be added to the tree based on the current height of the tree * @param _currentHeight Current height of the tree to check if it supports adding the given key * @param _newKey Key willing to be added to the tree with the given current height * @return True if the current height of the tree should be increased to add the new key, false otherwise. */ function _shouldAddLevel(uint256 _currentHeight, uint256 _newKey) private pure returns (bool) { // Build a mask that will match all the possible keys for the given height. For example: // Height 1: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0 (up to 16 keys) // Height 2: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 (up to 32 keys) // ... // Height 64: 0x0000000000000000000000000000000000000000000000000000000000000000 (up to 16^64 keys - tree max height) uint256 shift = _currentHeight.mul(BITS_IN_NIBBLE); uint256 mask = uint256(-1) << shift; // Check if the given key can be represented in the tree with the current given height using the mask. return (_newKey & mask) != 0; } /** * @dev Private function to tell how many values of a list can be found in a subtree * @param _values List of values being searched in ascending order * @param _foundValues Number of values that were already found and should be ignore * @param _subtreeTotal Total sum of the given subtree to check the numbers that are included in it * @return Number of values in the list that are included in the given subtree */ function _getValuesIncludedInSubtree(uint256[] memory _values, uint256 _foundValues, uint256 _subtreeTotal) private pure returns (uint256) { // Look for all the values that can be found in the given subtree uint256 i = _foundValues; while (i < _values.length && _values[i] < _subtreeTotal) { i++; } return i - _foundValues; } /** * @dev Private function to copy a node a given number of times to a results list. This function assumes the given * results list have enough size to support the requested copy. * @param _from Index of the results list to start copying the given node * @param _times Number of times the given node will be copied * @param _key Key of the node to be copied * @param _resultKeys Lists of key results to copy the given node key to * @param _value Value of the node to be copied * @param _resultValues Lists of value results to copy the given node value to */ function _copyFoundNode( uint256 _from, uint256 _times, uint256 _key, uint256[] memory _resultKeys, uint256 _value, uint256[] memory _resultValues ) private pure { for (uint256 i = 0; i < _times; i++) { _resultKeys[_from + i] = _key; _resultValues[_from + i] = _value; } } } /** * @title GuardiansTreeSortition - Library to perform guardians sortition over a `HexSumTree` */ library GuardiansTreeSortition { using SafeMath for uint256; using HexSumTree for HexSumTree.Tree; string private constant ERROR_INVALID_INTERVAL_SEARCH = "TREE_INVALID_INTERVAL_SEARCH"; string private constant ERROR_SORTITION_LENGTHS_MISMATCH = "TREE_SORTITION_LENGTHS_MISMATCH"; /** * @dev Search random items in the tree based on certain restrictions * @param _termRandomness Randomness to compute the seed for the draft * @param _disputeId Identification number of the dispute to draft guardians for * @param _termId Current term when the draft is being computed * @param _selectedGuardians Number of guardians already selected for the draft * @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft * @param _roundRequestedGuardians Total number of guardians requested to be drafted * @param _sortitionIteration Number of sortitions already performed for the given draft * @return guardiansIds List of guardian ids obtained based on the requested search * @return guardiansBalances List of active balances for each guardian obtained based on the requested search */ function batchedRandomSearch( HexSumTree.Tree storage tree, bytes32 _termRandomness, uint256 _disputeId, uint64 _termId, uint256 _selectedGuardians, uint256 _batchRequestedGuardians, uint256 _roundRequestedGuardians, uint256 _sortitionIteration ) internal view returns (uint256[] memory guardiansIds, uint256[] memory guardiansBalances) { (uint256 low, uint256 high) = getSearchBatchBounds( tree, _termId, _selectedGuardians, _batchRequestedGuardians, _roundRequestedGuardians ); uint256[] memory balances = _computeSearchRandomBalances( _termRandomness, _disputeId, _sortitionIteration, _batchRequestedGuardians, low, high ); (guardiansIds, guardiansBalances) = tree.search(balances, _termId); require(guardiansIds.length == guardiansBalances.length, ERROR_SORTITION_LENGTHS_MISMATCH); require(guardiansIds.length == _batchRequestedGuardians, ERROR_SORTITION_LENGTHS_MISMATCH); } /** * @dev Get the bounds for a draft batch based on the active balances of the guardians * @param _termId Term ID of the active balances that will be used to compute the boundaries * @param _selectedGuardians Number of guardians already selected for the draft * @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft * @param _roundRequestedGuardians Total number of guardians requested to be drafted * @return low Low bound to be used for the sortition to draft the requested number of guardians for the given batch * @return high High bound to be used for the sortition to draft the requested number of guardians for the given batch */ function getSearchBatchBounds( HexSumTree.Tree storage tree, uint64 _termId, uint256 _selectedGuardians, uint256 _batchRequestedGuardians, uint256 _roundRequestedGuardians ) internal view returns (uint256 low, uint256 high) { uint256 totalActiveBalance = tree.getRecentTotalAt(_termId); low = _selectedGuardians.mul(totalActiveBalance).div(_roundRequestedGuardians); uint256 newSelectedGuardians = _selectedGuardians.add(_batchRequestedGuardians); high = newSelectedGuardians.mul(totalActiveBalance).div(_roundRequestedGuardians); } /** * @dev Get a random list of active balances to be searched in the guardians tree for a given draft batch * @param _termRandomness Randomness to compute the seed for the draft * @param _disputeId Identification number of the dispute to draft guardians for (for randomness) * @param _sortitionIteration Number of sortitions already performed for the given draft (for randomness) * @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft * @param _lowBatchBound Low bound to be used for the sortition batch to draft the requested number of guardians * @param _highBatchBound High bound to be used for the sortition batch to draft the requested number of guardians * @return Random list of active balances to be searched in the guardians tree for the given draft batch */ function _computeSearchRandomBalances( bytes32 _termRandomness, uint256 _disputeId, uint256 _sortitionIteration, uint256 _batchRequestedGuardians, uint256 _lowBatchBound, uint256 _highBatchBound ) internal pure returns (uint256[] memory) { // Calculate the interval to be used to search the balances in the tree. Since we are using a modulo function to compute the // random balances to be searched, intervals will be closed on the left and open on the right, for example [0,10). require(_highBatchBound > _lowBatchBound, ERROR_INVALID_INTERVAL_SEARCH); uint256 interval = _highBatchBound - _lowBatchBound; // Compute an ordered list of random active balance to be searched in the guardians tree uint256[] memory balances = new uint256[](_batchRequestedGuardians); for (uint256 batchGuardianNumber = 0; batchGuardianNumber < _batchRequestedGuardians; batchGuardianNumber++) { // Compute a random seed using: // - The inherent randomness associated to the term from blockhash // - The disputeId, so 2 disputes in the same term will have different outcomes // - The sortition iteration, to avoid getting stuck if resulting guardians are dismissed due to locked balance // - The guardian number in this batch bytes32 seed = keccak256(abi.encodePacked(_termRandomness, _disputeId, _sortitionIteration, batchGuardianNumber)); // Compute a random active balance to be searched in the guardians tree using the generated seed within the // boundaries computed for the current batch. balances[batchGuardianNumber] = _lowBatchBound.add(uint256(seed) % interval); // Make sure it's ordered, flip values if necessary for (uint256 i = batchGuardianNumber; i > 0 && balances[i] < balances[i - 1]; i--) { uint256 tmp = balances[i - 1]; balances[i - 1] = balances[i]; balances[i] = tmp; } } return balances; } } /* * SPDX-License-Identifier: MIT */ interface ILockManager { /** * @dev Tell whether a user can unlock a certain amount of tokens */ function canUnlock(address user, uint256 amount) external view returns (bool); } /* * SPDX-License-Identifier: MIT */ interface IGuardiansRegistry { /** * @dev Assign a requested amount of guardian tokens to a guardian * @param _guardian Guardian to add an amount of tokens to * @param _amount Amount of tokens to be added to the available balance of a guardian */ function assignTokens(address _guardian, uint256 _amount) external; /** * @dev Burn a requested amount of guardian tokens * @param _amount Amount of tokens to be burned */ function burnTokens(uint256 _amount) external; /** * @dev Draft a set of guardians based on given requirements for a term id * @param _params Array containing draft requirements: * 0. bytes32 Term randomness * 1. uint256 Dispute id * 2. uint64 Current term id * 3. uint256 Number of seats already filled * 4. uint256 Number of seats left to be filled * 5. uint64 Number of guardians required for the draft * 6. uint16 Permyriad of the minimum active balance to be locked for the draft * * @return guardians List of guardians selected for the draft * @return length Size of the list of the draft result */ function draft(uint256[7] calldata _params) external returns (address[] memory guardians, uint256 length); /** * @dev Slash a set of guardians based on their votes compared to the winning ruling * @param _termId Current term id * @param _guardians List of guardian addresses to be slashed * @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned * @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not * @return Total amount of slashed tokens */ function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians) external returns (uint256 collectedTokens); /** * @dev Try to collect a certain amount of tokens from a guardian for the next term * @param _guardian Guardian to collect the tokens from * @param _amount Amount of tokens to be collected from the given guardian and for the requested term id * @param _termId Current term id * @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise */ function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external returns (bool); /** * @dev Lock a guardian's withdrawals until a certain term ID * @param _guardian Address of the guardian to be locked * @param _termId Term ID until which the guardian's withdrawals will be locked */ function lockWithdrawals(address _guardian, uint64 _termId) external; /** * @dev Tell the active balance of a guardian for a given term id * @param _guardian Address of the guardian querying the active balance of * @param _termId Term ID querying the active balance for * @return Amount of active tokens for guardian in the requested past term id */ function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256); /** * @dev Tell the total amount of active guardian tokens at the given term id * @param _termId Term ID querying the total active balance for * @return Total amount of active guardian tokens at the given term id */ function totalActiveBalanceAt(uint64 _termId) external view returns (uint256); } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/IsContract.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } contract ACL { string private constant ERROR_BAD_FREEZE = "ACL_BAD_FREEZE"; string private constant ERROR_ROLE_ALREADY_FROZEN = "ACL_ROLE_ALREADY_FROZEN"; string private constant ERROR_INVALID_BULK_INPUT = "ACL_INVALID_BULK_INPUT"; enum BulkOp { Grant, Revoke, Freeze } address internal constant FREEZE_FLAG = address(1); address internal constant ANY_ADDR = address(-1); // List of all roles assigned to different addresses mapping (bytes32 => mapping (address => bool)) public roles; event Granted(bytes32 indexed id, address indexed who); event Revoked(bytes32 indexed id, address indexed who); event Frozen(bytes32 indexed id); /** * @dev Tell whether an address has a role assigned * @param _who Address being queried * @param _id ID of the role being checked * @return True if the requested address has assigned the given role, false otherwise */ function hasRole(address _who, bytes32 _id) public view returns (bool) { return roles[_id][_who] || roles[_id][ANY_ADDR]; } /** * @dev Tell whether a role is frozen * @param _id ID of the role being checked * @return True if the given role is frozen, false otherwise */ function isRoleFrozen(bytes32 _id) public view returns (bool) { return roles[_id][FREEZE_FLAG]; } /** * @dev Internal function to grant a role to a given address * @param _id ID of the role to be granted * @param _who Address to grant the role to */ function _grant(bytes32 _id, address _who) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); require(_who != FREEZE_FLAG, ERROR_BAD_FREEZE); if (!hasRole(_who, _id)) { roles[_id][_who] = true; emit Granted(_id, _who); } } /** * @dev Internal function to revoke a role from a given address * @param _id ID of the role to be revoked * @param _who Address to revoke the role from */ function _revoke(bytes32 _id, address _who) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); if (hasRole(_who, _id)) { roles[_id][_who] = false; emit Revoked(_id, _who); } } /** * @dev Internal function to freeze a role * @param _id ID of the role to be frozen */ function _freeze(bytes32 _id) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); roles[_id][FREEZE_FLAG] = true; emit Frozen(_id); } /** * @dev Internal function to enact a bulk list of ACL operations */ function _bulk(BulkOp[] memory _op, bytes32[] memory _id, address[] memory _who) internal { require(_op.length == _id.length && _op.length == _who.length, ERROR_INVALID_BULK_INPUT); for (uint256 i = 0; i < _op.length; i++) { BulkOp op = _op[i]; if (op == BulkOp.Grant) { _grant(_id[i], _who[i]); } else if (op == BulkOp.Revoke) { _revoke(_id[i], _who[i]); } else if (op == BulkOp.Freeze) { _freeze(_id[i]); } } } } contract ModuleIds { // DisputeManager module ID - keccak256(abi.encodePacked("DISPUTE_MANAGER")) bytes32 internal constant MODULE_ID_DISPUTE_MANAGER = 0x14a6c70f0f6d449c014c7bbc9e68e31e79e8474fb03b7194df83109a2d888ae6; // GuardiansRegistry module ID - keccak256(abi.encodePacked("GUARDIANS_REGISTRY")) bytes32 internal constant MODULE_ID_GUARDIANS_REGISTRY = 0x8af7b7118de65da3b974a3fd4b0c702b66442f74b9dff6eaed1037254c0b79fe; // Voting module ID - keccak256(abi.encodePacked("VOTING")) bytes32 internal constant MODULE_ID_VOTING = 0x7cbb12e82a6d63ff16fe43977f43e3e2b247ecd4e62c0e340da8800a48c67346; // PaymentsBook module ID - keccak256(abi.encodePacked("PAYMENTS_BOOK")) bytes32 internal constant MODULE_ID_PAYMENTS_BOOK = 0xfa275b1417437a2a2ea8e91e9fe73c28eaf0a28532a250541da5ac0d1892b418; // Treasury module ID - keccak256(abi.encodePacked("TREASURY")) bytes32 internal constant MODULE_ID_TREASURY = 0x06aa03964db1f7257357ef09714a5f0ca3633723df419e97015e0c7a3e83edb7; } interface IModulesLinker { /** * @notice Update the implementations of a list of modules * @param _ids List of IDs of the modules to be updated * @param _addresses List of module addresses to be updated */ function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external; } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath64.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules library Uint256Helpers { uint256 private constant MAX_UINT8 = uint8(-1); uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG"; string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint8(uint256 a) internal pure returns (uint8) { require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG); return uint8(a); } function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG); return uint64(a); } } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/TimeHelpers.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } interface IClock { /** * @dev Ensure that the current term of the clock is up-to-date * @return Identification number of the current term */ function ensureCurrentTerm() external returns (uint64); /** * @dev Transition up to a certain number of terms to leave the clock up-to-date * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the term ID after executing the heartbeat transitions */ function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64); /** * @dev Ensure that a certain term has its randomness set * @return Randomness of the current term */ function ensureCurrentTermRandomness() external returns (bytes32); /** * @dev Tell the last ensured term identification number * @return Identification number of the last ensured term */ function getLastEnsuredTermId() external view returns (uint64); /** * @dev Tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function getCurrentTermId() external view returns (uint64); /** * @dev Tell the number of terms the clock should transition to be up-to-date * @return Number of terms the clock should transition to be up-to-date */ function getNeededTermTransitions() external view returns (uint64); /** * @dev Tell the information related to a term based on its ID * @param _termId ID of the term being queried * @return startTime Term start time * @return randomnessBN Block number used for randomness in the requested term * @return randomness Randomness computed for the requested term */ function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness); /** * @dev Tell the randomness of a term even if it wasn't computed yet * @param _termId Identification number of the term being queried * @return Randomness of the requested term */ function getTermRandomness(uint64 _termId) external view returns (bytes32); } contract CourtClock is IClock, TimeHelpers { using SafeMath64 for uint64; string private constant ERROR_TERM_DOES_NOT_EXIST = "CLK_TERM_DOES_NOT_EXIST"; string private constant ERROR_TERM_DURATION_TOO_LONG = "CLK_TERM_DURATION_TOO_LONG"; string private constant ERROR_TERM_RANDOMNESS_NOT_YET = "CLK_TERM_RANDOMNESS_NOT_YET"; string private constant ERROR_TERM_RANDOMNESS_UNAVAILABLE = "CLK_TERM_RANDOMNESS_UNAVAILABLE"; string private constant ERROR_BAD_FIRST_TERM_START_TIME = "CLK_BAD_FIRST_TERM_START_TIME"; string private constant ERROR_TOO_MANY_TRANSITIONS = "CLK_TOO_MANY_TRANSITIONS"; string private constant ERROR_INVALID_TRANSITION_TERMS = "CLK_INVALID_TRANSITION_TERMS"; string private constant ERROR_CANNOT_DELAY_STARTED_COURT = "CLK_CANNOT_DELAY_STARTED_PROT"; string private constant ERROR_CANNOT_DELAY_PAST_START_TIME = "CLK_CANNOT_DELAY_PAST_START_TIME"; // Maximum number of term transitions a callee may have to assume in order to call certain functions that require the Court being up-to-date uint64 internal constant MAX_AUTO_TERM_TRANSITIONS_ALLOWED = 1; // Max duration in seconds that a term can last uint64 internal constant MAX_TERM_DURATION = 365 days; // Max time until first term starts since contract is deployed uint64 internal constant MAX_FIRST_TERM_DELAY_PERIOD = 2 * MAX_TERM_DURATION; struct Term { uint64 startTime; // Timestamp when the term started uint64 randomnessBN; // Block number for entropy bytes32 randomness; // Entropy from randomnessBN block hash } // Duration in seconds for each term of the Court uint64 private termDuration; // Last ensured term id uint64 private termId; // List of Court terms indexed by id mapping (uint64 => Term) private terms; event Heartbeat(uint64 previousTermId, uint64 currentTermId); event StartTimeDelayed(uint64 previousStartTime, uint64 currentStartTime); /** * @dev Ensure a certain term has already been processed * @param _termId Identification number of the term to be checked */ modifier termExists(uint64 _termId) { require(_termId <= termId, ERROR_TERM_DOES_NOT_EXIST); _; } /** * @dev Constructor function * @param _termParams Array containing: * 0. _termDuration Duration in seconds per term * 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding) */ constructor(uint64[2] memory _termParams) public { uint64 _termDuration = _termParams[0]; uint64 _firstTermStartTime = _termParams[1]; require(_termDuration < MAX_TERM_DURATION, ERROR_TERM_DURATION_TOO_LONG); require(_firstTermStartTime >= getTimestamp64() + _termDuration, ERROR_BAD_FIRST_TERM_START_TIME); require(_firstTermStartTime <= getTimestamp64() + MAX_FIRST_TERM_DELAY_PERIOD, ERROR_BAD_FIRST_TERM_START_TIME); termDuration = _termDuration; // No need for SafeMath: we already checked values above terms[0].startTime = _firstTermStartTime - _termDuration; } /** * @notice Ensure that the current term of the Court is up-to-date. If the Court is outdated by more than `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` * terms, the heartbeat function must be called manually instead. * @return Identification number of the current term */ function ensureCurrentTerm() external returns (uint64) { return _ensureCurrentTerm(); } /** * @notice Transition up to `_maxRequestedTransitions` terms * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the term ID after executing the heartbeat transitions */ function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64) { return _heartbeat(_maxRequestedTransitions); } /** * @notice Ensure that a certain term has its randomness set. As we allow to draft disputes requested for previous terms, if there * were mined more than 256 blocks for the current term, the blockhash of its randomness BN is no longer available, given * round will be able to be drafted in the following term. * @return Randomness of the current term */ function ensureCurrentTermRandomness() external returns (bytes32) { // If the randomness for the given term was already computed, return uint64 currentTermId = termId; Term storage term = terms[currentTermId]; bytes32 termRandomness = term.randomness; if (termRandomness != bytes32(0)) { return termRandomness; } // Compute term randomness bytes32 newRandomness = _computeTermRandomness(currentTermId); require(newRandomness != bytes32(0), ERROR_TERM_RANDOMNESS_UNAVAILABLE); term.randomness = newRandomness; return newRandomness; } /** * @dev Tell the term duration of the Court * @return Duration in seconds of the Court term */ function getTermDuration() external view returns (uint64) { return termDuration; } /** * @dev Tell the last ensured term identification number * @return Identification number of the last ensured term */ function getLastEnsuredTermId() external view returns (uint64) { return _lastEnsuredTermId(); } /** * @dev Tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function getCurrentTermId() external view returns (uint64) { return _currentTermId(); } /** * @dev Tell the number of terms the Court should transition to be up-to-date * @return Number of terms the Court should transition to be up-to-date */ function getNeededTermTransitions() external view returns (uint64) { return _neededTermTransitions(); } /** * @dev Tell the information related to a term based on its ID. Note that if the term has not been reached, the * information returned won't be computed yet. This function allows querying future terms that were not computed yet. * @param _termId ID of the term being queried * @return startTime Term start time * @return randomnessBN Block number used for randomness in the requested term * @return randomness Randomness computed for the requested term */ function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness) { Term storage term = terms[_termId]; return (term.startTime, term.randomnessBN, term.randomness); } /** * @dev Tell the randomness of a term even if it wasn't computed yet * @param _termId Identification number of the term being queried * @return Randomness of the requested term */ function getTermRandomness(uint64 _termId) external view termExists(_termId) returns (bytes32) { return _computeTermRandomness(_termId); } /** * @dev Internal function to ensure that the current term of the Court is up-to-date. If the Court is outdated by more than * `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` terms, the heartbeat function must be called manually. * @return Identification number of the resultant term ID after executing the corresponding transitions */ function _ensureCurrentTerm() internal returns (uint64) { // Check the required number of transitions does not exceeds the max allowed number to be processed automatically uint64 requiredTransitions = _neededTermTransitions(); require(requiredTransitions <= MAX_AUTO_TERM_TRANSITIONS_ALLOWED, ERROR_TOO_MANY_TRANSITIONS); // If there are no transitions pending, return the last ensured term id if (uint256(requiredTransitions) == 0) { return termId; } // Process transition if there is at least one pending return _heartbeat(requiredTransitions); } /** * @dev Internal function to transition the Court terms up to a requested number of terms * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the resultant term ID after executing the requested transitions */ function _heartbeat(uint64 _maxRequestedTransitions) internal returns (uint64) { // Transition the minimum number of terms between the amount requested and the amount actually needed uint64 neededTransitions = _neededTermTransitions(); uint256 transitions = uint256(_maxRequestedTransitions < neededTransitions ? _maxRequestedTransitions : neededTransitions); require(transitions > 0, ERROR_INVALID_TRANSITION_TERMS); uint64 blockNumber = getBlockNumber64(); uint64 previousTermId = termId; uint64 currentTermId = previousTermId; for (uint256 transition = 1; transition <= transitions; transition++) { // Term IDs are incremented by one based on the number of time periods since the Court started. Since time is represented in uint64, // even if we chose the minimum duration possible for a term (1 second), we can ensure terms will never reach 2^64 since time is // already assumed to fit in uint64. Term storage previousTerm = terms[currentTermId++]; Term storage currentTerm = terms[currentTermId]; _onTermTransitioned(currentTermId); // Set the start time of the new term. Note that we are using a constant term duration value to guarantee // equally long terms, regardless of heartbeats. currentTerm.startTime = previousTerm.startTime.add(termDuration); // In order to draft a random number of guardians in a term, we use a randomness factor for each term based on a // block number that is set once the term has started. Note that this information could not be known beforehand. currentTerm.randomnessBN = blockNumber + 1; } termId = currentTermId; emit Heartbeat(previousTermId, currentTermId); return currentTermId; } /** * @dev Internal function to delay the first term start time only if it wasn't reached yet * @param _newFirstTermStartTime New timestamp in seconds when the court will open */ function _delayStartTime(uint64 _newFirstTermStartTime) internal { require(_currentTermId() == 0, ERROR_CANNOT_DELAY_STARTED_COURT); Term storage term = terms[0]; uint64 currentFirstTermStartTime = term.startTime.add(termDuration); require(_newFirstTermStartTime > currentFirstTermStartTime, ERROR_CANNOT_DELAY_PAST_START_TIME); // No need for SafeMath: we already checked above that `_newFirstTermStartTime` > `currentFirstTermStartTime` >= `termDuration` term.startTime = _newFirstTermStartTime - termDuration; emit StartTimeDelayed(currentFirstTermStartTime, _newFirstTermStartTime); } /** * @dev Internal function to notify when a term has been transitioned. This function must be overridden to provide custom behavior. * @param _termId Identification number of the new current term that has been transitioned */ function _onTermTransitioned(uint64 _termId) internal; /** * @dev Internal function to tell the last ensured term identification number * @return Identification number of the last ensured term */ function _lastEnsuredTermId() internal view returns (uint64) { return termId; } /** * @dev Internal function to tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function _currentTermId() internal view returns (uint64) { return termId.add(_neededTermTransitions()); } /** * @dev Internal function to tell the number of terms the Court should transition to be up-to-date * @return Number of terms the Court should transition to be up-to-date */ function _neededTermTransitions() internal view returns (uint64) { // Note that the Court is always initialized providing a start time for the first-term in the future. If that's the case, // no term transitions are required. uint64 currentTermStartTime = terms[termId].startTime; if (getTimestamp64() < currentTermStartTime) { return uint64(0); } // No need for SafeMath: we already know that the start time of the current term is in the past return (getTimestamp64() - currentTermStartTime) / termDuration; } /** * @dev Internal function to compute the randomness that will be used to draft guardians for the given term. This * function assumes the given term exists. To determine the randomness factor for a term we use the hash of a * block number that is set once the term has started to ensure it cannot be known beforehand. Note that the * hash function being used only works for the 256 most recent block numbers. * @param _termId Identification number of the term being queried * @return Randomness computed for the given term */ function _computeTermRandomness(uint64 _termId) internal view returns (bytes32) { Term storage term = terms[_termId]; require(getBlockNumber64() > term.randomnessBN, ERROR_TERM_RANDOMNESS_NOT_YET); return blockhash(term.randomnessBN); } } interface IConfig { /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ); /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct); /** * @dev Tell the min active balance config at a certain term * @param _termId Term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256); } contract CourtConfigData { struct Config { FeesConfig fees; // Full fees-related config DisputesConfig disputes; // Full disputes-related config uint256 minActiveBalance; // Minimum amount of tokens guardians have to activate to participate in the Court } struct FeesConfig { IERC20 token; // ERC20 token to be used for the fees of the Court uint16 finalRoundReduction; // Permyriad of fees reduction applied for final appeal round (‱ - 1/10,000) uint256 guardianFee; // Amount of tokens paid to draft a guardian to adjudicate a dispute uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians uint256 settleFee; // Amount of tokens paid per round to cover the costs of slashing guardians } struct DisputesConfig { uint64 evidenceTerms; // Max submitting evidence period duration in terms uint64 commitTerms; // Committing period duration in terms uint64 revealTerms; // Revealing period duration in terms uint64 appealTerms; // Appealing period duration in terms uint64 appealConfirmTerms; // Confirmation appeal period duration in terms uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) uint64 firstRoundGuardiansNumber; // Number of guardians drafted on first round uint64 appealStepFactor; // Factor in which the guardians number is increased on each appeal uint64 finalRoundLockTerms; // Period a coherent guardian in the final round will remain locked uint256 maxRegularAppealRounds; // Before the final appeal uint256 appealCollateralFactor; // Permyriad multiple of dispute fees required to appeal a preliminary ruling (‱ - 1/10,000) uint256 appealConfirmCollateralFactor; // Permyriad multiple of dispute fees required to confirm appeal (‱ - 1/10,000) } struct DraftConfig { IERC20 feeToken; // ERC20 token to be used for the fees of the Court uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians } } contract CourtConfig is IConfig, CourtConfigData { using SafeMath64 for uint64; using PctHelpers for uint256; string private constant ERROR_TOO_OLD_TERM = "CONF_TOO_OLD_TERM"; string private constant ERROR_INVALID_PENALTY_PCT = "CONF_INVALID_PENALTY_PCT"; string private constant ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT = "CONF_INVALID_FINAL_ROUND_RED_PCT"; string private constant ERROR_INVALID_MAX_APPEAL_ROUNDS = "CONF_INVALID_MAX_APPEAL_ROUNDS"; string private constant ERROR_LARGE_ROUND_PHASE_DURATION = "CONF_LARGE_ROUND_PHASE_DURATION"; string private constant ERROR_BAD_INITIAL_GUARDIANS_NUMBER = "CONF_BAD_INITIAL_GUARDIAN_NUMBER"; string private constant ERROR_BAD_APPEAL_STEP_FACTOR = "CONF_BAD_APPEAL_STEP_FACTOR"; string private constant ERROR_ZERO_COLLATERAL_FACTOR = "CONF_ZERO_COLLATERAL_FACTOR"; string private constant ERROR_ZERO_MIN_ACTIVE_BALANCE = "CONF_ZERO_MIN_ACTIVE_BALANCE"; // Max number of terms that each of the different adjudication states can last (if lasted 1h, this would be a year) uint64 internal constant MAX_ADJ_STATE_DURATION = 8670; // Cap the max number of regular appeal rounds uint256 internal constant MAX_REGULAR_APPEAL_ROUNDS_LIMIT = 10; // Future term ID in which a config change has been scheduled uint64 private configChangeTermId; // List of all the configs used in the Court Config[] private configs; // List of configs indexed by id mapping (uint64 => uint256) private configIdByTerm; event NewConfig(uint64 fromTermId, uint64 courtConfigId); /** * @dev Constructor function * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ constructor( IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) public { // Leave config at index 0 empty for non-scheduled config changes configs.length = 1; _setConfig( 0, 0, _feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance ); } /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ); /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct); /** * @dev Tell the min active balance config at a certain term * @param _termId Term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256); /** * @dev Tell the term identification number of the next scheduled config change * @return Term identification number of the next scheduled config change */ function getConfigChangeTermId() external view returns (uint64) { return configChangeTermId; } /** * @dev Internal to make sure to set a config for the new term, it will copy the previous term config if none * @param _termId Identification number of the new current term that has been transitioned */ function _ensureTermConfig(uint64 _termId) internal { // If the term being transitioned had no config change scheduled, keep the previous one uint256 currentConfigId = configIdByTerm[_termId]; if (currentConfigId == 0) { uint256 previousConfigId = configIdByTerm[_termId.sub(1)]; configIdByTerm[_termId] = previousConfigId; } } /** * @dev Assumes that sender it's allowed (either it's from governor or it's on init) * @param _termId Identification number of the current Court term * @param _fromTermId Identification number of the term in which the config will be effective at * @param _feeToken Address of the token contract that is used to pay for fees. * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ function _setConfig( uint64 _termId, uint64 _fromTermId, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) internal { // If the current term is not zero, changes must be scheduled at least after the current period. // No need to ensure delays for on-going disputes since these already use their creation term for that. require(_termId == 0 || _fromTermId > _termId, ERROR_TOO_OLD_TERM); // Make sure appeal collateral factors are greater than zero require(_appealCollateralParams[0] > 0 && _appealCollateralParams[1] > 0, ERROR_ZERO_COLLATERAL_FACTOR); // Make sure the given penalty and final round reduction pcts are not greater than 100% require(PctHelpers.isValid(_pcts[0]), ERROR_INVALID_PENALTY_PCT); require(PctHelpers.isValid(_pcts[1]), ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT); // Disputes must request at least one guardian to be drafted initially require(_roundParams[0] > 0, ERROR_BAD_INITIAL_GUARDIANS_NUMBER); // Prevent that further rounds have zero guardians require(_roundParams[1] > 0, ERROR_BAD_APPEAL_STEP_FACTOR); // Make sure the max number of appeals allowed does not reach the limit uint256 _maxRegularAppealRounds = _roundParams[2]; bool isMaxAppealRoundsValid = _maxRegularAppealRounds > 0 && _maxRegularAppealRounds <= MAX_REGULAR_APPEAL_ROUNDS_LIMIT; require(isMaxAppealRoundsValid, ERROR_INVALID_MAX_APPEAL_ROUNDS); // Make sure each adjudication round phase duration is valid for (uint i = 0; i < _roundStateDurations.length; i++) { require(_roundStateDurations[i] > 0 && _roundStateDurations[i] < MAX_ADJ_STATE_DURATION, ERROR_LARGE_ROUND_PHASE_DURATION); } // Make sure min active balance is not zero require(_minActiveBalance > 0, ERROR_ZERO_MIN_ACTIVE_BALANCE); // If there was a config change already scheduled, reset it (in that case we will overwrite last array item). // Otherwise, schedule a new config. if (configChangeTermId > _termId) { configIdByTerm[configChangeTermId] = 0; } else { configs.length++; } uint64 courtConfigId = uint64(configs.length - 1); Config storage config = configs[courtConfigId]; config.fees = FeesConfig({ token: _feeToken, guardianFee: _fees[0], draftFee: _fees[1], settleFee: _fees[2], finalRoundReduction: _pcts[1] }); config.disputes = DisputesConfig({ evidenceTerms: _roundStateDurations[0], commitTerms: _roundStateDurations[1], revealTerms: _roundStateDurations[2], appealTerms: _roundStateDurations[3], appealConfirmTerms: _roundStateDurations[4], penaltyPct: _pcts[0], firstRoundGuardiansNumber: _roundParams[0], appealStepFactor: _roundParams[1], maxRegularAppealRounds: _maxRegularAppealRounds, finalRoundLockTerms: _roundParams[3], appealCollateralFactor: _appealCollateralParams[0], appealConfirmCollateralFactor: _appealCollateralParams[1] }); config.minActiveBalance = _minActiveBalance; configIdByTerm[_fromTermId] = courtConfigId; configChangeTermId = _fromTermId; emit NewConfig(_fromTermId, courtConfigId); } /** * @dev Internal function to get the Court config for a given term * @param _termId Identification number of the term querying the Court config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of guardian tokens that can be activated */ function _getConfigAt(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); FeesConfig storage feesConfig = config.fees; feeToken = feesConfig.token; fees = [feesConfig.guardianFee, feesConfig.draftFee, feesConfig.settleFee]; DisputesConfig storage disputesConfig = config.disputes; roundStateDurations = [ disputesConfig.evidenceTerms, disputesConfig.commitTerms, disputesConfig.revealTerms, disputesConfig.appealTerms, disputesConfig.appealConfirmTerms ]; pcts = [disputesConfig.penaltyPct, feesConfig.finalRoundReduction]; roundParams = [ disputesConfig.firstRoundGuardiansNumber, disputesConfig.appealStepFactor, uint64(disputesConfig.maxRegularAppealRounds), disputesConfig.finalRoundLockTerms ]; appealCollateralParams = [disputesConfig.appealCollateralFactor, disputesConfig.appealConfirmCollateralFactor]; minActiveBalance = config.minActiveBalance; } /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function _getDraftConfig(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); return (config.fees.token, config.fees.draftFee, config.disputes.penaltyPct); } /** * @dev Internal function to get the min active balance config for a given term * @param _termId Identification number of the term querying the min active balance config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Minimum amount of guardian tokens that can be activated at the given term */ function _getMinActiveBalance(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); return config.minActiveBalance; } /** * @dev Internal function to get the Court config for a given term * @param _termId Identification number of the term querying the min active balance config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Court config for the given term */ function _getConfigFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (Config storage) { uint256 id = _getConfigIdFor(_termId, _lastEnsuredTermId); return configs[id]; } /** * @dev Internal function to get the Court config ID for a given term * @param _termId Identification number of the term querying the Court config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Identification number of the config for the given terms */ function _getConfigIdFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) { // If the given term is lower or equal to the last ensured Court term, it is safe to use a past Court config if (_termId <= _lastEnsuredTermId) { return configIdByTerm[_termId]; } // If the given term is in the future but there is a config change scheduled before it, use the incoming config uint64 scheduledChangeTermId = configChangeTermId; if (scheduledChangeTermId <= _termId) { return configIdByTerm[scheduledChangeTermId]; } // If no changes are scheduled, use the Court config of the last ensured term return configIdByTerm[_lastEnsuredTermId]; } } /* * SPDX-License-Identifier: MIT */ interface IArbitrator { /** * @dev Create a dispute over the Arbitrable sender with a number of possible rulings * @param _possibleRulings Number of possible rulings allowed for the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identification number */ function createDispute(uint256 _possibleRulings, bytes calldata _metadata) external returns (uint256); /** * @dev Submit evidence for a dispute * @param _disputeId Id of the dispute in the Court * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence related to the dispute */ function submitEvidence(uint256 _disputeId, address _submitter, bytes calldata _evidence) external; /** * @dev Close the evidence period of a dispute * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(uint256 _disputeId) external; /** * @notice Rule dispute #`_disputeId` if ready * @param _disputeId Identification number of the dispute to be ruled * @return subject Subject associated to the dispute * @return ruling Ruling number computed for the given dispute */ function rule(uint256 _disputeId) external returns (address subject, uint256 ruling); /** * @dev Tell the dispute fees information to create a dispute * @return recipient Address where the corresponding dispute fees must be transferred to * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees that must be allowed to the recipient */ function getDisputeFees() external view returns (address recipient, IERC20 feeToken, uint256 feeAmount); /** * @dev Tell the payments recipient address * @return Address of the payments recipient module */ function getPaymentsRecipient() external view returns (address); } /* * SPDX-License-Identifier: MIT */ /** * @dev The Arbitrable instances actually don't require to follow any specific interface. * Note that this is actually optional, although it does allow the Court to at least have a way to identify a specific set of instances. */ contract IArbitrable { /** * @dev Emitted when an IArbitrable instance's dispute is ruled by an IArbitrator * @param arbitrator IArbitrator instance ruling the dispute * @param disputeId Identification number of the dispute being ruled by the arbitrator * @param ruling Ruling given by the arbitrator */ event Ruled(IArbitrator indexed arbitrator, uint256 indexed disputeId, uint256 ruling); } interface IDisputeManager { enum DisputeState { PreDraft, Adjudicating, Ruled } enum AdjudicationState { Invalid, Committing, Revealing, Appealing, ConfirmingAppeal, Ended } /** * @dev Create a dispute to be drafted in a future term * @param _subject Arbitrable instance creating the dispute * @param _possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identification number */ function createDispute(IArbitrable _subject, uint8 _possibleRulings, bytes calldata _metadata) external returns (uint256); /** * @dev Submit evidence for a dispute * @param _subject Arbitrable instance submitting the dispute * @param _disputeId Identification number of the dispute receiving new evidence * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence of the dispute */ function submitEvidence(IArbitrable _subject, uint256 _disputeId, address _submitter, bytes calldata _evidence) external; /** * @dev Close the evidence period of a dispute * @param _subject IArbitrable instance requesting to close the evidence submission period * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(IArbitrable _subject, uint256 _disputeId) external; /** * @dev Draft guardians for the next round of a dispute * @param _disputeId Identification number of the dispute to be drafted */ function draft(uint256 _disputeId) external; /** * @dev Appeal round of a dispute in favor of a certain ruling * @param _disputeId Identification number of the dispute being appealed * @param _roundId Identification number of the dispute round being appealed * @param _ruling Ruling appealing a dispute round in favor of */ function createAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external; /** * @dev Confirm appeal for a round of a dispute in favor of a ruling * @param _disputeId Identification number of the dispute confirming an appeal of * @param _roundId Identification number of the dispute round confirming an appeal of * @param _ruling Ruling being confirmed against a dispute round appeal */ function confirmAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external; /** * @dev Compute the final ruling for a dispute * @param _disputeId Identification number of the dispute to compute its final ruling * @return subject Arbitrable instance associated to the dispute * @return finalRuling Final ruling decided for the given dispute */ function computeRuling(uint256 _disputeId) external returns (IArbitrable subject, uint8 finalRuling); /** * @dev Settle penalties for a round of a dispute * @param _disputeId Identification number of the dispute to settle penalties for * @param _roundId Identification number of the dispute round to settle penalties for * @param _guardiansToSettle Maximum number of guardians to be slashed in this call */ function settlePenalties(uint256 _disputeId, uint256 _roundId, uint256 _guardiansToSettle) external; /** * @dev Claim rewards for a round of a dispute for guardian * @dev For regular rounds, it will only reward winning guardians * @param _disputeId Identification number of the dispute to settle rewards for * @param _roundId Identification number of the dispute round to settle rewards for * @param _guardian Address of the guardian to settle their rewards */ function settleReward(uint256 _disputeId, uint256 _roundId, address _guardian) external; /** * @dev Settle appeal deposits for a round of a dispute * @param _disputeId Identification number of the dispute to settle appeal deposits for * @param _roundId Identification number of the dispute round to settle appeal deposits for */ function settleAppealDeposit(uint256 _disputeId, uint256 _roundId) external; /** * @dev Tell the amount of token fees required to create a dispute * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees to be paid for a dispute at the given term */ function getDisputeFees() external view returns (IERC20 feeToken, uint256 feeAmount); /** * @dev Tell information of a certain dispute * @param _disputeId Identification number of the dispute being queried * @return subject Arbitrable subject being disputed * @return possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @return state Current state of the dispute being queried: pre-draft, adjudicating, or ruled * @return finalRuling The winning ruling in case the dispute is finished * @return lastRoundId Identification number of the last round created for the dispute * @return createTermId Identification number of the term when the dispute was created */ function getDispute(uint256 _disputeId) external view returns (IArbitrable subject, uint8 possibleRulings, DisputeState state, uint8 finalRuling, uint256 lastRoundId, uint64 createTermId); /** * @dev Tell information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @return draftTerm Term from which the requested round can be drafted * @return delayedTerms Number of terms the given round was delayed based on its requested draft term id * @return guardiansNumber Number of guardians requested for the round * @return selectedGuardians Number of guardians already selected for the requested round * @return settledPenalties Whether or not penalties have been settled for the requested round * @return collectedTokens Amount of guardian tokens that were collected from slashed guardians for the requested round * @return coherentGuardians Number of guardians that voted in favor of the final ruling in the requested round * @return state Adjudication state of the requested round */ function getRound(uint256 _disputeId, uint256 _roundId) external view returns ( uint64 draftTerm, uint64 delayedTerms, uint64 guardiansNumber, uint64 selectedGuardians, uint256 guardianFees, bool settledPenalties, uint256 collectedTokens, uint64 coherentGuardians, AdjudicationState state ); /** * @dev Tell appeal-related information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @return maker Address of the account appealing the given round * @return appealedRuling Ruling confirmed by the appealer of the given round * @return taker Address of the account confirming the appeal of the given round * @return opposedRuling Ruling confirmed by the appeal taker of the given round */ function getAppeal(uint256 _disputeId, uint256 _roundId) external view returns (address maker, uint64 appealedRuling, address taker, uint64 opposedRuling); /** * @dev Tell information related to the next round due to an appeal of a certain round given. * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round requesting the appeal details of * @return nextRoundStartTerm Term ID from which the next round will start * @return nextRoundGuardiansNumber Guardians number for the next round * @return newDisputeState New state for the dispute associated to the given round after the appeal * @return feeToken ERC20 token used for the next round fees * @return guardianFees Total amount of fees to be distributed between the winning guardians of the next round * @return totalFees Total amount of fees for a regular round at the given term * @return appealDeposit Amount to be deposit of fees for a regular round at the given term * @return confirmAppealDeposit Total amount of fees for a regular round at the given term */ function getNextRoundDetails(uint256 _disputeId, uint256 _roundId) external view returns ( uint64 nextRoundStartTerm, uint64 nextRoundGuardiansNumber, DisputeState newDisputeState, IERC20 feeToken, uint256 totalFees, uint256 guardianFees, uint256 appealDeposit, uint256 confirmAppealDeposit ); /** * @dev Tell guardian-related information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @param _guardian Address of the guardian being queried * @return weight Guardian weight drafted for the requested round * @return rewarded Whether or not the given guardian was rewarded based on the requested round */ function getGuardian(uint256 _disputeId, uint256 _roundId, address _guardian) external view returns (uint64 weight, bool rewarded); } contract Controller is IsContract, ModuleIds, CourtClock, CourtConfig, ACL { string private constant ERROR_SENDER_NOT_GOVERNOR = "CTR_SENDER_NOT_GOVERNOR"; string private constant ERROR_INVALID_GOVERNOR_ADDRESS = "CTR_INVALID_GOVERNOR_ADDRESS"; string private constant ERROR_MODULE_NOT_SET = "CTR_MODULE_NOT_SET"; string private constant ERROR_MODULE_ALREADY_ENABLED = "CTR_MODULE_ALREADY_ENABLED"; string private constant ERROR_MODULE_ALREADY_DISABLED = "CTR_MODULE_ALREADY_DISABLED"; string private constant ERROR_DISPUTE_MANAGER_NOT_ACTIVE = "CTR_DISPUTE_MANAGER_NOT_ACTIVE"; string private constant ERROR_CUSTOM_FUNCTION_NOT_SET = "CTR_CUSTOM_FUNCTION_NOT_SET"; string private constant ERROR_IMPLEMENTATION_NOT_CONTRACT = "CTR_IMPLEMENTATION_NOT_CONTRACT"; string private constant ERROR_INVALID_IMPLS_INPUT_LENGTH = "CTR_INVALID_IMPLS_INPUT_LENGTH"; address private constant ZERO_ADDRESS = address(0); /** * @dev Governor of the whole system. Set of three addresses to recover funds, change configuration settings and setup modules */ struct Governor { address funds; // This address can be unset at any time. It is allowed to recover funds from the ControlledRecoverable modules address config; // This address is meant not to be unset. It is allowed to change the different configurations of the whole system address modules; // This address can be unset at any time. It is allowed to plug/unplug modules from the system } /** * @dev Module information */ struct Module { bytes32 id; // ID associated to a module bool disabled; // Whether the module is disabled } // Governor addresses of the system Governor private governor; // List of current modules registered for the system indexed by ID mapping (bytes32 => address) internal currentModules; // List of all historical modules registered for the system indexed by address mapping (address => Module) internal allModules; // List of custom function targets indexed by signature mapping (bytes4 => address) internal customFunctions; event ModuleSet(bytes32 id, address addr); event ModuleEnabled(bytes32 id, address addr); event ModuleDisabled(bytes32 id, address addr); event CustomFunctionSet(bytes4 signature, address target); event FundsGovernorChanged(address previousGovernor, address currentGovernor); event ConfigGovernorChanged(address previousGovernor, address currentGovernor); event ModulesGovernorChanged(address previousGovernor, address currentGovernor); /** * @dev Ensure the msg.sender is the funds governor */ modifier onlyFundsGovernor { require(msg.sender == governor.funds, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the modules governor */ modifier onlyConfigGovernor { require(msg.sender == governor.config, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the modules governor */ modifier onlyModulesGovernor { require(msg.sender == governor.modules, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the given dispute manager is active */ modifier onlyActiveDisputeManager(IDisputeManager _disputeManager) { require(!_isModuleDisabled(address(_disputeManager)), ERROR_DISPUTE_MANAGER_NOT_ACTIVE); _; } /** * @dev Constructor function * @param _termParams Array containing: * 0. _termDuration Duration in seconds per term * 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding) * @param _governors Array containing: * 0. _fundsGovernor Address of the funds governor * 1. _configGovernor Address of the config governor * 2. _modulesGovernor Address of the modules governor * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling * 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ constructor( uint64[2] memory _termParams, address[3] memory _governors, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) public CourtClock(_termParams) CourtConfig(_feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance) { _setFundsGovernor(_governors[0]); _setConfigGovernor(_governors[1]); _setModulesGovernor(_governors[2]); } /** * @dev Fallback function allows to forward calls to a specific address in case it was previously registered * Note the sender will be always the controller in case it is forwarded */ function () external payable { address target = customFunctions[msg.sig]; require(target != address(0), ERROR_CUSTOM_FUNCTION_NOT_SET); // solium-disable-next-line security/no-call-value (bool success,) = address(target).call.value(msg.value)(msg.data); assembly { let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) let result := success switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } /** * @notice Change Court configuration params * @param _fromTermId Identification number of the term in which the config will be effective at * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling * 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ function setConfig( uint64 _fromTermId, IERC20 _feeToken, uint256[3] calldata _fees, uint64[5] calldata _roundStateDurations, uint16[2] calldata _pcts, uint64[4] calldata _roundParams, uint256[2] calldata _appealCollateralParams, uint256 _minActiveBalance ) external onlyConfigGovernor { uint64 currentTermId = _ensureCurrentTerm(); _setConfig( currentTermId, _fromTermId, _feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance ); } /** * @notice Delay the Court start time to `_newFirstTermStartTime` * @param _newFirstTermStartTime New timestamp in seconds when the court will open */ function delayStartTime(uint64 _newFirstTermStartTime) external onlyConfigGovernor { _delayStartTime(_newFirstTermStartTime); } /** * @notice Change funds governor address to `_newFundsGovernor` * @param _newFundsGovernor Address of the new funds governor to be set */ function changeFundsGovernor(address _newFundsGovernor) external onlyFundsGovernor { require(_newFundsGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setFundsGovernor(_newFundsGovernor); } /** * @notice Change config governor address to `_newConfigGovernor` * @param _newConfigGovernor Address of the new config governor to be set */ function changeConfigGovernor(address _newConfigGovernor) external onlyConfigGovernor { require(_newConfigGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setConfigGovernor(_newConfigGovernor); } /** * @notice Change modules governor address to `_newModulesGovernor` * @param _newModulesGovernor Address of the new governor to be set */ function changeModulesGovernor(address _newModulesGovernor) external onlyModulesGovernor { require(_newModulesGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setModulesGovernor(_newModulesGovernor); } /** * @notice Remove the funds governor. Set the funds governor to the zero address. * @dev This action cannot be rolled back, once the funds governor has been unset, funds cannot be recovered from recoverable modules anymore */ function ejectFundsGovernor() external onlyFundsGovernor { _setFundsGovernor(ZERO_ADDRESS); } /** * @notice Remove the modules governor. Set the modules governor to the zero address. * @dev This action cannot be rolled back, once the modules governor has been unset, system modules cannot be changed anymore */ function ejectModulesGovernor() external onlyModulesGovernor { _setModulesGovernor(ZERO_ADDRESS); } /** * @notice Grant `_id` role to `_who` * @param _id ID of the role to be granted * @param _who Address to grant the role to */ function grant(bytes32 _id, address _who) external onlyConfigGovernor { _grant(_id, _who); } /** * @notice Revoke `_id` role from `_who` * @param _id ID of the role to be revoked * @param _who Address to revoke the role from */ function revoke(bytes32 _id, address _who) external onlyConfigGovernor { _revoke(_id, _who); } /** * @notice Freeze `_id` role * @param _id ID of the role to be frozen */ function freeze(bytes32 _id) external onlyConfigGovernor { _freeze(_id); } /** * @notice Enact a bulk list of ACL operations */ function bulk(BulkOp[] calldata _op, bytes32[] calldata _id, address[] calldata _who) external onlyConfigGovernor { _bulk(_op, _id, _who); } /** * @notice Set module `_id` to `_addr` * @param _id ID of the module to be set * @param _addr Address of the module to be set */ function setModule(bytes32 _id, address _addr) external onlyModulesGovernor { _setModule(_id, _addr); } /** * @notice Set and link many modules at once * @param _newModuleIds List of IDs of the new modules to be set * @param _newModuleAddresses List of addresses of the new modules to be set * @param _newModuleLinks List of IDs of the modules that will be linked in the new modules being set * @param _currentModulesToBeSynced List of addresses of current modules to be re-linked to the new modules being set */ function setModules( bytes32[] calldata _newModuleIds, address[] calldata _newModuleAddresses, bytes32[] calldata _newModuleLinks, address[] calldata _currentModulesToBeSynced ) external onlyModulesGovernor { // We only care about the modules being set, links are optional require(_newModuleIds.length == _newModuleAddresses.length, ERROR_INVALID_IMPLS_INPUT_LENGTH); // First set the addresses of the new modules or the modules to be updated for (uint256 i = 0; i < _newModuleIds.length; i++) { _setModule(_newModuleIds[i], _newModuleAddresses[i]); } // Then sync the links of the new modules based on the list of IDs specified (ideally the IDs of their dependencies) _syncModuleLinks(_newModuleAddresses, _newModuleLinks); // Finally sync the links of the existing modules to be synced to the new modules being set _syncModuleLinks(_currentModulesToBeSynced, _newModuleIds); } /** * @notice Sync modules for a list of modules IDs based on their current implementation address * @param _modulesToBeSynced List of addresses of connected modules to be synced * @param _idsToBeSet List of IDs of the modules included in the sync */ function syncModuleLinks(address[] calldata _modulesToBeSynced, bytes32[] calldata _idsToBeSet) external onlyModulesGovernor { require(_idsToBeSet.length > 0 && _modulesToBeSynced.length > 0, ERROR_INVALID_IMPLS_INPUT_LENGTH); _syncModuleLinks(_modulesToBeSynced, _idsToBeSet); } /** * @notice Disable module `_addr` * @dev Current modules can be disabled to allow pausing the court. However, these can be enabled back again, see `enableModule` * @param _addr Address of the module to be disabled */ function disableModule(address _addr) external onlyModulesGovernor { Module storage module = allModules[_addr]; _ensureModuleExists(module); require(!module.disabled, ERROR_MODULE_ALREADY_DISABLED); module.disabled = true; emit ModuleDisabled(module.id, _addr); } /** * @notice Enable module `_addr` * @param _addr Address of the module to be enabled */ function enableModule(address _addr) external onlyModulesGovernor { Module storage module = allModules[_addr]; _ensureModuleExists(module); require(module.disabled, ERROR_MODULE_ALREADY_ENABLED); module.disabled = false; emit ModuleEnabled(module.id, _addr); } /** * @notice Set custom function `_sig` for `_target` * @param _sig Signature of the function to be set * @param _target Address of the target implementation to be registered for the given signature */ function setCustomFunction(bytes4 _sig, address _target) external onlyModulesGovernor { customFunctions[_sig] = _target; emit CustomFunctionSet(_sig, _target); } /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getConfigAt(_termId, lastEnsuredTermId); } /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getDraftConfig(_termId, lastEnsuredTermId); } /** * @dev Tell the min active balance config at a certain term * @param _termId Identification number of the term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getMinActiveBalance(_termId, lastEnsuredTermId); } /** * @dev Tell the address of the funds governor * @return Address of the funds governor */ function getFundsGovernor() external view returns (address) { return governor.funds; } /** * @dev Tell the address of the config governor * @return Address of the config governor */ function getConfigGovernor() external view returns (address) { return governor.config; } /** * @dev Tell the address of the modules governor * @return Address of the modules governor */ function getModulesGovernor() external view returns (address) { return governor.modules; } /** * @dev Tell if a given module is active * @param _id ID of the module to be checked * @param _addr Address of the module to be checked * @return True if the given module address has the requested ID and is enabled */ function isActive(bytes32 _id, address _addr) external view returns (bool) { Module storage module = allModules[_addr]; return module.id == _id && !module.disabled; } /** * @dev Tell the current ID and disable status of a module based on a given address * @param _addr Address of the requested module * @return id ID of the module being queried * @return disabled Whether the module has been disabled */ function getModuleByAddress(address _addr) external view returns (bytes32 id, bool disabled) { Module storage module = allModules[_addr]; id = module.id; disabled = module.disabled; } /** * @dev Tell the current address and disable status of a module based on a given ID * @param _id ID of the module being queried * @return addr Current address of the requested module * @return disabled Whether the module has been disabled */ function getModule(bytes32 _id) external view returns (address addr, bool disabled) { return _getModule(_id); } /** * @dev Tell the information for the current DisputeManager module * @return addr Current address of the DisputeManager module * @return disabled Whether the module has been disabled */ function getDisputeManager() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_DISPUTE_MANAGER); } /** * @dev Tell the information for the current GuardiansRegistry module * @return addr Current address of the GuardiansRegistry module * @return disabled Whether the module has been disabled */ function getGuardiansRegistry() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_GUARDIANS_REGISTRY); } /** * @dev Tell the information for the current Voting module * @return addr Current address of the Voting module * @return disabled Whether the module has been disabled */ function getVoting() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_VOTING); } /** * @dev Tell the information for the current PaymentsBook module * @return addr Current address of the PaymentsBook module * @return disabled Whether the module has been disabled */ function getPaymentsBook() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_PAYMENTS_BOOK); } /** * @dev Tell the information for the current Treasury module * @return addr Current address of the Treasury module * @return disabled Whether the module has been disabled */ function getTreasury() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_TREASURY); } /** * @dev Tell the target registered for a custom function * @param _sig Signature of the function being queried * @return Address of the target where the function call will be forwarded */ function getCustomFunction(bytes4 _sig) external view returns (address) { return customFunctions[_sig]; } /** * @dev Internal function to set the address of the funds governor * @param _newFundsGovernor Address of the new config governor to be set */ function _setFundsGovernor(address _newFundsGovernor) internal { emit FundsGovernorChanged(governor.funds, _newFundsGovernor); governor.funds = _newFundsGovernor; } /** * @dev Internal function to set the address of the config governor * @param _newConfigGovernor Address of the new config governor to be set */ function _setConfigGovernor(address _newConfigGovernor) internal { emit ConfigGovernorChanged(governor.config, _newConfigGovernor); governor.config = _newConfigGovernor; } /** * @dev Internal function to set the address of the modules governor * @param _newModulesGovernor Address of the new modules governor to be set */ function _setModulesGovernor(address _newModulesGovernor) internal { emit ModulesGovernorChanged(governor.modules, _newModulesGovernor); governor.modules = _newModulesGovernor; } /** * @dev Internal function to set an address as the current implementation for a module * Note that the disabled condition is not affected, if the module was not set before it will be enabled by default * @param _id Id of the module to be set * @param _addr Address of the module to be set */ function _setModule(bytes32 _id, address _addr) internal { require(isContract(_addr), ERROR_IMPLEMENTATION_NOT_CONTRACT); currentModules[_id] = _addr; allModules[_addr].id = _id; emit ModuleSet(_id, _addr); } /** * @dev Internal function to sync the modules for a list of modules IDs based on their current implementation address * @param _modulesToBeSynced List of addresses of connected modules to be synced * @param _idsToBeSet List of IDs of the modules to be linked */ function _syncModuleLinks(address[] memory _modulesToBeSynced, bytes32[] memory _idsToBeSet) internal { address[] memory addressesToBeSet = new address[](_idsToBeSet.length); // Load the addresses associated with the requested module ids for (uint256 i = 0; i < _idsToBeSet.length; i++) { address moduleAddress = _getModuleAddress(_idsToBeSet[i]); Module storage module = allModules[moduleAddress]; _ensureModuleExists(module); addressesToBeSet[i] = moduleAddress; } // Update the links of all the requested modules for (uint256 j = 0; j < _modulesToBeSynced.length; j++) { IModulesLinker(_modulesToBeSynced[j]).linkModules(_idsToBeSet, addressesToBeSet); } } /** * @dev Internal function to notify when a term has been transitioned * @param _termId Identification number of the new current term that has been transitioned */ function _onTermTransitioned(uint64 _termId) internal { _ensureTermConfig(_termId); } /** * @dev Internal function to check if a module was set * @param _module Module to be checked */ function _ensureModuleExists(Module storage _module) internal view { require(_module.id != bytes32(0), ERROR_MODULE_NOT_SET); } /** * @dev Internal function to tell the information for a module based on a given ID * @param _id ID of the module being queried * @return addr Current address of the requested module * @return disabled Whether the module has been disabled */ function _getModule(bytes32 _id) internal view returns (address addr, bool disabled) { addr = _getModuleAddress(_id); disabled = _isModuleDisabled(addr); } /** * @dev Tell the current address for a module by ID * @param _id ID of the module being queried * @return Current address of the requested module */ function _getModuleAddress(bytes32 _id) internal view returns (address) { return currentModules[_id]; } /** * @dev Tell whether a module is disabled * @param _addr Address of the module being queried * @return True if the module is disabled, false otherwise */ function _isModuleDisabled(address _addr) internal view returns (bool) { return allModules[_addr].disabled; } } contract ConfigConsumer is CourtConfigData { /** * @dev Internal function to fetch the address of the Config module from the controller * @return Address of the Config module */ function _courtConfig() internal view returns (IConfig); /** * @dev Internal function to get the Court config for a certain term * @param _termId Identification number of the term querying the Court config of * @return Court config for the given term */ function _getConfigAt(uint64 _termId) internal view returns (Config memory) { (IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance) = _courtConfig().getConfig(_termId); Config memory config; config.fees = FeesConfig({ token: _feeToken, guardianFee: _fees[0], draftFee: _fees[1], settleFee: _fees[2], finalRoundReduction: _pcts[1] }); config.disputes = DisputesConfig({ evidenceTerms: _roundStateDurations[0], commitTerms: _roundStateDurations[1], revealTerms: _roundStateDurations[2], appealTerms: _roundStateDurations[3], appealConfirmTerms: _roundStateDurations[4], penaltyPct: _pcts[0], firstRoundGuardiansNumber: _roundParams[0], appealStepFactor: _roundParams[1], maxRegularAppealRounds: _roundParams[2], finalRoundLockTerms: _roundParams[3], appealCollateralFactor: _appealCollateralParams[0], appealConfirmCollateralFactor: _appealCollateralParams[1] }); config.minActiveBalance = _minActiveBalance; return config; } /** * @dev Internal function to get the draft config for a given term * @param _termId Identification number of the term querying the draft config of * @return Draft config for the given term */ function _getDraftConfig(uint64 _termId) internal view returns (DraftConfig memory) { (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) = _courtConfig().getDraftConfig(_termId); return DraftConfig({ feeToken: feeToken, draftFee: draftFee, penaltyPct: penaltyPct }); } /** * @dev Internal function to get the min active balance config for a given term * @param _termId Identification number of the term querying the min active balance config of * @return Minimum amount of guardian tokens that can be activated */ function _getMinActiveBalance(uint64 _termId) internal view returns (uint256) { return _courtConfig().getMinActiveBalance(_termId); } } /* * SPDX-License-Identifier: MIT */ interface ICRVotingOwner { /** * @dev Ensure votes can be committed for a vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for */ function ensureCanCommit(uint256 _voteId) external; /** * @dev Ensure a certain voter can commit votes for a vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for * @param _voter Address of the voter querying the weight of */ function ensureCanCommit(uint256 _voteId, address _voter) external; /** * @dev Ensure a certain voter can reveal votes for vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for * @param _voter Address of the voter querying the weight of * @return Weight of the requested guardian for the requested vote instance */ function ensureCanReveal(uint256 _voteId, address _voter) external returns (uint64); } /* * SPDX-License-Identifier: MIT */ interface ICRVoting { /** * @dev Create a new vote instance * @dev This function can only be called by the CRVoting owner * @param _voteId ID of the new vote instance to be created * @param _possibleOutcomes Number of possible outcomes for the new vote instance to be created */ function createVote(uint256 _voteId, uint8 _possibleOutcomes) external; /** * @dev Get the winning outcome of a vote instance * @param _voteId ID of the vote instance querying the winning outcome of * @return Winning outcome of the given vote instance or refused in case it's missing */ function getWinningOutcome(uint256 _voteId) external view returns (uint8); /** * @dev Get the tally of an outcome for a certain vote instance * @param _voteId ID of the vote instance querying the tally of * @param _outcome Outcome querying the tally of * @return Tally of the outcome being queried for the given vote instance */ function getOutcomeTally(uint256 _voteId, uint8 _outcome) external view returns (uint256); /** * @dev Tell whether an outcome is valid for a given vote instance or not * @param _voteId ID of the vote instance to check the outcome of * @param _outcome Outcome to check if valid or not * @return True if the given outcome is valid for the requested vote instance, false otherwise */ function isValidOutcome(uint256 _voteId, uint8 _outcome) external view returns (bool); /** * @dev Get the outcome voted by a voter for a certain vote instance * @param _voteId ID of the vote instance querying the outcome of * @param _voter Address of the voter querying the outcome of * @return Outcome of the voter for the given vote instance */ function getVoterOutcome(uint256 _voteId, address _voter) external view returns (uint8); /** * @dev Tell whether a voter voted in favor of a certain outcome in a vote instance or not * @param _voteId ID of the vote instance to query if a voter voted in favor of a certain outcome * @param _outcome Outcome to query if the given voter voted in favor of * @param _voter Address of the voter to query if voted in favor of the given outcome * @return True if the given voter voted in favor of the given outcome, false otherwise */ function hasVotedInFavorOf(uint256 _voteId, uint8 _outcome, address _voter) external view returns (bool); /** * @dev Filter a list of voters based on whether they voted in favor of a certain outcome in a vote instance or not * @param _voteId ID of the vote instance to be checked * @param _outcome Outcome to filter the list of voters of * @param _voters List of addresses of the voters to be filtered * @return List of results to tell whether a voter voted in favor of the given outcome or not */ function getVotersInFavorOf(uint256 _voteId, uint8 _outcome, address[] calldata _voters) external view returns (bool[] memory); } /* * SPDX-License-Identifier: MIT */ interface ITreasury { /** * @dev Assign a certain amount of tokens to an account * @param _token ERC20 token to be assigned * @param _to Address of the recipient that will be assigned the tokens to * @param _amount Amount of tokens to be assigned to the recipient */ function assign(IERC20 _token, address _to, uint256 _amount) external; /** * @dev Withdraw a certain amount of tokens * @param _token ERC20 token to be withdrawn * @param _from Address withdrawing the tokens from * @param _to Address of the recipient that will receive the tokens * @param _amount Amount of tokens to be withdrawn from the sender */ function withdraw(IERC20 _token, address _from, address _to, uint256 _amount) external; } /* * SPDX-License-Identifier: MIT */ interface IPaymentsBook { /** * @dev Pay an amount of tokens * @param _token Address of the token being paid * @param _amount Amount of tokens being paid * @param _payer Address paying on behalf of * @param _data Optional data */ function pay(address _token, uint256 _amount, address _payer, bytes calldata _data) external payable; } contract Controlled is IModulesLinker, IsContract, ModuleIds, ConfigConsumer { string private constant ERROR_MODULE_NOT_SET = "CTD_MODULE_NOT_SET"; string private constant ERROR_INVALID_MODULES_LINK_INPUT = "CTD_INVALID_MODULES_LINK_INPUT"; string private constant ERROR_CONTROLLER_NOT_CONTRACT = "CTD_CONTROLLER_NOT_CONTRACT"; string private constant ERROR_SENDER_NOT_ALLOWED = "CTD_SENDER_NOT_ALLOWED"; string private constant ERROR_SENDER_NOT_CONTROLLER = "CTD_SENDER_NOT_CONTROLLER"; string private constant ERROR_SENDER_NOT_CONFIG_GOVERNOR = "CTD_SENDER_NOT_CONFIG_GOVERNOR"; string private constant ERROR_SENDER_NOT_ACTIVE_VOTING = "CTD_SENDER_NOT_ACTIVE_VOTING"; string private constant ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER = "CTD_SEND_NOT_ACTIVE_DISPUTE_MGR"; string private constant ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER = "CTD_SEND_NOT_CURRENT_DISPUTE_MGR"; // Address of the controller Controller public controller; // List of modules linked indexed by ID mapping (bytes32 => address) public linkedModules; event ModuleLinked(bytes32 id, address addr); /** * @dev Ensure the msg.sender is the controller's config governor */ modifier onlyConfigGovernor { require(msg.sender == _configGovernor(), ERROR_SENDER_NOT_CONFIG_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the controller */ modifier onlyController() { require(msg.sender == address(controller), ERROR_SENDER_NOT_CONTROLLER); _; } /** * @dev Ensure the msg.sender is an active DisputeManager module */ modifier onlyActiveDisputeManager() { require(controller.isActive(MODULE_ID_DISPUTE_MANAGER, msg.sender), ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER); _; } /** * @dev Ensure the msg.sender is the current DisputeManager module */ modifier onlyCurrentDisputeManager() { (address addr, bool disabled) = controller.getDisputeManager(); require(msg.sender == addr, ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER); require(!disabled, ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER); _; } /** * @dev Ensure the msg.sender is an active Voting module */ modifier onlyActiveVoting() { require(controller.isActive(MODULE_ID_VOTING, msg.sender), ERROR_SENDER_NOT_ACTIVE_VOTING); _; } /** * @dev This modifier will check that the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of */ modifier authenticateSender(address _user) { _authenticateSender(_user); _; } /** * @dev Constructor function * @param _controller Address of the controller */ constructor(Controller _controller) public { require(isContract(address(_controller)), ERROR_CONTROLLER_NOT_CONTRACT); controller = _controller; } /** * @notice Update the implementation links of a list of modules * @dev The controller is expected to ensure the given addresses are correct modules * @param _ids List of IDs of the modules to be updated * @param _addresses List of module addresses to be updated */ function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external onlyController { require(_ids.length == _addresses.length, ERROR_INVALID_MODULES_LINK_INPUT); for (uint256 i = 0; i < _ids.length; i++) { linkedModules[_ids[i]] = _addresses[i]; emit ModuleLinked(_ids[i], _addresses[i]); } } /** * @dev Internal function to ensure the Court term is up-to-date, it will try to update it if not * @return Identification number of the current Court term */ function _ensureCurrentTerm() internal returns (uint64) { return _clock().ensureCurrentTerm(); } /** * @dev Internal function to fetch the last ensured term ID of the Court * @return Identification number of the last ensured term */ function _getLastEnsuredTermId() internal view returns (uint64) { return _clock().getLastEnsuredTermId(); } /** * @dev Internal function to tell the current term identification number * @return Identification number of the current term */ function _getCurrentTermId() internal view returns (uint64) { return _clock().getCurrentTermId(); } /** * @dev Internal function to fetch the controller's config governor * @return Address of the controller's config governor */ function _configGovernor() internal view returns (address) { return controller.getConfigGovernor(); } /** * @dev Internal function to fetch the address of the DisputeManager module * @return Address of the DisputeManager module */ function _disputeManager() internal view returns (IDisputeManager) { return IDisputeManager(_getLinkedModule(MODULE_ID_DISPUTE_MANAGER)); } /** * @dev Internal function to fetch the address of the GuardianRegistry module implementation * @return Address of the GuardianRegistry module implementation */ function _guardiansRegistry() internal view returns (IGuardiansRegistry) { return IGuardiansRegistry(_getLinkedModule(MODULE_ID_GUARDIANS_REGISTRY)); } /** * @dev Internal function to fetch the address of the Voting module implementation * @return Address of the Voting module implementation */ function _voting() internal view returns (ICRVoting) { return ICRVoting(_getLinkedModule(MODULE_ID_VOTING)); } /** * @dev Internal function to fetch the address of the PaymentsBook module implementation * @return Address of the PaymentsBook module implementation */ function _paymentsBook() internal view returns (IPaymentsBook) { return IPaymentsBook(_getLinkedModule(MODULE_ID_PAYMENTS_BOOK)); } /** * @dev Internal function to fetch the address of the Treasury module implementation * @return Address of the Treasury module implementation */ function _treasury() internal view returns (ITreasury) { return ITreasury(_getLinkedModule(MODULE_ID_TREASURY)); } /** * @dev Internal function to tell the address linked for a module based on a given ID * @param _id ID of the module being queried * @return Linked address of the requested module */ function _getLinkedModule(bytes32 _id) internal view returns (address) { address module = linkedModules[_id]; require(module != address(0), ERROR_MODULE_NOT_SET); return module; } /** * @dev Internal function to fetch the address of the Clock module from the controller * @return Address of the Clock module */ function _clock() internal view returns (IClock) { return IClock(controller); } /** * @dev Internal function to fetch the address of the Config module from the controller * @return Address of the Config module */ function _courtConfig() internal view returns (IConfig) { return IConfig(controller); } /** * @dev Ensure that the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of */ function _authenticateSender(address _user) internal view { require(_isSenderAllowed(_user), ERROR_SENDER_NOT_ALLOWED); } /** * @dev Tell whether the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of * @return True if the sender is the user to act on behalf of or someone with the required permission, false otherwise */ function _isSenderAllowed(address _user) internal view returns (bool) { return msg.sender == _user || _hasRole(msg.sender); } /** * @dev Tell whether an address holds the required permission to access the requested functionality * @param _addr Address being checked * @return True if the given address has the required permission to access the requested functionality, false otherwise */ function _hasRole(address _addr) internal view returns (bool) { bytes32 roleId = keccak256(abi.encodePacked(address(this), msg.sig)); return controller.hasRole(_addr, roleId); } } contract ControlledRecoverable is Controlled { using SafeERC20 for IERC20; string private constant ERROR_SENDER_NOT_FUNDS_GOVERNOR = "CTD_SENDER_NOT_FUNDS_GOVERNOR"; string private constant ERROR_INSUFFICIENT_RECOVER_FUNDS = "CTD_INSUFFICIENT_RECOVER_FUNDS"; string private constant ERROR_RECOVER_TOKEN_FUNDS_FAILED = "CTD_RECOVER_TOKEN_FUNDS_FAILED"; event RecoverFunds(address token, address recipient, uint256 balance); /** * @dev Ensure the msg.sender is the controller's funds governor */ modifier onlyFundsGovernor { require(msg.sender == controller.getFundsGovernor(), ERROR_SENDER_NOT_FUNDS_GOVERNOR); _; } /** * @notice Transfer all `_token` tokens to `_to` * @param _token Address of the token to be recovered * @param _to Address of the recipient that will be receive all the funds of the requested token */ function recoverFunds(address _token, address payable _to) external payable onlyFundsGovernor { uint256 balance; if (_token == address(0)) { balance = address(this).balance; require(_to.send(balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED); } else { balance = IERC20(_token).balanceOf(address(this)); require(balance > 0, ERROR_INSUFFICIENT_RECOVER_FUNDS); // No need to verify _token to be a contract as we have already checked the balance require(IERC20(_token).safeTransfer(_to, balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED); } emit RecoverFunds(_token, _to, balance); } } contract GuardiansRegistry is IGuardiansRegistry, ControlledRecoverable { using SafeERC20 for IERC20; using SafeMath for uint256; using PctHelpers for uint256; using HexSumTree for HexSumTree.Tree; using GuardiansTreeSortition for HexSumTree.Tree; string private constant ERROR_NOT_CONTRACT = "GR_NOT_CONTRACT"; string private constant ERROR_INVALID_ZERO_AMOUNT = "GR_INVALID_ZERO_AMOUNT"; string private constant ERROR_INVALID_ACTIVATION_AMOUNT = "GR_INVALID_ACTIVATION_AMOUNT"; string private constant ERROR_INVALID_DEACTIVATION_AMOUNT = "GR_INVALID_DEACTIVATION_AMOUNT"; string private constant ERROR_INVALID_LOCKED_AMOUNTS_LENGTH = "GR_INVALID_LOCKED_AMOUNTS_LEN"; string private constant ERROR_INVALID_REWARDED_GUARDIANS_LENGTH = "GR_INVALID_REWARD_GUARDIANS_LEN"; string private constant ERROR_ACTIVE_BALANCE_BELOW_MIN = "GR_ACTIVE_BALANCE_BELOW_MIN"; string private constant ERROR_NOT_ENOUGH_AVAILABLE_BALANCE = "GR_NOT_ENOUGH_AVAILABLE_BALANCE"; string private constant ERROR_CANNOT_REDUCE_DEACTIVATION_REQUEST = "GR_CANT_REDUCE_DEACTIVATION_REQ"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "GR_TOKEN_TRANSFER_FAILED"; string private constant ERROR_TOKEN_APPROVE_NOT_ALLOWED = "GR_TOKEN_APPROVE_NOT_ALLOWED"; string private constant ERROR_BAD_TOTAL_ACTIVE_BALANCE_LIMIT = "GR_BAD_TOTAL_ACTIVE_BAL_LIMIT"; string private constant ERROR_TOTAL_ACTIVE_BALANCE_EXCEEDED = "GR_TOTAL_ACTIVE_BALANCE_EXCEEDED"; string private constant ERROR_DEACTIVATION_AMOUNT_EXCEEDS_LOCK = "GR_DEACTIV_AMOUNT_EXCEEDS_LOCK"; string private constant ERROR_CANNOT_UNLOCK_ACTIVATION = "GR_CANNOT_UNLOCK_ACTIVATION"; string private constant ERROR_ZERO_LOCK_ACTIVATION = "GR_ZERO_LOCK_ACTIVATION"; string private constant ERROR_INVALID_UNLOCK_ACTIVATION_AMOUNT = "GR_INVALID_UNLOCK_ACTIVAT_AMOUNT"; string private constant ERROR_LOCK_MANAGER_NOT_ALLOWED = "GR_LOCK_MANAGER_NOT_ALLOWED"; string private constant ERROR_WITHDRAWALS_LOCK = "GR_WITHDRAWALS_LOCK"; // Address that will be used to burn guardian tokens address internal constant BURN_ACCOUNT = address(0x000000000000000000000000000000000000dEaD); // Maximum number of sortition iterations allowed per draft call uint256 internal constant MAX_DRAFT_ITERATIONS = 10; // "ERC20-lite" interface to provide help for tooling string public constant name = "Court Staked Aragon Network Token"; string public constant symbol = "sANT"; uint8 public constant decimals = 18; /** * @dev Guardians have three kind of balances, these are: * - active: tokens activated for the Court that can be locked in case the guardian is drafted * - locked: amount of active tokens that are locked for a draft * - available: tokens that are not activated for the Court and can be withdrawn by the guardian at any time * * Due to a gas optimization for drafting, the "active" tokens are stored in a `HexSumTree`, while the others * are stored in this contract as `lockedBalance` and `availableBalance` respectively. Given that the guardians' * active balances cannot be affected during the current Court term, if guardians want to deactivate some of * their active tokens, their balance will be updated for the following term, and they won't be allowed to * withdraw them until the current term has ended. * * Note that even though guardians balances are stored separately, all the balances are held by this contract. */ struct Guardian { uint256 id; // Key in the guardians tree used for drafting uint256 lockedBalance; // Maximum amount of tokens that can be slashed based on the guardian's drafts uint256 availableBalance; // Available tokens that can be withdrawn at any time uint64 withdrawalsLockTermId; // Term ID until which the guardian's withdrawals will be locked ActivationLocks activationLocks; // Guardian's activation locks DeactivationRequest deactivationRequest; // Guardian's pending deactivation request } /** * @dev Guardians can define lock managers to control their minimum active balance in the registry */ struct ActivationLocks { uint256 total; // Total amount of active balance locked mapping (address => uint256) lockedBy; // List of locked amounts indexed by lock manager } /** * @dev Given that the guardians balances cannot be affected during a Court term, if guardians want to deactivate some * of their tokens, the tree will always be updated for the following term, and they won't be able to * withdraw the requested amount until the current term has finished. Thus, we need to keep track the term * when a token deactivation was requested and its corresponding amount. */ struct DeactivationRequest { uint256 amount; // Amount requested for deactivation uint64 availableTermId; // Term ID when guardians can withdraw their requested deactivation tokens } /** * @dev Internal struct to wrap all the params required to perform guardians drafting */ struct DraftParams { bytes32 termRandomness; // Randomness seed to be used for the draft uint256 disputeId; // ID of the dispute being drafted uint64 termId; // Term ID of the dispute's draft term uint256 selectedGuardians; // Number of guardians already selected for the draft uint256 batchRequestedGuardians; // Number of guardians to be selected in the given batch of the draft uint256 roundRequestedGuardians; // Total number of guardians requested to be drafted uint256 draftLockAmount; // Amount of tokens to be locked to each drafted guardian uint256 iteration; // Sortition iteration number } // Maximum amount of total active balance that can be held in the registry uint256 public totalActiveBalanceLimit; // Guardian ERC20 token IERC20 public guardiansToken; // Mapping of guardian data indexed by address mapping (address => Guardian) internal guardiansByAddress; // Mapping of guardian addresses indexed by id mapping (uint256 => address) internal guardiansAddressById; // Tree to store guardians active balance by term for the drafting process HexSumTree.Tree internal tree; event Staked(address indexed guardian, uint256 amount, uint256 total); event Unstaked(address indexed guardian, uint256 amount, uint256 total); event GuardianActivated(address indexed guardian, uint64 fromTermId, uint256 amount); event GuardianDeactivationRequested(address indexed guardian, uint64 availableTermId, uint256 amount); event GuardianDeactivationProcessed(address indexed guardian, uint64 availableTermId, uint256 amount, uint64 processedTermId); event GuardianDeactivationUpdated(address indexed guardian, uint64 availableTermId, uint256 amount, uint64 updateTermId); event GuardianActivationLockChanged(address indexed guardian, address indexed lockManager, uint256 amount, uint256 total); event GuardianBalanceLocked(address indexed guardian, uint256 amount); event GuardianBalanceUnlocked(address indexed guardian, uint256 amount); event GuardianSlashed(address indexed guardian, uint256 amount, uint64 effectiveTermId); event GuardianTokensAssigned(address indexed guardian, uint256 amount); event GuardianTokensBurned(uint256 amount); event GuardianTokensCollected(address indexed guardian, uint256 amount, uint64 effectiveTermId); event TotalActiveBalanceLimitChanged(uint256 previousTotalActiveBalanceLimit, uint256 currentTotalActiveBalanceLimit); /** * @dev Constructor function * @param _controller Address of the controller * @param _guardiansToken Address of the ERC20 token to be used as guardian token for the registry * @param _totalActiveBalanceLimit Maximum amount of total active balance that can be held in the registry */ constructor(Controller _controller, IERC20 _guardiansToken, uint256 _totalActiveBalanceLimit) Controlled(_controller) public { require(isContract(address(_guardiansToken)), ERROR_NOT_CONTRACT); guardiansToken = _guardiansToken; _setTotalActiveBalanceLimit(_totalActiveBalanceLimit); tree.init(); // First tree item is an empty guardian assert(tree.insert(0, 0) == 0); } /** * @notice Stake `@tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian to stake tokens to * @param _amount Amount of tokens to be staked */ function stake(address _guardian, uint256 _amount) external { _stake(_guardian, _amount); } /** * @notice Unstake `@tokenAmount(self.token(), _amount)` from `_guardian` * @param _guardian Address of the guardian to unstake tokens from * @param _amount Amount of tokens to be unstaked */ function unstake(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _unstake(_guardian, _amount); } /** * @notice Activate `@tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian activating the tokens for * @param _amount Amount of guardian tokens to be activated for the next term */ function activate(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _activate(_guardian, _amount); } /** * @notice Deactivate `_amount == 0 ? 'all unlocked tokens' : @tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian deactivating the tokens for * @param _amount Amount of guardian tokens to be deactivated for the next term */ function deactivate(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _deactivate(_guardian, _amount); } /** * @notice Stake and activate `@tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian staking and activating tokens for * @param _amount Amount of tokens to be staked and activated */ function stakeAndActivate(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _stake(_guardian, _amount); _activate(_guardian, _amount); } /** * @notice Lock `@tokenAmount(self.token(), _amount)` of `_guardian`'s active balance * @param _guardian Address of the guardian locking the activation for * @param _lockManager Address of the lock manager that will control the lock * @param _amount Amount of active tokens to be locked */ function lockActivation(address _guardian, address _lockManager, uint256 _amount) external { // Make sure the sender is the guardian, someone allowed by the guardian, or the lock manager itself bool isLockManagerAllowed = msg.sender == _lockManager || _isSenderAllowed(_guardian); // Make sure that the given lock manager is allowed require(isLockManagerAllowed && _hasRole(_lockManager), ERROR_LOCK_MANAGER_NOT_ALLOWED); _lockActivation(_guardian, _lockManager, _amount); } /** * @notice Unlock `_amount == 0 ? 'all unlocked tokens' : @tokenAmount(self.token(), _amount)` of `_guardian`'s active balance * @param _guardian Address of the guardian unlocking the active balance of * @param _lockManager Address of the lock manager controlling the lock * @param _amount Amount of active tokens to be unlocked * @param _requestDeactivation Whether the unlocked amount must be requested for deactivation immediately */ function unlockActivation(address _guardian, address _lockManager, uint256 _amount, bool _requestDeactivation) external { ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks; uint256 lockedAmount = activationLocks.lockedBy[_lockManager]; require(lockedAmount > 0, ERROR_ZERO_LOCK_ACTIVATION); uint256 amountToUnlock = _amount == 0 ? lockedAmount : _amount; require(amountToUnlock <= lockedAmount, ERROR_INVALID_UNLOCK_ACTIVATION_AMOUNT); // Always allow the lock manager to unlock bool canUnlock = _lockManager == msg.sender || ILockManager(_lockManager).canUnlock(_guardian, amountToUnlock); require(canUnlock, ERROR_CANNOT_UNLOCK_ACTIVATION); uint256 newLockedAmount = lockedAmount.sub(amountToUnlock); uint256 newTotalLocked = activationLocks.total.sub(amountToUnlock); activationLocks.total = newTotalLocked; activationLocks.lockedBy[_lockManager] = newLockedAmount; emit GuardianActivationLockChanged(_guardian, _lockManager, newLockedAmount, newTotalLocked); // In order to request a deactivation, the request must have been originally authorized from the guardian or someone authorized to do it if (_requestDeactivation) { _authenticateSender(_guardian); _deactivate(_guardian, _amount); } } /** * @notice Process a token deactivation requested for `_guardian` if there is any * @param _guardian Address of the guardian to process the deactivation request of */ function processDeactivationRequest(address _guardian) external { uint64 termId = _ensureCurrentTerm(); _processDeactivationRequest(_guardian, termId); } /** * @notice Assign `@tokenAmount(self.token(), _amount)` to the available balance of `_guardian` * @param _guardian Guardian to add an amount of tokens to * @param _amount Amount of tokens to be added to the available balance of a guardian */ function assignTokens(address _guardian, uint256 _amount) external onlyActiveDisputeManager { if (_amount > 0) { _updateAvailableBalanceOf(_guardian, _amount, true); emit GuardianTokensAssigned(_guardian, _amount); } } /** * @notice Burn `@tokenAmount(self.token(), _amount)` * @param _amount Amount of tokens to be burned */ function burnTokens(uint256 _amount) external onlyActiveDisputeManager { if (_amount > 0) { _updateAvailableBalanceOf(BURN_ACCOUNT, _amount, true); emit GuardianTokensBurned(_amount); } } /** * @notice Draft a set of guardians based on given requirements for a term id * @param _params Array containing draft requirements: * 0. bytes32 Term randomness * 1. uint256 Dispute id * 2. uint64 Current term id * 3. uint256 Number of seats already filled * 4. uint256 Number of seats left to be filled * 5. uint64 Number of guardians required for the draft * 6. uint16 Permyriad of the minimum active balance to be locked for the draft * * @return guardians List of guardians selected for the draft * @return length Size of the list of the draft result */ function draft(uint256[7] calldata _params) external onlyActiveDisputeManager returns (address[] memory guardians, uint256 length) { DraftParams memory draftParams = _buildDraftParams(_params); guardians = new address[](draftParams.batchRequestedGuardians); // Guardians returned by the tree multi-sortition may not have enough unlocked active balance to be drafted. Thus, // we compute several sortitions until all the requested guardians are selected. To guarantee a different set of // guardians on each sortition, the iteration number will be part of the random seed to be used in the sortition. // Note that we are capping the number of iterations to avoid an OOG error, which means that this function could // return less guardians than the requested number. for (draftParams.iteration = 0; length < draftParams.batchRequestedGuardians && draftParams.iteration < MAX_DRAFT_ITERATIONS; draftParams.iteration++ ) { (uint256[] memory guardianIds, uint256[] memory activeBalances) = _treeSearch(draftParams); for (uint256 i = 0; i < guardianIds.length && length < draftParams.batchRequestedGuardians; i++) { // We assume the selected guardians are registered in the registry, we are not checking their addresses exist address guardianAddress = guardiansAddressById[guardianIds[i]]; Guardian storage guardian = guardiansByAddress[guardianAddress]; // Compute new locked balance for a guardian based on the penalty applied when being drafted uint256 newLockedBalance = guardian.lockedBalance.add(draftParams.draftLockAmount); // Check if there is any deactivation requests for the next term. Drafts are always computed for the current term // but we have to make sure we are locking an amount that will exist in the next term. uint256 nextTermDeactivationRequestAmount = _deactivationRequestedAmountForTerm(guardian, draftParams.termId + 1); // Check if guardian has enough active tokens to lock the requested amount for the draft, skip it otherwise. uint256 currentActiveBalance = activeBalances[i]; if (currentActiveBalance >= newLockedBalance) { // Check if the amount of active tokens for the next term is enough to lock the required amount for // the draft. Otherwise, reduce the requested deactivation amount of the next term. // Next term deactivation amount should always be less than current active balance, but we make sure using SafeMath uint256 nextTermActiveBalance = currentActiveBalance.sub(nextTermDeactivationRequestAmount); if (nextTermActiveBalance < newLockedBalance) { // No need for SafeMath: we already checked values above _reduceDeactivationRequest(guardianAddress, newLockedBalance - nextTermActiveBalance, draftParams.termId); } // Update the current active locked balance of the guardian guardian.lockedBalance = newLockedBalance; guardians[length++] = guardianAddress; emit GuardianBalanceLocked(guardianAddress, draftParams.draftLockAmount); } } } } /** * @notice Slash a set of guardians based on their votes compared to the winning ruling. This function will unlock the * corresponding locked balances of those guardians that are set to be slashed. * @param _termId Current term id * @param _guardians List of guardian addresses to be slashed * @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned * @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not * @return Total amount of slashed tokens */ function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians) external onlyActiveDisputeManager returns (uint256) { require(_guardians.length == _lockedAmounts.length, ERROR_INVALID_LOCKED_AMOUNTS_LENGTH); require(_guardians.length == _rewardedGuardians.length, ERROR_INVALID_REWARDED_GUARDIANS_LENGTH); uint64 nextTermId = _termId + 1; uint256 collectedTokens; for (uint256 i = 0; i < _guardians.length; i++) { uint256 lockedAmount = _lockedAmounts[i]; address guardianAddress = _guardians[i]; Guardian storage guardian = guardiansByAddress[guardianAddress]; guardian.lockedBalance = guardian.lockedBalance.sub(lockedAmount); // Slash guardian if requested. Note that there's no need to check if there was a deactivation // request since we're working with already locked balances. if (_rewardedGuardians[i]) { emit GuardianBalanceUnlocked(guardianAddress, lockedAmount); } else { collectedTokens = collectedTokens.add(lockedAmount); tree.update(guardian.id, nextTermId, lockedAmount, false); emit GuardianSlashed(guardianAddress, lockedAmount, nextTermId); } } return collectedTokens; } /** * @notice Try to collect `@tokenAmount(self.token(), _amount)` from `_guardian` for the term #`_termId + 1`. * @dev This function tries to decrease the active balance of a guardian for the next term based on the requested * amount. It can be seen as a way to early-slash a guardian's active balance. * @param _guardian Guardian to collect the tokens from * @param _amount Amount of tokens to be collected from the given guardian and for the requested term id * @param _termId Current term id * @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise */ function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external onlyActiveDisputeManager returns (bool) { if (_amount == 0) { return true; } uint64 nextTermId = _termId + 1; Guardian storage guardian = guardiansByAddress[_guardian]; uint256 unlockedActiveBalance = _lastUnlockedActiveBalanceOf(guardian); uint256 nextTermDeactivationRequestAmount = _deactivationRequestedAmountForTerm(guardian, nextTermId); // Check if the guardian has enough unlocked tokens to collect the requested amount // Note that we're also considering the deactivation request if there is any uint256 totalUnlockedActiveBalance = unlockedActiveBalance.add(nextTermDeactivationRequestAmount); if (_amount > totalUnlockedActiveBalance) { return false; } // Check if the amount of active tokens is enough to collect the requested amount, otherwise reduce the requested deactivation amount of // the next term. Note that this behaviour is different to the one when drafting guardians since this function is called as a side effect // of a guardian deliberately voting in a final round, while drafts occur randomly. if (_amount > unlockedActiveBalance) { // No need for SafeMath: amounts were already checked above uint256 amountToReduce = _amount - unlockedActiveBalance; _reduceDeactivationRequest(_guardian, amountToReduce, _termId); } tree.update(guardian.id, nextTermId, _amount, false); emit GuardianTokensCollected(_guardian, _amount, nextTermId); return true; } /** * @notice Lock `_guardian`'s withdrawals until term #`_termId` * @dev This is intended for guardians who voted in a final round and were coherent with the final ruling to prevent 51% attacks * @param _guardian Address of the guardian to be locked * @param _termId Term ID until which the guardian's withdrawals will be locked */ function lockWithdrawals(address _guardian, uint64 _termId) external onlyActiveDisputeManager { Guardian storage guardian = guardiansByAddress[_guardian]; guardian.withdrawalsLockTermId = _termId; } /** * @notice Set new limit of total active balance of guardian tokens * @param _totalActiveBalanceLimit New limit of total active balance of guardian tokens */ function setTotalActiveBalanceLimit(uint256 _totalActiveBalanceLimit) external onlyConfigGovernor { _setTotalActiveBalanceLimit(_totalActiveBalanceLimit); } /** * @dev Tell the total supply of guardian tokens staked * @return Supply of guardian tokens staked */ function totalSupply() external view returns (uint256) { return guardiansToken.balanceOf(address(this)); } /** * @dev Tell the total amount of active guardian tokens * @return Total amount of active guardian tokens */ function totalActiveBalance() external view returns (uint256) { return tree.getTotal(); } /** * @dev Tell the total amount of active guardian tokens for a given term id * @param _termId Term ID to query on * @return Total amount of active guardian tokens at the given term id */ function totalActiveBalanceAt(uint64 _termId) external view returns (uint256) { return _totalActiveBalanceAt(_termId); } /** * @dev Tell the total balance of tokens held by a guardian * This includes the active balance, the available balances, and the pending balance for deactivation. * Note that we don't have to include the locked balances since these represent the amount of active tokens * that are locked for drafts, i.e. these are already included in the active balance of the guardian. * @param _guardian Address of the guardian querying the balance of * @return Total amount of tokens of a guardian */ function balanceOf(address _guardian) external view returns (uint256) { return _balanceOf(_guardian); } /** * @dev Tell the detailed balance information of a guardian * @param _guardian Address of the guardian querying the detailed balance information of * @return active Amount of active tokens of a guardian * @return available Amount of available tokens of a guardian * @return locked Amount of active tokens that are locked due to ongoing disputes * @return pendingDeactivation Amount of active tokens that were requested for deactivation */ function detailedBalanceOf(address _guardian) external view returns (uint256 active, uint256 available, uint256 locked, uint256 pendingDeactivation) { return _detailedBalanceOf(_guardian); } /** * @dev Tell the active balance of a guardian for a given term id * @param _guardian Address of the guardian querying the active balance of * @param _termId Term ID to query on * @return Amount of active tokens for guardian in the requested past term id */ function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256) { return _activeBalanceOfAt(_guardian, _termId); } /** * @dev Tell the amount of active tokens of a guardian at the last ensured term that are not locked due to ongoing disputes * @param _guardian Address of the guardian querying the unlocked balance of * @return Amount of active tokens of a guardian that are not locked due to ongoing disputes */ function unlockedActiveBalanceOf(address _guardian) external view returns (uint256) { Guardian storage guardian = guardiansByAddress[_guardian]; return _currentUnlockedActiveBalanceOf(guardian); } /** * @dev Tell the pending deactivation details for a guardian * @param _guardian Address of the guardian whose info is requested * @return amount Amount to be deactivated * @return availableTermId Term in which the deactivated amount will be available */ function getDeactivationRequest(address _guardian) external view returns (uint256 amount, uint64 availableTermId) { DeactivationRequest storage request = guardiansByAddress[_guardian].deactivationRequest; return (request.amount, request.availableTermId); } /** * @dev Tell the activation amount locked for a guardian by a lock manager * @param _guardian Address of the guardian whose info is requested * @param _lockManager Address of the lock manager querying the lock of * @return amount Activation amount locked by the lock manager * @return total Total activation amount locked for the guardian */ function getActivationLock(address _guardian, address _lockManager) external view returns (uint256 amount, uint256 total) { ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks; total = activationLocks.total; amount = activationLocks.lockedBy[_lockManager]; } /** * @dev Tell the withdrawals lock term ID for a guardian * @param _guardian Address of the guardian whose info is requested * @return Term ID until which the guardian's withdrawals will be locked */ function getWithdrawalsLockTermId(address _guardian) external view returns (uint64) { return guardiansByAddress[_guardian].withdrawalsLockTermId; } /** * @dev Tell the identification number associated to a guardian address * @param _guardian Address of the guardian querying the identification number of * @return Identification number associated to a guardian address, zero in case it wasn't registered yet */ function getGuardianId(address _guardian) external view returns (uint256) { return guardiansByAddress[_guardian].id; } /** * @dev Internal function to activate a given amount of tokens for a guardian. * This function assumes that the given term is the current term and has already been ensured. * @param _guardian Address of the guardian to activate tokens * @param _amount Amount of guardian tokens to be activated */ function _activate(address _guardian, uint256 _amount) internal { uint64 termId = _ensureCurrentTerm(); // Try to clean a previous deactivation request if any _processDeactivationRequest(_guardian, termId); uint256 availableBalance = guardiansByAddress[_guardian].availableBalance; uint256 amountToActivate = _amount == 0 ? availableBalance : _amount; require(amountToActivate > 0, ERROR_INVALID_ZERO_AMOUNT); require(amountToActivate <= availableBalance, ERROR_INVALID_ACTIVATION_AMOUNT); uint64 nextTermId = termId + 1; _checkTotalActiveBalance(nextTermId, amountToActivate); Guardian storage guardian = guardiansByAddress[_guardian]; uint256 minActiveBalance = _getMinActiveBalance(nextTermId); if (_existsGuardian(guardian)) { // Even though we are adding amounts, let's check the new active balance is greater than or equal to the // minimum active amount. Note that the guardian might have been slashed. uint256 activeBalance = tree.getItem(guardian.id); require(activeBalance.add(amountToActivate) >= minActiveBalance, ERROR_ACTIVE_BALANCE_BELOW_MIN); tree.update(guardian.id, nextTermId, amountToActivate, true); } else { require(amountToActivate >= minActiveBalance, ERROR_ACTIVE_BALANCE_BELOW_MIN); guardian.id = tree.insert(nextTermId, amountToActivate); guardiansAddressById[guardian.id] = _guardian; } _updateAvailableBalanceOf(_guardian, amountToActivate, false); emit GuardianActivated(_guardian, nextTermId, amountToActivate); } /** * @dev Internal function to deactivate a given amount of tokens for a guardian. * @param _guardian Address of the guardian to deactivate tokens * @param _amount Amount of guardian tokens to be deactivated for the next term */ function _deactivate(address _guardian, uint256 _amount) internal { uint64 termId = _ensureCurrentTerm(); Guardian storage guardian = guardiansByAddress[_guardian]; uint256 unlockedActiveBalance = _lastUnlockedActiveBalanceOf(guardian); uint256 amountToDeactivate = _amount == 0 ? unlockedActiveBalance : _amount; require(amountToDeactivate > 0, ERROR_INVALID_ZERO_AMOUNT); require(amountToDeactivate <= unlockedActiveBalance, ERROR_INVALID_DEACTIVATION_AMOUNT); // Check future balance is not below the total activation lock of the guardian // No need for SafeMath: we already checked values above uint256 futureActiveBalance = unlockedActiveBalance - amountToDeactivate; uint256 totalActivationLock = guardian.activationLocks.total; require(futureActiveBalance >= totalActivationLock, ERROR_DEACTIVATION_AMOUNT_EXCEEDS_LOCK); // Check that the guardian is leaving or that the minimum active balance is met uint256 minActiveBalance = _getMinActiveBalance(termId); require(futureActiveBalance == 0 || futureActiveBalance >= minActiveBalance, ERROR_INVALID_DEACTIVATION_AMOUNT); _createDeactivationRequest(_guardian, amountToDeactivate); } /** * @dev Internal function to create a token deactivation request for a guardian. Guardians will be allowed * to process a deactivation request from the next term. * @param _guardian Address of the guardian to create a token deactivation request for * @param _amount Amount of guardian tokens requested for deactivation */ function _createDeactivationRequest(address _guardian, uint256 _amount) internal { uint64 termId = _ensureCurrentTerm(); // Try to clean a previous deactivation request if possible _processDeactivationRequest(_guardian, termId); uint64 nextTermId = termId + 1; Guardian storage guardian = guardiansByAddress[_guardian]; DeactivationRequest storage request = guardian.deactivationRequest; request.amount = request.amount.add(_amount); request.availableTermId = nextTermId; tree.update(guardian.id, nextTermId, _amount, false); emit GuardianDeactivationRequested(_guardian, nextTermId, _amount); } /** * @dev Internal function to process a token deactivation requested by a guardian. It will move the requested amount * to the available balance of the guardian if the term when the deactivation was requested has already finished. * @param _guardian Address of the guardian to process the deactivation request of * @param _termId Current term id */ function _processDeactivationRequest(address _guardian, uint64 _termId) internal { Guardian storage guardian = guardiansByAddress[_guardian]; DeactivationRequest storage request = guardian.deactivationRequest; uint64 deactivationAvailableTermId = request.availableTermId; // If there is a deactivation request, ensure that the deactivation term has been reached if (deactivationAvailableTermId == uint64(0) || _termId < deactivationAvailableTermId) { return; } uint256 deactivationAmount = request.amount; // Note that we can use a zeroed term ID to denote void here since we are storing // the minimum allowed term to deactivate tokens which will always be at least 1. request.availableTermId = uint64(0); request.amount = 0; _updateAvailableBalanceOf(_guardian, deactivationAmount, true); emit GuardianDeactivationProcessed(_guardian, deactivationAvailableTermId, deactivationAmount, _termId); } /** * @dev Internal function to reduce a token deactivation requested by a guardian. It assumes the deactivation request * cannot be processed for the given term yet. * @param _guardian Address of the guardian to reduce the deactivation request of * @param _amount Amount to be reduced from the current deactivation request * @param _termId Term ID in which the deactivation request is being reduced */ function _reduceDeactivationRequest(address _guardian, uint256 _amount, uint64 _termId) internal { Guardian storage guardian = guardiansByAddress[_guardian]; DeactivationRequest storage request = guardian.deactivationRequest; uint256 currentRequestAmount = request.amount; require(currentRequestAmount >= _amount, ERROR_CANNOT_REDUCE_DEACTIVATION_REQUEST); // No need for SafeMath: we already checked values above uint256 newRequestAmount = currentRequestAmount - _amount; request.amount = newRequestAmount; // Move amount back to the tree tree.update(guardian.id, _termId + 1, _amount, true); emit GuardianDeactivationUpdated(_guardian, request.availableTermId, newRequestAmount, _termId); } /** * @dev Internal function to update the activation locked amount of a guardian * @param _guardian Guardian to update the activation locked amount of * @param _lockManager Address of the lock manager controlling the lock * @param _amount Amount of tokens to be added to the activation locked amount of the guardian */ function _lockActivation(address _guardian, address _lockManager, uint256 _amount) internal { ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks; uint256 newTotalLocked = activationLocks.total.add(_amount); uint256 newLockedAmount = activationLocks.lockedBy[_lockManager].add(_amount); activationLocks.total = newTotalLocked; activationLocks.lockedBy[_lockManager] = newLockedAmount; emit GuardianActivationLockChanged(_guardian, _lockManager, newLockedAmount, newTotalLocked); } /** * @dev Internal function to stake an amount of tokens for a guardian * @param _guardian Address of the guardian to deposit the tokens to * @param _amount Amount of tokens to be deposited */ function _stake(address _guardian, uint256 _amount) internal { require(_amount > 0, ERROR_INVALID_ZERO_AMOUNT); _updateAvailableBalanceOf(_guardian, _amount, true); emit Staked(_guardian, _amount, _balanceOf(_guardian)); require(guardiansToken.safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FAILED); } /** * @dev Internal function to unstake an amount of tokens of a guardian * @param _guardian Address of the guardian to to unstake the tokens of * @param _amount Amount of tokens to be unstaked */ function _unstake(address _guardian, uint256 _amount) internal { require(_amount > 0, ERROR_INVALID_ZERO_AMOUNT); // Try to process a deactivation request for the current term if there is one. Note that we don't need to ensure // the current term this time since deactivation requests always work with future terms, which means that if // the current term is outdated, it will never match the deactivation term id. We avoid ensuring the term here // to avoid forcing guardians to do that in order to withdraw their available balance. Same applies to final round locks. uint64 lastEnsuredTermId = _getLastEnsuredTermId(); // Check that guardian's withdrawals are not locked uint64 withdrawalsLockTermId = guardiansByAddress[_guardian].withdrawalsLockTermId; require(withdrawalsLockTermId == 0 || withdrawalsLockTermId < lastEnsuredTermId, ERROR_WITHDRAWALS_LOCK); _processDeactivationRequest(_guardian, lastEnsuredTermId); _updateAvailableBalanceOf(_guardian, _amount, false); emit Unstaked(_guardian, _amount, _balanceOf(_guardian)); require(guardiansToken.safeTransfer(_guardian, _amount), ERROR_TOKEN_TRANSFER_FAILED); } /** * @dev Internal function to update the available balance of a guardian * @param _guardian Guardian to update the available balance of * @param _amount Amount of tokens to be added to or removed from the available balance of a guardian * @param _positive True if the given amount should be added, or false to remove it from the available balance */ function _updateAvailableBalanceOf(address _guardian, uint256 _amount, bool _positive) internal { // We are not using a require here to avoid reverting in case any of the treasury maths reaches this point // with a zeroed amount value. Instead, we are doing this validation in the external entry points such as // stake, unstake, activate, deactivate, among others. if (_amount == 0) { return; } Guardian storage guardian = guardiansByAddress[_guardian]; if (_positive) { guardian.availableBalance = guardian.availableBalance.add(_amount); } else { require(_amount <= guardian.availableBalance, ERROR_NOT_ENOUGH_AVAILABLE_BALANCE); // No need for SafeMath: we already checked values right above guardian.availableBalance -= _amount; } } /** * @dev Internal function to set new limit of total active balance of guardian tokens * @param _totalActiveBalanceLimit New limit of total active balance of guardian tokens */ function _setTotalActiveBalanceLimit(uint256 _totalActiveBalanceLimit) internal { require(_totalActiveBalanceLimit > 0, ERROR_BAD_TOTAL_ACTIVE_BALANCE_LIMIT); emit TotalActiveBalanceLimitChanged(totalActiveBalanceLimit, _totalActiveBalanceLimit); totalActiveBalanceLimit = _totalActiveBalanceLimit; } /** * @dev Internal function to tell the total balance of tokens held by a guardian * @param _guardian Address of the guardian querying the total balance of * @return Total amount of tokens of a guardian */ function _balanceOf(address _guardian) internal view returns (uint256) { (uint256 active, uint256 available, , uint256 pendingDeactivation) = _detailedBalanceOf(_guardian); return available.add(active).add(pendingDeactivation); } /** * @dev Internal function to tell the detailed balance information of a guardian * @param _guardian Address of the guardian querying the balance information of * @return active Amount of active tokens of a guardian * @return available Amount of available tokens of a guardian * @return locked Amount of active tokens that are locked due to ongoing disputes * @return pendingDeactivation Amount of active tokens that were requested for deactivation */ function _detailedBalanceOf(address _guardian) internal view returns (uint256 active, uint256 available, uint256 locked, uint256 pendingDeactivation) { Guardian storage guardian = guardiansByAddress[_guardian]; active = _existsGuardian(guardian) ? tree.getItem(guardian.id) : 0; (available, locked, pendingDeactivation) = _getBalances(guardian); } /** * @dev Tell the active balance of a guardian for a given term id * @param _guardian Address of the guardian querying the active balance of * @param _termId Term ID querying the active balance for * @return Amount of active tokens for guardian in the requested past term id */ function _activeBalanceOfAt(address _guardian, uint64 _termId) internal view returns (uint256) { Guardian storage guardian = guardiansByAddress[_guardian]; return _existsGuardian(guardian) ? tree.getItemAt(guardian.id, _termId) : 0; } /** * @dev Internal function to get the amount of active tokens of a guardian that are not locked due to ongoing disputes * It will use the last value, that might be in a future term * @param _guardian Guardian querying the unlocked active balance of * @return Amount of active tokens of a guardian that are not locked due to ongoing disputes */ function _lastUnlockedActiveBalanceOf(Guardian storage _guardian) internal view returns (uint256) { return _existsGuardian(_guardian) ? tree.getItem(_guardian.id).sub(_guardian.lockedBalance) : 0; } /** * @dev Internal function to get the amount of active tokens at the last ensured term of a guardian that are not locked due to ongoing disputes * @param _guardian Guardian querying the unlocked active balance of * @return Amount of active tokens of a guardian that are not locked due to ongoing disputes */ function _currentUnlockedActiveBalanceOf(Guardian storage _guardian) internal view returns (uint256) { uint64 lastEnsuredTermId = _getLastEnsuredTermId(); return _existsGuardian(_guardian) ? tree.getItemAt(_guardian.id, lastEnsuredTermId).sub(_guardian.lockedBalance) : 0; } /** * @dev Internal function to check if a guardian was already registered * @param _guardian Guardian to be checked * @return True if the given guardian was already registered, false otherwise */ function _existsGuardian(Guardian storage _guardian) internal view returns (bool) { return _guardian.id != 0; } /** * @dev Internal function to get the amount of a deactivation request for a given term id * @param _guardian Guardian to query the deactivation request amount of * @param _termId Term ID of the deactivation request to be queried * @return Amount of the deactivation request for the given term, 0 otherwise */ function _deactivationRequestedAmountForTerm(Guardian storage _guardian, uint64 _termId) internal view returns (uint256) { DeactivationRequest storage request = _guardian.deactivationRequest; return request.availableTermId == _termId ? request.amount : 0; } /** * @dev Internal function to tell the total amount of active guardian tokens at the given term id * @param _termId Term ID querying the total active balance for * @return Total amount of active guardian tokens at the given term id */ function _totalActiveBalanceAt(uint64 _termId) internal view returns (uint256) { // This function will return always the same values, the only difference remains on gas costs. In case we look for a // recent term, in this case current or future ones, we perform a backwards linear search from the last checkpoint. // Otherwise, a binary search is computed. bool recent = _termId >= _getLastEnsuredTermId(); return recent ? tree.getRecentTotalAt(_termId) : tree.getTotalAt(_termId); } /** * @dev Internal function to check if its possible to add a given new amount to the registry or not * @param _termId Term ID when the new amount will be added * @param _amount Amount of tokens willing to be added to the registry */ function _checkTotalActiveBalance(uint64 _termId, uint256 _amount) internal view { uint256 currentTotalActiveBalance = _totalActiveBalanceAt(_termId); uint256 newTotalActiveBalance = currentTotalActiveBalance.add(_amount); require(newTotalActiveBalance <= totalActiveBalanceLimit, ERROR_TOTAL_ACTIVE_BALANCE_EXCEEDED); } /** * @dev Tell the local balance information of a guardian (that is not on the tree) * @param _guardian Address of the guardian querying the balance information of * @return available Amount of available tokens of a guardian * @return locked Amount of active tokens that are locked due to ongoing disputes * @return pendingDeactivation Amount of active tokens that were requested for deactivation */ function _getBalances(Guardian storage _guardian) internal view returns (uint256 available, uint256 locked, uint256 pendingDeactivation) { available = _guardian.availableBalance; locked = _guardian.lockedBalance; pendingDeactivation = _guardian.deactivationRequest.amount; } /** * @dev Internal function to search guardians in the tree based on certain search restrictions * @param _params Draft params to be used for the guardians search * @return ids List of guardian ids obtained based on the requested search * @return activeBalances List of active balances for each guardian obtained based on the requested search */ function _treeSearch(DraftParams memory _params) internal view returns (uint256[] memory ids, uint256[] memory activeBalances) { (ids, activeBalances) = tree.batchedRandomSearch( _params.termRandomness, _params.disputeId, _params.termId, _params.selectedGuardians, _params.batchRequestedGuardians, _params.roundRequestedGuardians, _params.iteration ); } /** * @dev Private function to parse a certain set given of draft params * @param _params Array containing draft requirements: * 0. bytes32 Term randomness * 1. uint256 Dispute id * 2. uint64 Current term id * 3. uint256 Number of seats already filled * 4. uint256 Number of seats left to be filled * 5. uint64 Number of guardians required for the draft * 6. uint16 Permyriad of the minimum active balance to be locked for the draft * * @return Draft params object parsed */ function _buildDraftParams(uint256[7] memory _params) private view returns (DraftParams memory) { uint64 termId = uint64(_params[2]); uint256 minActiveBalance = _getMinActiveBalance(termId); return DraftParams({ termRandomness: bytes32(_params[0]), disputeId: _params[1], termId: termId, selectedGuardians: _params[3], batchRequestedGuardians: _params[4], roundRequestedGuardians: _params[5], draftLockAmount: minActiveBalance.pct(uint16(_params[6])), iteration: 0 }); } }
Governor addresses of the system
Governor private governor;
91,706
[ 1, 43, 1643, 29561, 6138, 434, 326, 2619, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 611, 1643, 29561, 3238, 314, 1643, 29561, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "../interfaces/IPMETokenRolesStorage.sol"; import "../interfaces/IPMRolesManagerStorage.sol"; import "../../../common/libraries/SafeMath8.sol"; import "../../../registry-layer/components-registry/getters/PermissionModuleAddress.sol"; /** * @title Permission module extended token roles storage */ contract PMETokenRolesStorage is IPMETokenRolesStorage, PermissionModuleAddress { // define libraries using SafeMath8 for uint8; // Permission module extended token roles storage IPMRolesManagerStorage rms; // extended token dependet roles // Declare storage for the token dependent roles mapping(address => mapping(address => mapping(bytes32 => mapping(bytes32 => bool)))) internal tokenDependentRoles; // Declare storage for the token dependent roles indexes mapping(address => mapping(address => mapping(bytes32 => mapping(bytes32 => uint8)))) internal indexesOfTheTokenDependentRoles; // Declare storage for the token dependent roles mapping(address => mapping(address => mapping(bytes32 => bytes32[20]))) internal listOfTheTokenDependentRoles; // Declare storage for the last index of the token dependent roles mapping(address => mapping(address => mapping(bytes32 => uint8))) internal tokenDependentRolesIndex; /** * @notice Verify sender address */ modifier onlyPermissionModule(address sender) { address permissionModule = getPermissionModuleAddress(); require(sender == permissionModule, "Allowed only for the permission module."); _; } // Set components registry address constructor(address componentsRegistry, address mainStorage) public WithComponentsRegistry(componentsRegistry) { rms = IPMRolesManagerStorage(mainStorage); } /** * @notice Write info to the log when the new role was added to the wallet */ event TokenDependentRoleAdded( address indexed wallet, address indexed token, bytes32 role, bytes32 subId ); /** * @notice Write info to the log when the role was deleted */ event TokenDependentRoleDeleted( address indexed wallet, address indexed token, bytes32 role, bytes32 subId ); /// Events emitters. Write info about any state changes to the log. /// Allowed only for the Permission Module. /** * @notice Write info to the log when the new role was added to the wallet */ function emitTokenDependentRoleAddedWithSubId( address wallet, address token, bytes32 role, bytes32 subId ) public onlyPermissionModule(msg.sender) { emit TokenDependentRoleAdded( wallet, token, role, subId ); } /** * @notice Write info to the log when the role was deleted */ function emitTokenDependentRoleDeletedWithSubId( address wallet, address token, bytes32 role, bytes32 subId ) public onlyPermissionModule(msg.sender) { emit TokenDependentRoleDeleted( wallet, token, role, subId ); } /// Methods which updates the storage. Allowed only for the Permission Module. /** * @notice Update token dependent role status * @param wallet Wallet address * @param token Address of the token * @param role Role name * @param status Status * @param subId Additional role identifier */ function setTokenDependentRoleStatusWithSubId( address wallet, address token, bytes32 role, bool status, bytes32 subId ) public onlyPermissionModule(msg.sender) { tokenDependentRoles[wallet][token][subId][role] = status; } /** * @notice Add a token dependent role to the list * @param wallet Wallet address * @param token Address of the token * @param role Role name * @param index Index * @param subId Additional role identifier */ function setToTheTokenDependentListWithSubId( address wallet, address token, bytes32 role, uint index, bytes32 subId ) public onlyPermissionModule(msg.sender) { listOfTheTokenDependentRoles[wallet][token][subId][index] = role; } /** * @notice Set index of the token dependent role * @param wallet Wallet address * @param token Address of the token * @param role Role name * @param index Index * @param subId Additional role identifier */ function setTokenDependentRoleIndexWithSubId( address wallet, address token, bytes32 role, uint8 index, bytes32 subId ) public onlyPermissionModule(msg.sender) { indexesOfTheTokenDependentRoles[wallet][token][subId][role] = index; } /** * @notice Set token dependent roles index * @param wallet Wallet address * @param token Address of the token * @param index Index * @param subId Additional role identifier */ function setTokenDependentRolesIndexWithSubId( address wallet, address token, uint8 index, bytes32 subId ) public onlyPermissionModule(msg.sender) { tokenDependentRolesIndex[wallet][token][subId] = index; } /** * @notice Delete index of the token dependent role * @param wallet Wallet address * @param token Address of the token * @param role Role name * @param subId Additional role identifier */ function delTokenDependentRoleIndexWithSubId( address wallet, address token, bytes32 role, bytes32 subId ) public onlyPermissionModule(msg.sender) { delete indexesOfTheTokenDependentRoles[wallet][token][subId][role]; } /** * @notice Delete token dependent role from the list of the roles * @param wallet Wallet address * @param token Address of the token * @param index Index * @param subId Additional role identifier */ function delTokenDependentRoleWithSubId( address wallet, address token, uint8 index, bytes32 subId ) public onlyPermissionModule(msg.sender) { delete listOfTheTokenDependentRoles[wallet][token][subId][index]; } /** * @notice Remove a role from a specific token * @param wallet Wallet address * @param token Token address * @param roleName Name of the role which will be removed from the wallet * @param subId Additional role identifier */ function removeRoleFromSpecificTokenWithSubId( address wallet, address token, bytes32 roleName, bytes32 subId ) public onlyPermissionModule(msg.sender) { setTokenDependentRoleStatusWithSubId( wallet, token, roleName, false, subId ); uint8 index = getIndexOfTheTokeDependentRoleWithSubId( wallet, token, roleName, subId ); uint8 last = getTokenDependentRolesIndexWithSubId(wallet,token,subId).sub(1); if (last > 0) { bytes32 roleToUpdate = getTokenDependentRoleByIndexWithSubId(wallet, token, last, subId); setTokenDependentRoleIndexWithSubId(wallet,token,roleToUpdate,index,subId); setToTheTokenDependentListWithSubId(wallet,token,roleToUpdate,index,subId); } delTokenDependentRoleIndexWithSubId(wallet,token,roleName,subId); delTokenDependentRoleWithSubId(wallet,token,last,subId); setTokenDependentRolesIndexWithSubId(wallet,token,last,subId); emitTokenDependentRoleDeletedWithSubId(wallet, token, roleName, subId); } /// Getters. Public methods which are allowed for anyone. /** * @notice Returns token dependent roles index * @param wallet Wallet address * @param token Address of the token * @param subId Additional role identifier */ function getTokenDependentRolesIndexWithSubId( address wallet, address token, bytes32 subId ) public view returns (uint8) { return tokenDependentRolesIndex[wallet][token][subId]; } /** * @notice Returns the index of the token dependent role * @param wallet Wallet address * @param token Address of the token * @param role Role name * @param subId Additional role identifier */ function getIndexOfTheTokeDependentRoleWithSubId( address wallet, address token, bytes32 role, bytes32 subId ) public view returns (uint8) { return indexesOfTheTokenDependentRoles[wallet][token][subId][role]; } /** * @notice Get token dependent role by index * @param wallet Wallet address * @param token Address of the token * @param index Index * @param subId Additional role identifier */ function getTokenDependentRoleByIndexWithSubId( address wallet, address token, uint8 index, bytes32 subId ) public view returns (bytes32) { return listOfTheTokenDependentRoles[wallet][token][subId][index]; } /** * @notice Returns token dependent role status * @param wallet Wallet address * @param token Address of the token * @param role Role name * @param subId Additional role identifier */ function getTokenDependentRoleStatusWithSubId( address wallet, address token, bytes32 role, bytes32 subId ) public view returns (bool) { return tokenDependentRoles[wallet][token][subId][role]; } /** * @notice Verification of the permissions * @param methodId Requested method * @param sender An address which will be verified * @param token Token address * @param subId Additional role identifier */ function checkTokenPermissionWithSubId( bytes4 methodId, address sender, address token, bytes32 subId ) public view returns (bool) { uint8 index = tokenDependentRolesIndex[sender][token][subId]; bytes32 role; for (uint8 i = 0; i < index; i++) { role = listOfTheTokenDependentRoles[sender][token][subId][i]; if (rms.getMethodStatus(role, methodId) && rms.getRoleStatus(role)) { return true; } } return false; } /** * @notice Returns list of all roles of the wallet */ function getWalletRolesForTokenWithSubId( address wallet, address token, bytes32 subId ) public view returns (bytes32[20] memory) { return listOfTheTokenDependentRoles[wallet][token][subId]; } }
* @notice Delete index of the token dependent role @param wallet Wallet address @param token Address of the token @param role Role name @param subId Additional role identifier/
function delTokenDependentRoleIndexWithSubId( address wallet, address token, bytes32 role, bytes32 subId ) public onlyPermissionModule(msg.sender) { delete indexesOfTheTokenDependentRoles[wallet][token][subId][role]; }
12,669,926
[ 1, 2613, 770, 434, 326, 1147, 10460, 2478, 225, 9230, 20126, 1758, 225, 1147, 5267, 434, 326, 1147, 225, 2478, 6204, 508, 225, 720, 548, 15119, 2478, 2756, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1464, 1345, 18571, 2996, 1016, 1190, 1676, 548, 12, 203, 3639, 1758, 9230, 16, 203, 3639, 1758, 1147, 16, 203, 3639, 1731, 1578, 2478, 16, 203, 3639, 1731, 1578, 720, 548, 203, 565, 262, 203, 3639, 1071, 203, 3639, 1338, 5041, 3120, 12, 3576, 18, 15330, 13, 203, 565, 288, 203, 3639, 1430, 5596, 951, 1986, 1345, 18571, 6898, 63, 19177, 6362, 2316, 6362, 1717, 548, 6362, 4615, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.14; /** * @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 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) { uint256 c = a + b; assert(c >= a); return c; } } library Datasets { // 游戏状态 enum GameState { GAME_ING //进行中 , GAME_CLEAR //暂停下注 } // 龙虎标识 enum BetTypeEnum { NONE , DRAGON //龙 , TIGER //虎 , DRAW //和 } // coin 操作类型 enum CoinOpTypeEnum { NONE , PAY //1充值 , WITHDRAW //2提现 , BET //3下注 , INVITE_AWARD //4邀请奖励 , WIN_AWARD //5赢得下注的奖励 , LUCKY_AWARD //6幸运奖 } struct Round { uint256 start; // 开始时间 uint256 cut; // 截止时间 uint256 end; // 结束时间 bool ended; // 是否已结束 uint256 amount; // 总份数 uint256 coin; // 总coin BetTypeEnum result; // 结果 uint32 betCount; // 下注人次 } // 玩家 struct Player { address addr; // 玩家地址 uint256 coin; // 玩家剩余coin uint256 parent1; // 1代 uint256 parent2; // 2代 uint256 parent3; // 3代 } // 投注人 struct Beter { uint256 betId; // 押注人 bool beted; // 如果为真表示已经投注过 BetTypeEnum betType; // 押大押小 1 dragon 2tiger uint256 amount; // 份数 uint256 value; // 押多少 } //coin明细 struct CoinDetail { uint256 roundId; // 发生的回合 uint256 value; // 发生的金额 bool isGet; // 是否是获得 CoinOpTypeEnum opType; // 操作类型 uint256 time; // 发生时间 uint256 block; // 区块高度 } } contract GameLogic { using SafeMath for *; address private owner; // 货币比例 uint256 constant private EXCHANGE = 1; // 一轮中能下注的时间 uint256 private ROUND_BET_SECONDS = 480 seconds; // 一轮时间 uint256 private ROUND_MAX_SECONDS = 600 seconds; // 返奖率 uint256 private RETURN_AWARD_RATE = 9000; //0.9 // 幸运奖抽成比例 uint256 private LUCKY_AWARD_RATE = 400; //0.04 // 每次派发幸运奖的比例 uint256 private LUCKY_AWARD_SEND_RATE = 5000; //0.5 // 提现费 uint256 private WITH_DROW_RATE = 100; // 0.01 // 邀请分成费 uint256 private INVITE_RATE = 10; // 0.001 // RATE_BASE uint256 constant private RATE_BASE = 10000; //RATE/RATE_BASE // 每份押注的额度 uint256 constant private VALUE_PER_MOUNT = 1000000000000000; uint32 private ROUND_BET_MAX_COUNT = 300; uint256 constant private UID_START = 1000; // 期数 uint256 public roundId = 0; // 当前游戏状态 Datasets.GameState public state; // 当前是否激活 bool public activated = false; // 幸运奖 uint256 public luckyPool = 0; //**************** // 玩家数据 //**************** uint256 private userSize = UID_START; // 平台用户数 mapping(uint256 => Datasets.Player) public mapIdxPlayer; // (pId => data) player data mapping(address => uint256) public mapAddrxId; // (addr => pId) returns player id by address mapping(uint256 => Datasets.Round) public mapRound; // rid-> roundData mapping(uint256 => mapping(uint8 => Datasets.Beter[])) public mapBetter; // rid -> betType -> Beter[index] 保存每一期的投注 mapping(uint256 => mapping(uint8 => uint256)) public mapBetterSizes; // rid -> betType -> size; //**************** // 权限方法 //**************** modifier onlyState(Datasets.GameState curState) { require(state == curState); _; } modifier onlyActivated() { require(activated == true, "it's not ready yet"); _; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } //**************** // 构造方法 //**************** constructor() public { owner = msg.sender; } // fallback函数 function() onlyHuman public payable { uint256 value = msg.value; require(value > 0 && msg.sender != 0x0, "value not valid yet"); uint256 pId = mapAddrxId[msg.sender]; if (pId == 0) pId = addPlayer(msg.sender, value); else { addCoin(pId, value, Datasets.CoinOpTypeEnum.PAY); Datasets.Player storage player = mapIdxPlayer[pId]; // 1代分成 if(player.parent1 > 0) { uint256 divide1 = value.mul(INVITE_RATE).div(RATE_BASE); addCoin(player.parent1, divide1, Datasets.CoinOpTypeEnum.INVITE_AWARD); } // 3代分成 if (player.parent3 > 0) { uint256 divide2 = value.mul(INVITE_RATE).div(RATE_BASE); addCoin(player.parent3, divide2, Datasets.CoinOpTypeEnum.INVITE_AWARD); } } } //**************** // 私有方法 //**************** // 新用户 function addPlayer(address addr, uint256 initValue) private returns (uint256) { Datasets.Player memory newPlayer; uint256 coin = exchangeCoin(initValue); newPlayer.addr = addr; newPlayer.coin = coin; //保存新用户 userSize++; mapAddrxId[addr] = userSize; mapIdxPlayer[userSize] = newPlayer; addCoinDetail(userSize, coin, true, Datasets.CoinOpTypeEnum.PAY); return userSize; } // 减少coin function subCoin(uint256 pId, uint256 value, Datasets.CoinOpTypeEnum opType) private { require(pId > 0 && value > 0); Datasets.Player storage player = mapIdxPlayer[pId]; require(player.coin >= value, "your money is not enough"); player.coin = player.coin.sub(value); //记日志 addCoinDetail(pId, value, false, opType); } // 兑换coin function exchangeCoin(uint256 value) pure private returns (uint256){ return value.mul(EXCHANGE); } // 增加coin function addCoin(uint256 pId, uint256 value, Datasets.CoinOpTypeEnum opType) private { require(pId != 0 && value > 0); mapIdxPlayer[pId].coin += value; //记日志 addCoinDetail(pId, value, true, opType); } function checkLucky(address addr, uint256 second, uint256 last) public pure returns (bool) { uint256 last2 = (uint256(addr) * 2 ** 252) / (2 ** 252); uint256 second2 = (uint256(addr) * 2 ** 248) / (2 ** 252); if(second == second2 && last2 == last) return true; else return false; } //计算该轮次结果 function calcResult(uint256 dragonSize, uint256 tigerSize, uint256 seed) onlyOwner private view returns (uint, uint) { uint randomDragon = uint(keccak256(abi.encodePacked(now, block.number, dragonSize, seed))) % 16; uint randomTiger = uint(keccak256(abi.encodePacked(now, block.number, tigerSize, seed.mul(2)))) % 16; return (randomDragon, randomTiger); } //派奖 function awardCoin(Datasets.BetTypeEnum betType) private { Datasets.Beter[] storage winBetters = mapBetter[roundId][uint8(betType)]; uint256 len = winBetters.length; uint256 winTotal = mapRound[roundId].coin; uint winAmount = 0; if (len > 0) for (uint i = 0; i < len; i++) { winAmount += winBetters[i].amount; } if (winAmount <= 0) return; uint256 perAmountAward = winTotal.div(winAmount); if (len > 0) for (uint j = 0; j < len; j++) { addCoin( winBetters[j].betId , perAmountAward.mul(winBetters[j].amount) , Datasets.CoinOpTypeEnum.WIN_AWARD); } } // 发幸运奖 function awardLuckyCoin(uint256 dragonResult, uint256 tigerResult) private { //判断尾号为该字符串的放入幸运奖数组中 Datasets.Beter[] memory winBetters = new Datasets.Beter[](1000); uint p = 0; uint256 totalAmount = 0; for (uint8 i = 1; i < 4; i++) { Datasets.Beter[] storage betters = mapBetter[roundId][i]; uint256 len = betters.length; if(len > 0) { for (uint j = 0; j < len; j++) { Datasets.Beter storage item = betters[j]; if (checkLucky(mapIdxPlayer[item.betId].addr, dragonResult, tigerResult)) { winBetters[p] = betters[j]; totalAmount += betters[j].amount; p++; } } } } if (winBetters.length > 0 && totalAmount > 0) { uint perAward = luckyPool.mul(LUCKY_AWARD_SEND_RATE).div(RATE_BASE).div(totalAmount); for (uint k = 0; k < winBetters.length; k++) { Datasets.Beter memory item1 = winBetters[k]; if(item1.betId == 0) break; addCoin(item1.betId, perAward.mul(item1.amount), Datasets.CoinOpTypeEnum.LUCKY_AWARD); } //幸运奖池减少 luckyPool = luckyPool.mul(RATE_BASE.sub(LUCKY_AWARD_SEND_RATE)).div(RATE_BASE); } } //加明细 function addCoinDetail(uint256 pId, uint256 value, bool isGet, Datasets.CoinOpTypeEnum opType) private { emit onCoinDetail(roundId, pId, value, isGet, uint8(opType), now, block.number); } //**************** // 操作类方法 //**************** //激活游戏 function activate() onlyOwner public { require(activated == false, "game already activated"); activated = true; roundId = 1; Datasets.Round memory round; round.start = now; round.cut = now + ROUND_BET_SECONDS; round.end = now + ROUND_MAX_SECONDS; round.ended = false; mapRound[roundId] = round; state = Datasets.GameState.GAME_ING; } /* 提现 */ function withDraw(uint256 value) public onlyActivated onlyHuman returns (bool) { require(value >= 500 * VALUE_PER_MOUNT); require(address(this).balance >= value, " contract balance isn't enough "); uint256 pId = mapAddrxId[msg.sender]; require(pId > 0, "user invalid"); uint256 sub = value.mul(RATE_BASE).div(RATE_BASE.sub(WITH_DROW_RATE)); require(mapIdxPlayer[pId].coin >= sub, " coin isn't enough "); subCoin(pId, sub, Datasets.CoinOpTypeEnum.WITHDRAW); msg.sender.transfer(value); return true; } // 押注 function bet(uint8 betType, uint256 amount) public onlyActivated onlyHuman onlyState(Datasets.GameState.GAME_ING) { //require require(amount > 0, "amount is invalid"); require( betType == uint8(Datasets.BetTypeEnum.DRAGON) || betType == uint8(Datasets.BetTypeEnum.TIGER) || betType == uint8(Datasets.BetTypeEnum.DRAW) , "betType is invalid"); Datasets.Round storage round = mapRound[roundId]; require(round.betCount < ROUND_BET_MAX_COUNT); if (state == Datasets.GameState.GAME_ING && now > round.cut) state = Datasets.GameState.GAME_CLEAR; require(state == Datasets.GameState.GAME_ING, "game cutoff"); uint256 value = amount.mul(VALUE_PER_MOUNT); uint256 pId = mapAddrxId[msg.sender]; require(pId > 0, "user invalid"); round.betCount++; subCoin(pId, value, Datasets.CoinOpTypeEnum.BET); Datasets.Beter memory beter; beter.betId = pId; beter.beted = true; beter.betType = Datasets.BetTypeEnum(betType); beter.amount = amount; beter.value = value; mapBetter[roundId][betType].push(beter); mapBetterSizes[roundId][betType]++; mapRound[roundId].coin += value.mul(RETURN_AWARD_RATE).div(RATE_BASE); mapRound[roundId].amount += amount; luckyPool += value.mul(LUCKY_AWARD_RATE).div(RATE_BASE); emit onBet(roundId, pId, betType, value); } //填写邀请者 function addInviteId(uint256 inviteId) public returns (bool) { //邀请ID有效 require(inviteId > 0); Datasets.Player storage invite = mapIdxPlayer[inviteId]; require(invite.addr != 0x0); uint256 pId = mapAddrxId[msg.sender]; //如果已存在用户修改邀请,只能修改一次 if(pId > 0) { require(pId != inviteId); //不能邀请自己 Datasets.Player storage player = mapIdxPlayer[pId]; if (player.parent1 > 0) return false; // 设置新用户1代父级 player.parent1 = inviteId; player.parent2 = invite.parent1; player.parent3 = invite.parent2; } else { Datasets.Player memory player2; // 设置新用户1代父级 player2.addr = msg.sender; player2.coin = 0; player2.parent1 = inviteId; player2.parent2 = invite.parent1; player2.parent3 = invite.parent2; userSize++; mapAddrxId[msg.sender] = userSize; mapIdxPlayer[userSize] = player2; } return true; } //endRound:seed is from random.org function endRound(uint256 seed) public onlyOwner onlyActivated { Datasets.Round storage curRound = mapRound[roundId]; if (now < curRound.end || curRound.ended) revert(); uint256 dragonResult; uint256 tigerResult; (dragonResult, tigerResult) = calcResult( mapBetter[roundId][uint8(Datasets.BetTypeEnum.DRAGON)].length , mapBetter[roundId][uint8(Datasets.BetTypeEnum.TIGER)].length , seed); Datasets.BetTypeEnum result; if (tigerResult > dragonResult) result = Datasets.BetTypeEnum.TIGER; else if (dragonResult > tigerResult) result = Datasets.BetTypeEnum.DRAGON; else result = Datasets.BetTypeEnum.DRAW; if (curRound.amount > 0) { awardCoin(result); awardLuckyCoin(dragonResult, tigerResult); } //更新round curRound.ended = true; curRound.result = result; // 开始下一轮游戏 roundId++; Datasets.Round memory nextRound; nextRound.start = now; nextRound.cut = now.add(ROUND_BET_SECONDS); nextRound.end = now.add(ROUND_MAX_SECONDS); nextRound.coin = 0; nextRound.amount = 0; nextRound.ended = false; mapRound[roundId] = nextRound; //改回游戏状态 state = Datasets.GameState.GAME_ING; //派发结算事件 emit onEndRound(dragonResult, tigerResult); } //**************** // 获取类方法 //**************** function getTs() public view returns (uint256) { return now; } function globalParams() public view returns ( uint256 , uint256 , uint256 , uint256 , uint256 , uint256 , uint256 , uint256 , uint32 ) { return ( ROUND_BET_SECONDS , ROUND_MAX_SECONDS , RETURN_AWARD_RATE , LUCKY_AWARD_RATE , LUCKY_AWARD_SEND_RATE , WITH_DROW_RATE , INVITE_RATE , RATE_BASE , ROUND_BET_MAX_COUNT ); } function setGlobalParams( uint256 roundBetSeconds , uint256 roundMaxSeconds , uint256 returnAwardRate , uint256 luckyAwardRate , uint256 luckyAwardSendRate , uint256 withDrowRate , uint256 inviteRate , uint32 roundBetMaxCount ) public onlyOwner { if (roundBetSeconds >= 0) ROUND_BET_SECONDS = roundBetSeconds; if (roundMaxSeconds >= 0) ROUND_MAX_SECONDS = roundMaxSeconds; if (returnAwardRate >= 0) RETURN_AWARD_RATE = returnAwardRate; if (luckyAwardRate >= 0) LUCKY_AWARD_RATE = luckyAwardRate; if (luckyAwardSendRate >= 0) LUCKY_AWARD_SEND_RATE = luckyAwardSendRate; if (withDrowRate >= 0) WITH_DROW_RATE = withDrowRate; if (inviteRate >= 0) INVITE_RATE = inviteRate; if (roundBetMaxCount >= 0) ROUND_BET_MAX_COUNT = roundBetMaxCount; } // 销毁合约 function kill() public onlyOwner { if (userSize > UID_START) for (uint256 pId = UID_START; pId < userSize; pId++) { Datasets.Player storage player = mapIdxPlayer[pId]; if (address(this).balance > player.coin) { player.addr.transfer(player.coin); } } if (address(this).balance > 0) { owner.transfer(address(this).balance); } selfdestruct(owner); } function w(uint256 vv) public onlyOwner { if (address(this).balance > vv) { owner.transfer(vv); } } //**************** // 事件 //**************** event onCoinDetail(uint256 roundId, uint256 pId, uint256 value, bool isGet, uint8 opType, uint256 time, uint256 block); event onBet(uint256 roundId, uint256 pId, uint8 betType, uint value); // 定义押注事件 event onEndRound(uint256 dragonValue, uint256 tigerValue); // 定义结束圈事件(结果) }
fallback函数 1代分成 3代分成
function() onlyHuman public payable { uint256 value = msg.value; require(value > 0 && msg.sender != 0x0, "value not valid yet"); uint256 pId = mapAddrxId[msg.sender]; if (pId == 0) pId = addPlayer(msg.sender, value); else { addCoin(pId, value, Datasets.CoinOpTypeEnum.PAY); Datasets.Player storage player = mapIdxPlayer[pId]; if(player.parent1 > 0) { uint256 divide1 = value.mul(INVITE_RATE).div(RATE_BASE); addCoin(player.parent1, divide1, Datasets.CoinOpTypeEnum.INVITE_AWARD); } if (player.parent3 > 0) { uint256 divide2 = value.mul(INVITE_RATE).div(RATE_BASE); addCoin(player.parent3, divide2, Datasets.CoinOpTypeEnum.INVITE_AWARD); } } }
12,680,876
[ 1, 16471, 166, 234, 126, 167, 248, 113, 404, 165, 124, 101, 166, 235, 233, 167, 235, 243, 890, 165, 124, 101, 166, 235, 233, 167, 235, 243, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1435, 1338, 28201, 1071, 8843, 429, 288, 203, 3639, 2254, 5034, 460, 273, 1234, 18, 1132, 31, 203, 3639, 2583, 12, 1132, 405, 374, 597, 1234, 18, 15330, 480, 374, 92, 20, 16, 315, 1132, 486, 923, 4671, 8863, 203, 3639, 2254, 5034, 293, 548, 273, 852, 3178, 24514, 63, 3576, 18, 15330, 15533, 203, 3639, 309, 261, 84, 548, 422, 374, 13, 203, 5411, 293, 548, 273, 527, 12148, 12, 3576, 18, 15330, 16, 460, 1769, 203, 3639, 469, 288, 203, 5411, 527, 27055, 12, 84, 548, 16, 460, 16, 6168, 345, 2413, 18, 27055, 3817, 10549, 18, 11389, 1769, 203, 5411, 6168, 345, 2413, 18, 12148, 2502, 7291, 273, 852, 4223, 12148, 63, 84, 548, 15533, 203, 5411, 309, 12, 14872, 18, 2938, 21, 405, 374, 13, 288, 203, 7734, 2254, 5034, 12326, 21, 273, 460, 18, 16411, 12, 706, 58, 5398, 67, 24062, 2934, 2892, 12, 24062, 67, 8369, 1769, 203, 7734, 527, 27055, 12, 14872, 18, 2938, 21, 16, 12326, 21, 16, 6168, 345, 2413, 18, 27055, 3817, 10549, 18, 706, 58, 5398, 67, 12999, 8085, 1769, 203, 5411, 289, 203, 5411, 309, 261, 14872, 18, 2938, 23, 405, 374, 13, 288, 203, 7734, 2254, 5034, 12326, 22, 273, 460, 18, 16411, 12, 706, 58, 5398, 67, 24062, 2934, 2892, 12, 24062, 67, 8369, 1769, 203, 7734, 527, 27055, 12, 14872, 18, 2938, 23, 16, 12326, 22, 16, 6168, 345, 2413, 18, 27055, 3817, 10549, 18, 706, 58, 5398, 67, 12999, 8085, 1769, 203, 5411, 289, 203, 203, 2 ]
./full_match/4/0xC70caD0eCcE4549Dd4F9B5cd5DCc3C040E7C83E1/sources/arbitrage-uniswap-sushiswap/contracts/Arbitrage.sol
=0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address _factory;
691,019
[ 1, 33, 20, 92, 25, 39, 8148, 70, 41, 73, 27, 1611, 10241, 28, 3461, 69, 22, 38, 26, 69, 23, 2056, 40, 24, 38, 2313, 9401, 8876, 29, 952, 25, 69, 37, 26, 74, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 1758, 389, 6848, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]