Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
155
// flag for whether or not contract is paused/
bool public paused;
bool public paused;
20,945
476
// returns the health factor liquidation threshold /
{ return HEALTH_FACTOR_LIQUIDATION_THRESHOLD; }
{ return HEALTH_FACTOR_LIQUIDATION_THRESHOLD; }
17,597
13
// Amount of `token` deposited by the `account`. /
function deposited(address account, address token) public view returns (uint256) { return _data[account][token].deposited; }
function deposited(address account, address token) public view returns (uint256) { return _data[account][token].deposited; }
54,404
6
// external
function tokenURI( uint tokenId
function tokenURI( uint tokenId
31,738
85
// Check for null entries
if (thisNFT.token_id != 0){ IUniswapV3PositionsNFT.CollectParams memory collect_params = IUniswapV3PositionsNFT.CollectParams( thisNFT.token_id, destination_address, type(uint128).max, type(uint128).max ); (uint256 tok0_amt, uint256 tok1_amt) = stakingTokenNFT.collect(collect_params); accumulated_token0 = accumulated_token0.add(tok0_amt); accumulated_token1 = accumulated_token1.add(tok1_amt);
if (thisNFT.token_id != 0){ IUniswapV3PositionsNFT.CollectParams memory collect_params = IUniswapV3PositionsNFT.CollectParams( thisNFT.token_id, destination_address, type(uint128).max, type(uint128).max ); (uint256 tok0_amt, uint256 tok1_amt) = stakingTokenNFT.collect(collect_params); accumulated_token0 = accumulated_token0.add(tok0_amt); accumulated_token1 = accumulated_token1.add(tok1_amt);
4,310
66
// number of transferred address
uint public transferredIndex;
uint public transferredIndex;
17,512
194
// Set a new sector space balance minime token _newSectorSpaceBalance address of the new sector space balance token /
function _setSectorSpaceBalanceToken(address _newSectorSpaceBalance) internal { require(_newSectorSpaceBalance != address(0), "New sectorSpaceBalance should not be zero address"); emit SetSectorSpaceBalanceToken(sectorSpaceBalance, _newSectorSpaceBalance); sectorSpaceBalance = IMiniMeToken(_newSectorSpaceBalance); }
function _setSectorSpaceBalanceToken(address _newSectorSpaceBalance) internal { require(_newSectorSpaceBalance != address(0), "New sectorSpaceBalance should not be zero address"); emit SetSectorSpaceBalanceToken(sectorSpaceBalance, _newSectorSpaceBalance); sectorSpaceBalance = IMiniMeToken(_newSectorSpaceBalance); }
30,596
131
// if DAI value is greater than maximum allowed, return excess DAI to msg.sender
if (receivedDAI > MAX_DONATION) { require(dai.transfer(msg.sender, receivedDAI.sub(MAX_DONATION)), "Excess DAI transfer failed"); receivedDAI = MAX_DONATION; }
if (receivedDAI > MAX_DONATION) { require(dai.transfer(msg.sender, receivedDAI.sub(MAX_DONATION)), "Excess DAI transfer failed"); receivedDAI = MAX_DONATION; }
49,103
10
// Admins can withdraw any funds sent to the contract.
function MEWwithdraw() public payable isAdmin { msg.sender.transfer(address(this).balance); }
function MEWwithdraw() public payable isAdmin { msg.sender.transfer(address(this).balance); }
22,968
5
// Lower Convert an alphabetic character to lower case and return the original value when not alphabetic_b1 The byte to be converted to lower case return bytes1 The converted value if the passed value was alphabeticand in a upper case otherwise returns the original value/
function _lower(bytes1 _b1) internal pure returns (bytes1) { if (_b1 >= 0x41 && _b1 <= 0x5A) { return bytes1(uint8(_b1) + 32); } return _b1; }
function _lower(bytes1 _b1) internal pure returns (bytes1) { if (_b1 >= 0x41 && _b1 <= 0x5A) { return bytes1(uint8(_b1) + 32); } return _b1; }
72,706
20
// Set the address of ValidationManager with which validation will be done/Allowed only for Deployer (see contract Deployerable)
function setValidationManager( address _validationAddress
function setValidationManager( address _validationAddress
26,751
2
// Emitted when an ERC721 token is deposited /
event DepositERC721(address indexed depositor, uint256 indexed bundleId, address tokenAddress, uint256 tokenId);
event DepositERC721(address indexed depositor, uint256 indexed bundleId, address tokenAddress, uint256 tokenId);
30,384
78
// Set the sender on the top of cache.
cache.setSender(msg.sender);
cache.setSender(msg.sender);
29,822
77
// Equivalent to "x + delta(remainder > 0 ? 1 : 0)" but faster.
result := add(x, mul(delta, gt(remainder, 0)))
result := add(x, mul(delta, gt(remainder, 0)))
36,328
13
// We don't want our tokens to start at 0 but at 1.
uint256 tokenId = totalGiftSupply + 1; totalGiftSupply += 1; _safeMint(to[i], tokenId);
uint256 tokenId = totalGiftSupply + 1; totalGiftSupply += 1; _safeMint(to[i], tokenId);
24,417
89
// Order
bytes32 id; address creator; uint256 outcome; Order.Types orderType; uint256 amount; uint256 price; uint256 sharesEscrowed; uint256 moneyEscrowed; bytes32 betterOrderId; bytes32 worseOrderId;
bytes32 id; address creator; uint256 outcome; Order.Types orderType; uint256 amount; uint256 price; uint256 sharesEscrowed; uint256 moneyEscrowed; bytes32 betterOrderId; bytes32 worseOrderId;
37,328
14
// evenly split deposit across multiple gauges in a single round
function depositSplitGauges( address _token, uint256 _amount, uint256 _round, address[] calldata _gauges, uint256 _maxPerVote, address[] calldata _excluded
function depositSplitGauges( address _token, uint256 _amount, uint256 _round, address[] calldata _gauges, uint256 _maxPerVote, address[] calldata _excluded
17,927
0
// SET UP
function setMaxCount(uint256 _maxCount) public onlyOwner { maxCount = _maxCount; }
function setMaxCount(uint256 _maxCount) public onlyOwner { maxCount = _maxCount; }
31,548
32
// - settle the publisher balance INSTANT-ly (ding ding ding, IDA) - adjust static balance directly
token.settleBalance(publisher, (-int256(newIndexValue - idata.indexValue)).mul(int256(idata.totalUnitsApproved)));
token.settleBalance(publisher, (-int256(newIndexValue - idata.indexValue)).mul(int256(idata.totalUnitsApproved)));
21,844
90
// Test remember to change for mainnet deploy
address constant _trustedForwarder = 0x891b363AC490Ed7bd9b36378028f46eC857d2139; //TRUSTED FORWARDER using SafeMath for uint256; using SafeERC20 for IERC20;
address constant _trustedForwarder = 0x891b363AC490Ed7bd9b36378028f46eC857d2139; //TRUSTED FORWARDER using SafeMath for uint256; using SafeERC20 for IERC20;
18,070
93
// Do something
} else revert("Invalid post process");
} else revert("Invalid post process");
6,482
65
// `reporter` receives the reward in locked CELO, so it must be given to an account There is no reward for slashing via the GovernanceSlasher, and `reporter` is set to 0x0.
if (reporter != address(0)) { reporter = getAccounts().signerToAccount(reporter); }
if (reporter != address(0)) { reporter = getAccounts().signerToAccount(reporter); }
25,640
69
// Multiply the result by the integer part 2^n + 1. We have to shift by one bit extra because we have already divided by two when we set the result equal to 0.5 above.
result = result << ((x >> 128) + 1);
result = result << ((x >> 128) + 1);
48,044
10
// NumericalMath John Michael Statheros (GitHub: jstat17) This library builds on the fixed-point math in FixidityLib withnumerical approximations to trigonometric functions, the value of pi,generation of pseudorandom numbers etc. /
library NumericalMath { /** * @notice Returns value of pi to 24 digits of precision. * @return π as int256 */ function pi() public pure returns(int256) { return 3141592653589793238462643; } /** * @notice 7th order numerical approximation to the sine function. * @param theta: angle in radians * @param digits: digits of precision of the angle * @return sin(x) * @dev Example input: sin(11,1) => sin(1.1) * sin(3,0) => sin(3) */ function sin(int256 theta, uint8 digits) public pure returns(int256){ int256 x = FixidityLib.newFixed(theta, digits); int256 _2pi = FixidityLib.multiply(FixidityLib.newFixed(2),pi()); int256 _3_2pi = FixidityLib.multiply(pi(), FixidityLib.newFixedFraction(3, 2)); x = normAngle(x); int256 temp = FixidityLib.abs(FixidityLib.subtract(x, pi())); if (FixidityLib.subtract(x, pi()) < 0 && FixidityLib.subtract(x, FixidityLib.divide(pi(), FixidityLib.newFixed(2))) > 0) { // > 90 deg and < 180 deg x = temp; } else if (FixidityLib.subtract(x, pi()) > 0 && FixidityLib.subtract(x, _3_2pi) < 0) { // > 180 deg and < 270 deg x = FixidityLib.subtract(temp, FixidityLib.multiply(temp, FixidityLib.newFixed(2))); } else if(FixidityLib.subtract(x, _3_2pi) > 0) { // > 270 deg and < 360 deg x = FixidityLib.subtract(x, _2pi); } int256 x_3 = FixidityLib.multiply(FixidityLib.multiply(x, x), x); int256 x_5 = FixidityLib.multiply(FixidityLib.multiply(x_3, x), x); int256 a = FixidityLib.subtract(x, FixidityLib.divide(x_3, FixidityLib.newFixed(6))); int256 b = FixidityLib.add(a, FixidityLib.divide(x_5, FixidityLib.newFixed(120))); return b; } /** * @notice 6th order numerical approximation to the cosine function. * @param theta: angle in radians * @param digits: digits of precision of the angle * @return cos(x) * @dev Example input: cos(11,1) => cos(1.1) * cos(3,0) => cos(3) */ function cos(int256 theta, uint8 digits) public pure returns(int256){ int256 x = FixidityLib.newFixed(theta, digits); int256 _2pi = FixidityLib.multiply(FixidityLib.newFixed(2),pi()); int256 _3_2pi = FixidityLib.multiply(pi(), FixidityLib.newFixedFraction(3, 2)); x = normAngle(x); int256 temp = FixidityLib.abs(FixidityLib.subtract(x, pi())); int8 c = 1; if (FixidityLib.subtract(x, pi()) < 0 && FixidityLib.subtract(x, FixidityLib.divide(pi(), FixidityLib.newFixed(2))) > 0) { // > 90 deg and < 180 deg x = temp; c = -1; } else if (FixidityLib.subtract(x, pi()) > 0 && FixidityLib.subtract(x, _3_2pi) < 0) { // > 180 deg and < 270 deg x = FixidityLib.subtract(temp, FixidityLib.multiply(temp, FixidityLib.newFixed(2))); c = -1; } else if(FixidityLib.subtract(x, _3_2pi) > 0) { // > 270 deg and < 360 deg x = FixidityLib.subtract(x, _2pi); } int256 x_2 = FixidityLib.multiply(x, x); int256 x_4 = FixidityLib.multiply(x_2, x_2); int256 a = FixidityLib.subtract(FixidityLib.fixed1(), FixidityLib.divide(x_2, FixidityLib.newFixed(2))); int256 b = FixidityLib.add(a, FixidityLib.divide(x_4, FixidityLib.newFixed(24))); return b*c; } /** * @notice Numerical approximation of the tangent function, * using the fact that sin(x)/cos(x) = tan(x). * @param theta: angle in radians * @param digits: digits of precision of the angle * @return tan(x) * @dev Example input: tan(11,1) => tan(1.1) * tan(3,0) => tan(3) */ function tan(int256 theta, uint8 digits) public pure returns(int256) { return (FixidityLib.divide(sin(theta, digits), cos(theta, digits))); /** Taylor series approximation of tan(x), but is poor near asymptotes. * int256 x = FixidityLib.newFixed(theta, digits); int256 _2pi = FixidityLib.multiply(FixidityLib.newFixed(2),pi()); int256 _3_2pi = FixidityLib.multiply(pi(), FixidityLib.newFixedFraction(3, 2)); x = normAngle(x); int256 temp = FixidityLib.abs(FixidityLib.subtract(x, pi())); int8 c = 1; if (FixidityLib.subtract(x, pi()) < 0 && FixidityLib.subtract(x, FixidityLib.divide(pi(), FixidityLib.newFixed(2))) > 0) { // > 90 deg and < 180 deg x = temp; c = -1; } else if (FixidityLib.subtract(x, pi()) > 0 && FixidityLib.subtract(x, _3_2pi) < 0) { // > 180 deg and < 270 deg x = FixidityLib.subtract(temp, FixidityLib.multiply(temp, FixidityLib.newFixed(2))); } else if(FixidityLib.subtract(x, _3_2pi) > 0) { // > 270 deg and < 360 deg x = FixidityLib.subtract(x, _2pi); c = -1; } int256 x_3 = FixidityLib.multiply(FixidityLib.multiply(x, x), x); int256 x_5 = FixidityLib.multiply(FixidityLib.multiply(x_3, x), x); int256 a = FixidityLib.add(x, FixidityLib.divide(x_3, FixidityLib.newFixed(3))); int256 b = FixidityLib.add(a, FixidityLib.multiply(x_5, FixidityLib.newFixedFraction(2, 15))); return b*c; */ } /** * @notice Helper function for the trigonometric functions, * which transforms any angle > 360 deg or < -360 deg to * -360 < x < 360, or its 'normal'/'standard' representation. * @param x: angle in radians * @return angle x where -2π < x < 2π */ function normAngle(int256 x) internal pure returns(int256) { int256 _2pi = FixidityLib.multiply(FixidityLib.newFixed(2),pi()); bool k = false; while (!k) { int256 x_sub2pi = FixidityLib.subtract(x, _2pi); if (x_sub2pi > 0) { x = x_sub2pi; continue; } int256 x_add2pi = FixidityLib.add(x, _2pi); if (x_add2pi < 0) { x = x_add2pi; continue; } k = !k; } return x; } /** * @notice Generates a random int256 between some upper * and lower bounds using an int256 seed. * @param num_seed: integer seed * @param lower: lower-bound of the random number * @param upper: upper-bound of the random number * @return random int256 between upper and lower (inclusive) */ function getRandomNum(int256 num_seed, int256 lower, int256 upper) public pure returns(int256) { int256 rand_num = convBtwUpLo(callKeccak256(abi.encodePacked(num_seed)), lower, upper); return rand_num; } /** * @notice Helper function to hash a seed using keccak256. * @param seed: bytes object * @return int256 of hashed seed */ function callKeccak256(bytes memory seed) public pure returns(int256) { return int256(uint256(keccak256(seed))); } /** * @notice Helper function to convert some large number * to be between an upper and lower bound. * @param bigNum: int256 of some large number * @param lower: lower-bound of the output number * @param upper: upper-bound of the output number * @return int256 between upper and lower (inclusive) */ function convBtwUpLo(int256 bigNum, int256 lower, int256 upper) public pure returns(int256) { return FixidityLib.add(FixidityLib.abs(bigNum) % FixidityLib.add(FixidityLib.subtract(upper, lower), 1), lower); } /** * @notice I saw Patrick Collins use this method in a * Chainlink video tutorial, where he took a large * random number and broke it up into multiple * random numbers. The use case is for verifiably * random number generation, so that multiple * random numbers do not need to be generated. * @dev take note that this only generates * a random number between 1 and an upper bound. * Should update so that any range can be * generated. * @param x: the large random number * @param y: the upper bound of the random number, * but this value must mutate with each successive * call of this function. * @param y_orig: the original and unmutating * upper bound of the random number * @return new_rand: the new random number that * is between 1 and upper * @return y: the mutated form of the upper bound * that must be used as the y in the next call of * this function */ function getAnotherSplitRand(int256 x, int256 y, int256 y_orig) public pure returns(int256, int256) { int256 new_rand = (x % y)/(y/y_orig) + 1; y *= y; return (new_rand, y); } }
library NumericalMath { /** * @notice Returns value of pi to 24 digits of precision. * @return π as int256 */ function pi() public pure returns(int256) { return 3141592653589793238462643; } /** * @notice 7th order numerical approximation to the sine function. * @param theta: angle in radians * @param digits: digits of precision of the angle * @return sin(x) * @dev Example input: sin(11,1) => sin(1.1) * sin(3,0) => sin(3) */ function sin(int256 theta, uint8 digits) public pure returns(int256){ int256 x = FixidityLib.newFixed(theta, digits); int256 _2pi = FixidityLib.multiply(FixidityLib.newFixed(2),pi()); int256 _3_2pi = FixidityLib.multiply(pi(), FixidityLib.newFixedFraction(3, 2)); x = normAngle(x); int256 temp = FixidityLib.abs(FixidityLib.subtract(x, pi())); if (FixidityLib.subtract(x, pi()) < 0 && FixidityLib.subtract(x, FixidityLib.divide(pi(), FixidityLib.newFixed(2))) > 0) { // > 90 deg and < 180 deg x = temp; } else if (FixidityLib.subtract(x, pi()) > 0 && FixidityLib.subtract(x, _3_2pi) < 0) { // > 180 deg and < 270 deg x = FixidityLib.subtract(temp, FixidityLib.multiply(temp, FixidityLib.newFixed(2))); } else if(FixidityLib.subtract(x, _3_2pi) > 0) { // > 270 deg and < 360 deg x = FixidityLib.subtract(x, _2pi); } int256 x_3 = FixidityLib.multiply(FixidityLib.multiply(x, x), x); int256 x_5 = FixidityLib.multiply(FixidityLib.multiply(x_3, x), x); int256 a = FixidityLib.subtract(x, FixidityLib.divide(x_3, FixidityLib.newFixed(6))); int256 b = FixidityLib.add(a, FixidityLib.divide(x_5, FixidityLib.newFixed(120))); return b; } /** * @notice 6th order numerical approximation to the cosine function. * @param theta: angle in radians * @param digits: digits of precision of the angle * @return cos(x) * @dev Example input: cos(11,1) => cos(1.1) * cos(3,0) => cos(3) */ function cos(int256 theta, uint8 digits) public pure returns(int256){ int256 x = FixidityLib.newFixed(theta, digits); int256 _2pi = FixidityLib.multiply(FixidityLib.newFixed(2),pi()); int256 _3_2pi = FixidityLib.multiply(pi(), FixidityLib.newFixedFraction(3, 2)); x = normAngle(x); int256 temp = FixidityLib.abs(FixidityLib.subtract(x, pi())); int8 c = 1; if (FixidityLib.subtract(x, pi()) < 0 && FixidityLib.subtract(x, FixidityLib.divide(pi(), FixidityLib.newFixed(2))) > 0) { // > 90 deg and < 180 deg x = temp; c = -1; } else if (FixidityLib.subtract(x, pi()) > 0 && FixidityLib.subtract(x, _3_2pi) < 0) { // > 180 deg and < 270 deg x = FixidityLib.subtract(temp, FixidityLib.multiply(temp, FixidityLib.newFixed(2))); c = -1; } else if(FixidityLib.subtract(x, _3_2pi) > 0) { // > 270 deg and < 360 deg x = FixidityLib.subtract(x, _2pi); } int256 x_2 = FixidityLib.multiply(x, x); int256 x_4 = FixidityLib.multiply(x_2, x_2); int256 a = FixidityLib.subtract(FixidityLib.fixed1(), FixidityLib.divide(x_2, FixidityLib.newFixed(2))); int256 b = FixidityLib.add(a, FixidityLib.divide(x_4, FixidityLib.newFixed(24))); return b*c; } /** * @notice Numerical approximation of the tangent function, * using the fact that sin(x)/cos(x) = tan(x). * @param theta: angle in radians * @param digits: digits of precision of the angle * @return tan(x) * @dev Example input: tan(11,1) => tan(1.1) * tan(3,0) => tan(3) */ function tan(int256 theta, uint8 digits) public pure returns(int256) { return (FixidityLib.divide(sin(theta, digits), cos(theta, digits))); /** Taylor series approximation of tan(x), but is poor near asymptotes. * int256 x = FixidityLib.newFixed(theta, digits); int256 _2pi = FixidityLib.multiply(FixidityLib.newFixed(2),pi()); int256 _3_2pi = FixidityLib.multiply(pi(), FixidityLib.newFixedFraction(3, 2)); x = normAngle(x); int256 temp = FixidityLib.abs(FixidityLib.subtract(x, pi())); int8 c = 1; if (FixidityLib.subtract(x, pi()) < 0 && FixidityLib.subtract(x, FixidityLib.divide(pi(), FixidityLib.newFixed(2))) > 0) { // > 90 deg and < 180 deg x = temp; c = -1; } else if (FixidityLib.subtract(x, pi()) > 0 && FixidityLib.subtract(x, _3_2pi) < 0) { // > 180 deg and < 270 deg x = FixidityLib.subtract(temp, FixidityLib.multiply(temp, FixidityLib.newFixed(2))); } else if(FixidityLib.subtract(x, _3_2pi) > 0) { // > 270 deg and < 360 deg x = FixidityLib.subtract(x, _2pi); c = -1; } int256 x_3 = FixidityLib.multiply(FixidityLib.multiply(x, x), x); int256 x_5 = FixidityLib.multiply(FixidityLib.multiply(x_3, x), x); int256 a = FixidityLib.add(x, FixidityLib.divide(x_3, FixidityLib.newFixed(3))); int256 b = FixidityLib.add(a, FixidityLib.multiply(x_5, FixidityLib.newFixedFraction(2, 15))); return b*c; */ } /** * @notice Helper function for the trigonometric functions, * which transforms any angle > 360 deg or < -360 deg to * -360 < x < 360, or its 'normal'/'standard' representation. * @param x: angle in radians * @return angle x where -2π < x < 2π */ function normAngle(int256 x) internal pure returns(int256) { int256 _2pi = FixidityLib.multiply(FixidityLib.newFixed(2),pi()); bool k = false; while (!k) { int256 x_sub2pi = FixidityLib.subtract(x, _2pi); if (x_sub2pi > 0) { x = x_sub2pi; continue; } int256 x_add2pi = FixidityLib.add(x, _2pi); if (x_add2pi < 0) { x = x_add2pi; continue; } k = !k; } return x; } /** * @notice Generates a random int256 between some upper * and lower bounds using an int256 seed. * @param num_seed: integer seed * @param lower: lower-bound of the random number * @param upper: upper-bound of the random number * @return random int256 between upper and lower (inclusive) */ function getRandomNum(int256 num_seed, int256 lower, int256 upper) public pure returns(int256) { int256 rand_num = convBtwUpLo(callKeccak256(abi.encodePacked(num_seed)), lower, upper); return rand_num; } /** * @notice Helper function to hash a seed using keccak256. * @param seed: bytes object * @return int256 of hashed seed */ function callKeccak256(bytes memory seed) public pure returns(int256) { return int256(uint256(keccak256(seed))); } /** * @notice Helper function to convert some large number * to be between an upper and lower bound. * @param bigNum: int256 of some large number * @param lower: lower-bound of the output number * @param upper: upper-bound of the output number * @return int256 between upper and lower (inclusive) */ function convBtwUpLo(int256 bigNum, int256 lower, int256 upper) public pure returns(int256) { return FixidityLib.add(FixidityLib.abs(bigNum) % FixidityLib.add(FixidityLib.subtract(upper, lower), 1), lower); } /** * @notice I saw Patrick Collins use this method in a * Chainlink video tutorial, where he took a large * random number and broke it up into multiple * random numbers. The use case is for verifiably * random number generation, so that multiple * random numbers do not need to be generated. * @dev take note that this only generates * a random number between 1 and an upper bound. * Should update so that any range can be * generated. * @param x: the large random number * @param y: the upper bound of the random number, * but this value must mutate with each successive * call of this function. * @param y_orig: the original and unmutating * upper bound of the random number * @return new_rand: the new random number that * is between 1 and upper * @return y: the mutated form of the upper bound * that must be used as the y in the next call of * this function */ function getAnotherSplitRand(int256 x, int256 y, int256 y_orig) public pure returns(int256, int256) { int256 new_rand = (x % y)/(y/y_orig) + 1; y *= y; return (new_rand, y); } }
32,793
26
// core: Should be FarmMaster Contract
function setCore(address _core) public onlyCore { core = _core; emit CoreTransferred(core, _core); }
function setCore(address _core) public onlyCore { core = _core; emit CoreTransferred(core, _core); }
43,994
9
// =====================Events====================//=====================Modifiers ====================//can only be called if actions are initialized/
function actionsInitialized() private view { require(actions.length > 0, "O1"); }
function actionsInitialized() private view { require(actions.length > 0, "O1"); }
56,144
89
// Returns the multiplication of two unsigned integers, reverting onoverflow. 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; }
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; }
28,149
231
// Normalize the amount
_amount = _amount.mul(1e18).div(10**tokenList[1].decimals); tradeAmountLeft = _amount; executeTradeBatch(); emit TradeState(_amount, percentChange, sellPercent, lastDiggTotalSupply, currentTotalSupply, block.number);
_amount = _amount.mul(1e18).div(10**tokenList[1].decimals); tradeAmountLeft = _amount; executeTradeBatch(); emit TradeState(_amount, percentChange, sellPercent, lastDiggTotalSupply, currentTotalSupply, block.number);
61,143
35
// require(msg.sender == owner, "msg.sender != owner");
require(!allPunksAssigned); require(punkIndex < 10000); if (punkIndexToAddress[punkIndex] != to) { if (punkIndexToAddress[punkIndex] != address(0)) { balanceOf[punkIndexToAddress[punkIndex]]--;
require(!allPunksAssigned); require(punkIndex < 10000); if (punkIndexToAddress[punkIndex] != to) { if (punkIndexToAddress[punkIndex] != address(0)) { balanceOf[punkIndexToAddress[punkIndex]]--;
1,132
18
// Remove the token from the swapTokens array if it exists
_removeTokenFromArray(token, swapTokens);
_removeTokenFromArray(token, swapTokens);
5,570
9
// Exactly 8 iterations
for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (ONE << s)) { _n >>= s; res |= s; }
for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (ONE << s)) { _n >>= s; res |= s; }
3,750
18
// sale (current totalSupply) represents 55% of final token supply need to mint additional poolSupply tokens representing 45% offinal token totalSupply: poolSupply = totalSupply(45 / 55) the minted poolSupply is initially allocated to the token manager
uint256 poolSupply = SafeMath.div(SafeMath.mul(totalSupply, 45),55);
uint256 poolSupply = SafeMath.div(SafeMath.mul(totalSupply, 45),55);
19,991
107
// This is sent from the registry and already deleted on their end
delete membershipRequests[candidate];
delete membershipRequests[candidate];
16,648
34
// Hook that is called before an `amount` of tokens are burned. Calling conditions:- `burner` and `from` cannot be the zero address/
function _beforeBurn( address burner, address from, uint256 id,
function _beforeBurn( address burner, address from, uint256 id,
16,768
27
// GenesisProtocol implementation -an organization's voting machine scheme. /
contract GenesisProtocol is IntVoteInterface, GenesisProtocolLogic { using ECDSA for bytes32; // Digest describing the data the user signs according EIP 712. // Needs to match what is passed to Metamask. bytes32 public constant DELEGATION_HASH_EIP712 = keccak256(abi.encodePacked( "address GenesisProtocolAddress", "bytes32 ProposalId", "uint256 Vote", "uint256 AmountToStake", "uint256 Nonce" )); mapping(address=>uint256) public stakesNonce; //stakes Nonce /** * @dev Constructor */ constructor(IERC20 _stakingToken) public // solhint-disable-next-line no-empty-blocks GenesisProtocolLogic(_stakingToken) { } /** * @dev staking function * @param _proposalId id of the proposal * @param _vote NO(2) or YES(1). * @param _amount the betting amount * @return bool true - the proposal has been executed * false - otherwise. */ function stake(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) { return _stake(_proposalId, _vote, _amount, msg.sender); } /** * @dev stakeWithSignature function * @param _proposalId id of the proposal * @param _vote NO(2) or YES(1). * @param _amount the betting amount * @param _nonce nonce value ,it is part of the signature to ensure that a signature can be received only once. * @param _signatureType signature type 1 - for web3.eth.sign 2 - for eth_signTypedData according to EIP #712. * @param _signature - signed data by the staker * @return bool true - the proposal has been executed * false - otherwise. */ function stakeWithSignature( bytes32 _proposalId, uint256 _vote, uint256 _amount, uint256 _nonce, uint256 _signatureType, bytes calldata _signature ) external returns(bool) { // Recreate the digest the user signed bytes32 delegationDigest; if (_signatureType == 2) { delegationDigest = keccak256( abi.encodePacked( DELEGATION_HASH_EIP712, keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ) ) ); } else { delegationDigest = keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ).toEthSignedMessageHash(); } address staker = delegationDigest.recover(_signature); //a garbage staker address due to wrong signature will revert due to lack of approval and funds. require(staker != address(0), "staker address cannot be 0"); require(stakesNonce[staker] == _nonce); stakesNonce[staker] = stakesNonce[staker].add(1); return _stake(_proposalId, _vote, _amount, staker); } /** * @dev voting function * @param _proposalId id of the proposal * @param _vote NO(2) or YES(1). * @param _amount the reputation amount to vote with . if _amount == 0 it will use all voter reputation. * @param _voter voter address * @return bool true - the proposal has been executed * false - otherwise. */ function vote(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter) external votable(_proposalId) returns(bool) { Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; address voter; if (params.voteOnBehalf != address(0)) { require(msg.sender == params.voteOnBehalf); voter = _voter; } else { voter = msg.sender; } return internalVote(_proposalId, voter, _vote, _amount); } /** * @dev Cancel the vote of the msg.sender. * cancel vote is not allow in genesisProtocol so this function doing nothing. * This function is here in order to comply to the IntVoteInterface . */ function cancelVote(bytes32 _proposalId) external votable(_proposalId) { //this is not allowed return; } /** * @dev execute check if the proposal has been decided, and if so, execute the proposal * @param _proposalId the id of the proposal * @return bool true - the proposal has been executed * false - otherwise. */ function execute(bytes32 _proposalId) external votable(_proposalId) returns(bool) { return _execute(_proposalId); } /** * @dev getNumberOfChoices returns the number of choices possible in this proposal * @return uint256 that contains number of choices */ function getNumberOfChoices(bytes32) external view returns(uint256) { return NUM_OF_CHOICES; } /** * @dev getProposalTimes returns proposals times variables. * @param _proposalId id of the proposal * @return proposals times array */ function getProposalTimes(bytes32 _proposalId) external view returns(uint[3] memory times) { return proposals[_proposalId].times; } /** * @dev voteInfo returns the vote and the amount of reputation of the user committed to this proposal * @param _proposalId the ID of the proposal * @param _voter the address of the voter * @return uint256 vote - the voters vote * uint256 reputation - amount of reputation committed by _voter to _proposalId */ function voteInfo(bytes32 _proposalId, address _voter) external view returns(uint, uint) { Voter memory voter = proposals[_proposalId].voters[_voter]; return (voter.vote, voter.reputation); } /** * @dev voteStatus returns the reputation voted for a proposal for a specific voting choice. * @param _proposalId the ID of the proposal * @param _choice the index in the * @return voted reputation for the given choice */ function voteStatus(bytes32 _proposalId, uint256 _choice) external view returns(uint256) { return proposals[_proposalId].votes[_choice]; } /** * @dev isVotable check if the proposal is votable * @param _proposalId the ID of the proposal * @return bool true or false */ function isVotable(bytes32 _proposalId) external view returns(bool) { return _isVotable(_proposalId); } /** * @dev proposalStatus return the total votes and stakes for a given proposal * @param _proposalId the ID of the proposal * @return uint256 preBoostedVotes YES * @return uint256 preBoostedVotes NO * @return uint256 total stakes YES * @return uint256 total stakes NO */ function proposalStatus(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) { return ( proposals[_proposalId].preBoostedVotes[YES], proposals[_proposalId].preBoostedVotes[NO], proposals[_proposalId].stakes[YES], proposals[_proposalId].stakes[NO] ); } /** * @dev getProposalOrganization return the organizationId for a given proposal * @param _proposalId the ID of the proposal * @return bytes32 organization identifier */ function getProposalOrganization(bytes32 _proposalId) external view returns(bytes32) { return (proposals[_proposalId].organizationId); } /** * @dev getStaker return the vote and stake amount for a given proposal and staker * @param _proposalId the ID of the proposal * @param _staker staker address * @return uint256 vote * @return uint256 amount */ function getStaker(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) { return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount); } /** * @dev voteStake return the amount stakes for a given proposal and vote * @param _proposalId the ID of the proposal * @param _vote vote number * @return uint256 stake amount */ function voteStake(bytes32 _proposalId, uint256 _vote) external view returns(uint256) { return proposals[_proposalId].stakes[_vote]; } /** * @dev voteStake return the winningVote for a given proposal * @param _proposalId the ID of the proposal * @return uint256 winningVote */ function winningVote(bytes32 _proposalId) external view returns(uint256) { return proposals[_proposalId].winningVote; } /** * @dev voteStake return the state for a given proposal * @param _proposalId the ID of the proposal * @return ProposalState proposal state */ function state(bytes32 _proposalId) external view returns(ProposalState) { return proposals[_proposalId].state; } /** * @dev isAbstainAllow returns if the voting machine allow abstain (0) * @return bool true or false */ function isAbstainAllow() external pure returns(bool) { return false; } /** * @dev getAllowedRangeOfChoices returns the allowed range of choices for a voting machine. * @return min - minimum number of choices max - maximum number of choices */ function getAllowedRangeOfChoices() external pure returns(uint256 min, uint256 max) { return (YES, NO); } /** * @dev score return the proposal score * @param _proposalId the ID of the proposal * @return uint256 proposal score. */ function score(bytes32 _proposalId) public view returns(uint256) { return _score(_proposalId); } }
contract GenesisProtocol is IntVoteInterface, GenesisProtocolLogic { using ECDSA for bytes32; // Digest describing the data the user signs according EIP 712. // Needs to match what is passed to Metamask. bytes32 public constant DELEGATION_HASH_EIP712 = keccak256(abi.encodePacked( "address GenesisProtocolAddress", "bytes32 ProposalId", "uint256 Vote", "uint256 AmountToStake", "uint256 Nonce" )); mapping(address=>uint256) public stakesNonce; //stakes Nonce /** * @dev Constructor */ constructor(IERC20 _stakingToken) public // solhint-disable-next-line no-empty-blocks GenesisProtocolLogic(_stakingToken) { } /** * @dev staking function * @param _proposalId id of the proposal * @param _vote NO(2) or YES(1). * @param _amount the betting amount * @return bool true - the proposal has been executed * false - otherwise. */ function stake(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) { return _stake(_proposalId, _vote, _amount, msg.sender); } /** * @dev stakeWithSignature function * @param _proposalId id of the proposal * @param _vote NO(2) or YES(1). * @param _amount the betting amount * @param _nonce nonce value ,it is part of the signature to ensure that a signature can be received only once. * @param _signatureType signature type 1 - for web3.eth.sign 2 - for eth_signTypedData according to EIP #712. * @param _signature - signed data by the staker * @return bool true - the proposal has been executed * false - otherwise. */ function stakeWithSignature( bytes32 _proposalId, uint256 _vote, uint256 _amount, uint256 _nonce, uint256 _signatureType, bytes calldata _signature ) external returns(bool) { // Recreate the digest the user signed bytes32 delegationDigest; if (_signatureType == 2) { delegationDigest = keccak256( abi.encodePacked( DELEGATION_HASH_EIP712, keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ) ) ); } else { delegationDigest = keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ).toEthSignedMessageHash(); } address staker = delegationDigest.recover(_signature); //a garbage staker address due to wrong signature will revert due to lack of approval and funds. require(staker != address(0), "staker address cannot be 0"); require(stakesNonce[staker] == _nonce); stakesNonce[staker] = stakesNonce[staker].add(1); return _stake(_proposalId, _vote, _amount, staker); } /** * @dev voting function * @param _proposalId id of the proposal * @param _vote NO(2) or YES(1). * @param _amount the reputation amount to vote with . if _amount == 0 it will use all voter reputation. * @param _voter voter address * @return bool true - the proposal has been executed * false - otherwise. */ function vote(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter) external votable(_proposalId) returns(bool) { Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; address voter; if (params.voteOnBehalf != address(0)) { require(msg.sender == params.voteOnBehalf); voter = _voter; } else { voter = msg.sender; } return internalVote(_proposalId, voter, _vote, _amount); } /** * @dev Cancel the vote of the msg.sender. * cancel vote is not allow in genesisProtocol so this function doing nothing. * This function is here in order to comply to the IntVoteInterface . */ function cancelVote(bytes32 _proposalId) external votable(_proposalId) { //this is not allowed return; } /** * @dev execute check if the proposal has been decided, and if so, execute the proposal * @param _proposalId the id of the proposal * @return bool true - the proposal has been executed * false - otherwise. */ function execute(bytes32 _proposalId) external votable(_proposalId) returns(bool) { return _execute(_proposalId); } /** * @dev getNumberOfChoices returns the number of choices possible in this proposal * @return uint256 that contains number of choices */ function getNumberOfChoices(bytes32) external view returns(uint256) { return NUM_OF_CHOICES; } /** * @dev getProposalTimes returns proposals times variables. * @param _proposalId id of the proposal * @return proposals times array */ function getProposalTimes(bytes32 _proposalId) external view returns(uint[3] memory times) { return proposals[_proposalId].times; } /** * @dev voteInfo returns the vote and the amount of reputation of the user committed to this proposal * @param _proposalId the ID of the proposal * @param _voter the address of the voter * @return uint256 vote - the voters vote * uint256 reputation - amount of reputation committed by _voter to _proposalId */ function voteInfo(bytes32 _proposalId, address _voter) external view returns(uint, uint) { Voter memory voter = proposals[_proposalId].voters[_voter]; return (voter.vote, voter.reputation); } /** * @dev voteStatus returns the reputation voted for a proposal for a specific voting choice. * @param _proposalId the ID of the proposal * @param _choice the index in the * @return voted reputation for the given choice */ function voteStatus(bytes32 _proposalId, uint256 _choice) external view returns(uint256) { return proposals[_proposalId].votes[_choice]; } /** * @dev isVotable check if the proposal is votable * @param _proposalId the ID of the proposal * @return bool true or false */ function isVotable(bytes32 _proposalId) external view returns(bool) { return _isVotable(_proposalId); } /** * @dev proposalStatus return the total votes and stakes for a given proposal * @param _proposalId the ID of the proposal * @return uint256 preBoostedVotes YES * @return uint256 preBoostedVotes NO * @return uint256 total stakes YES * @return uint256 total stakes NO */ function proposalStatus(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) { return ( proposals[_proposalId].preBoostedVotes[YES], proposals[_proposalId].preBoostedVotes[NO], proposals[_proposalId].stakes[YES], proposals[_proposalId].stakes[NO] ); } /** * @dev getProposalOrganization return the organizationId for a given proposal * @param _proposalId the ID of the proposal * @return bytes32 organization identifier */ function getProposalOrganization(bytes32 _proposalId) external view returns(bytes32) { return (proposals[_proposalId].organizationId); } /** * @dev getStaker return the vote and stake amount for a given proposal and staker * @param _proposalId the ID of the proposal * @param _staker staker address * @return uint256 vote * @return uint256 amount */ function getStaker(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) { return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount); } /** * @dev voteStake return the amount stakes for a given proposal and vote * @param _proposalId the ID of the proposal * @param _vote vote number * @return uint256 stake amount */ function voteStake(bytes32 _proposalId, uint256 _vote) external view returns(uint256) { return proposals[_proposalId].stakes[_vote]; } /** * @dev voteStake return the winningVote for a given proposal * @param _proposalId the ID of the proposal * @return uint256 winningVote */ function winningVote(bytes32 _proposalId) external view returns(uint256) { return proposals[_proposalId].winningVote; } /** * @dev voteStake return the state for a given proposal * @param _proposalId the ID of the proposal * @return ProposalState proposal state */ function state(bytes32 _proposalId) external view returns(ProposalState) { return proposals[_proposalId].state; } /** * @dev isAbstainAllow returns if the voting machine allow abstain (0) * @return bool true or false */ function isAbstainAllow() external pure returns(bool) { return false; } /** * @dev getAllowedRangeOfChoices returns the allowed range of choices for a voting machine. * @return min - minimum number of choices max - maximum number of choices */ function getAllowedRangeOfChoices() external pure returns(uint256 min, uint256 max) { return (YES, NO); } /** * @dev score return the proposal score * @param _proposalId the ID of the proposal * @return uint256 proposal score. */ function score(bytes32 _proposalId) public view returns(uint256) { return _score(_proposalId); } }
18,566
212
// Add exp.This is intended to be called by Dungeon, Arena, Guild contracts.
function addExp(uint256 _tokenId, uint32 _exp) onlyAccessDeploy public returns (bool)
function addExp(uint256 _tokenId, uint32 _exp) onlyAccessDeploy public returns (bool)
18,931
2
// Implements `IFactory`.// Calls the `_createChild` hook that inheriting contracts must override./ Registers child contract address such that `isChild` is `true`./ Emits `NewChild` event.//data_ Encoded data to pass down to child contract constructor./ return New child contract address.
function createChild(bytes calldata data_) external virtual override nonReentrant returns (address) {
function createChild(bytes calldata data_) external virtual override nonReentrant returns (address) {
20,998
31
// An event emitted when tokens are minted
event TokensMinted( address indexed _owner, uint256 indexed _id, uint256 _amount );
event TokensMinted( address indexed _owner, uint256 indexed _id, uint256 _amount );
34,432
15
// nftStatus[tokenId].isMating = true; nftStatus[tokenId].lovePoint -= 50;
matingId += 1; matingStatus[matingId] = MatingStatus({ tokenIds: tokenIds, startTime: block.timestamp, endTime: block.timestamp + timedelta, birthed: false });
matingId += 1; matingStatus[matingId] = MatingStatus({ tokenIds: tokenIds, startTime: block.timestamp, endTime: block.timestamp + timedelta, birthed: false });
23,121
4
// Set the threshold limits for each aggregator parameters must be same length aggregators address[] memory flaggingThresholds uint256[] memory /
function setThresholds(address[] memory aggregators, uint256[] memory flaggingThresholds) public onlyOwner()
function setThresholds(address[] memory aggregators, uint256[] memory flaggingThresholds) public onlyOwner()
45,434
63
// Deposit a portion of CRV to the voter to gain CRV boost.
crvBalance = adjustCRV(crvBalance); IERC20(crvToken).safeIncreaseAllowance(uniswap, crvBalance); address[] memory path = new address[](3); path[0] = crvToken; path[1] = wethToken; path[2] = wbtcToken; IUniswapV2Router(uniswap).swapExactTokensForTokens(
crvBalance = adjustCRV(crvBalance); IERC20(crvToken).safeIncreaseAllowance(uniswap, crvBalance); address[] memory path = new address[](3); path[0] = crvToken; path[1] = wethToken; path[2] = wbtcToken; IUniswapV2Router(uniswap).swapExactTokensForTokens(
12,092
56
// 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);
function balanceOf(address account, uint256 id) external view returns (uint256);
2,295
75
// Set to pairData.updatePeriod. maxUpdateWindow is called by other contracts.
uint public maxUpdateWindow; ExchangePair public pairData; IAggregatorV3 public oracle;
uint public maxUpdateWindow; ExchangePair public pairData; IAggregatorV3 public oracle;
52,171
27
// On upgrades this is set in the case that the pause router is used to pass the rollback check
address internal rollbackRouterImplementation;
address internal rollbackRouterImplementation;
29,757
46
// all the nfts are expired. so just add
head = expireId; tail = expireId; checkPoints[bucket] = Bucket(expireId, expireId); infos[expireId] = ExpireMetadata(EMPTY,EMPTY,expiresAt); return;
head = expireId; tail = expireId; checkPoints[bucket] = Bucket(expireId, expireId); infos[expireId] = ExpireMetadata(EMPTY,EMPTY,expiresAt); return;
10,224
0
// Role for `PoolManager` only - keccak256("POOLMANAGER_ROLE")
bytes32 public constant POOLMANAGER_ROLE = 0x5916f72c85af4ac6f7e34636ecc97619c4b2085da099a5d28f3e58436cfbe562;
bytes32 public constant POOLMANAGER_ROLE = 0x5916f72c85af4ac6f7e34636ecc97619c4b2085da099a5d28f3e58436cfbe562;
17,898
946
// ========== ORACLE VIEW FUNCTIONS ========== /
function valueOfAsset(address token, uint amount) public override view returns (uint) { return priceOf(token).mul(amount).div(1e18); }
function valueOfAsset(address token, uint amount) public override view returns (uint) { return priceOf(token).mul(amount).div(1e18); }
48,983
12
// this defines a new function modifier which will be added to our contract function modifiers are for reducing repeating code
modifier calledByManager() { require(msg.sender == manager); // only manager can call this function _; // this statement takes the content (all statements) of the function to which the modifier is attached // and puts it to this place (this is done by the compiler behind the scenes) }
modifier calledByManager() { require(msg.sender == manager); // only manager can call this function _; // this statement takes the content (all statements) of the function to which the modifier is attached // and puts it to this place (this is done by the compiler behind the scenes) }
212
19
// Issue an escrow ticket to the buyer
address escrowTicketer = getMarketController().getEscrowTicketer(_consignmentId); IEscrowTicketer(escrowTicketer).issueTicket(_consignmentId, _amount, payable(msg.sender));
address escrowTicketer = getMarketController().getEscrowTicketer(_consignmentId); IEscrowTicketer(escrowTicketer).issueTicket(_consignmentId, _amount, payable(msg.sender));
18,151
24
// transfer the NFT to the auction contract to hold in escrow for the duration of the auction
IERC721(_nftAddress).safeTransferFrom(auction.payee, address(this), _tokenId); emit AuctionCreated( auctionIdsCounter.current(), _nftAddress, _tokenId, auction.payee, _reservePrice, auction.paused, _msgSender(),
IERC721(_nftAddress).safeTransferFrom(auction.payee, address(this), _tokenId); emit AuctionCreated( auctionIdsCounter.current(), _nftAddress, _tokenId, auction.payee, _reservePrice, auction.paused, _msgSender(),
18,829
1
// https:docs.uniswap.org/contracts/v3/reference/deployments
address public constant UNISWAP_V3_ROUTER_ADDRESS = 0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45;
address public constant UNISWAP_V3_ROUTER_ADDRESS = 0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45;
29,465
25
// `contribute()` in batch form./ May not revert if any individual contribution fails./args The arguments to pass to each `contribute()` call./ return votingPowers The voting power received for each contribution.
function batchContribute( BatchContributeArgs calldata args
function batchContribute( BatchContributeArgs calldata args
38,784
72
// shareAsset balance index, this asset distribution index
balanceIndex = ua.processingBalanceIndex; distributionIndex = ua.processingDistributionIndex;
balanceIndex = ua.processingBalanceIndex; distributionIndex = ua.processingDistributionIndex;
34,354
65
// Picking the largest value between block.timestamp, action.timestamp and startingTime
uint88 timestamp = uint88(block.timestamp > action.timestamp ? block.timestamp : action.timestamp); if (action.action == Actions.UNSTAKED) _transfer(orcOwner, address(this), id); else { if (block.timestamp > action.timestamp) _claim(id); timestamp = timestamp > action.timestamp ? timestamp : action.timestamp; }
uint88 timestamp = uint88(block.timestamp > action.timestamp ? block.timestamp : action.timestamp); if (action.action == Actions.UNSTAKED) _transfer(orcOwner, address(this), id); else { if (block.timestamp > action.timestamp) _claim(id); timestamp = timestamp > action.timestamp ? timestamp : action.timestamp; }
13,987
3
// Remove a key from the store. The key to remove must exist. self A Set struct key An address to remove from the Set. context A message string about interpretation of the issue. Normally the calling function. /
function remove( Set storage self, bytes32 key, string memory context
function remove( Set storage self, bytes32 key, string memory context
29,301
33
// VestingVault A token holder contract that can release its token balance gradually like atypical vesting scheme, with a cliff and vesting period. Optionally revocable by theowner. /
contract VestingVault is Initializable, Ownable { // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // cliff period of a year and a duration of four years, are safe to use. // solhint-disable not-rely-on-time using SafeMath for uint256; using SafeERC20 for IERC20; using ECDSA for bytes32; event TokensReleased(address token, uint256 amount); event TokenVestingRevoked(address token); event TokenVestingBeneficiaryVerified(address beneficiary); // beneficiary of tokens after they are released address private _beneficiary; uint256 private _vestingAmount; uint256 private _intervalVested; uint256 private _cliff; uint256 private _start; uint256 private _interval; string private _stamp; uint256 private _duration; bool private _revocable; bool private _beneficiaryVerified; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint32 private constant SECONDS_PER_MINUTE = 60; uint32 private constant MINUTES_PER_HOUR = 60; uint32 private constant SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR; uint32 private constant HOURS_PER_DAY = 24; uint32 private constant SECONDS_PER_DAY = HOURS_PER_DAY * SECONDS_PER_HOUR; // 86400 seconds per day uint32 private constant DAYS_PER_MONTH = 30; uint32 private constant SECONDS_PER_MONTH = DAYS_PER_MONTH * SECONDS_PER_DAY; // Month here is of 30 days period or 2592000 seconds per month. uint32 private constant DAYS_PER_YEAR = 365; uint32 private constant SECONDS_PER_YEAR = DAYS_PER_YEAR * SECONDS_PER_DAY; // Year here is of 365 days period. mapping(address => uint256) private _released; mapping(address => bool) private _revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @param beneficiary address of the beneficiary to whom vested tokens are transferred * @param vestingAmount vesting amount of the benefeciary to be recieved * @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest * @param start the time (as Unix time) at which point vesting starts * @param duration duration in seconds of the period in which the tokens will vest * @param interval The time period at which the tokens has to be vested * @param stamp the interval is in Minutes(MIN)/Hours(H)/Days(D)/Months(M)/Years(Y) * @param revocable whether the vesting is revocable or not */ function initialize( address beneficiary, uint256 vestingAmount, uint256 start, uint256 cliffDuration, uint256 duration, uint256 interval, string memory stamp, bool revocable ) public initializer { require( beneficiary != address(0), "VestingVault: beneficiary is the zero address" ); require(duration > 0, "VestingVault: duration is 0"); // solhint-disable-next-line max-line-length require( cliffDuration <= duration, "VestingVault: cliff is longer than duration" ); // solhint-disable-next-line max-line-length require( start.add(duration) > block.timestamp, "VestingVault: final time is before current time" ); require( keccak256(abi.encodePacked(stamp)) == keccak256("MIN") || keccak256(abi.encodePacked(stamp)) == keccak256("H") || keccak256(abi.encodePacked(stamp)) == keccak256("D") || keccak256(abi.encodePacked(stamp)) == keccak256("M") || keccak256(abi.encodePacked(stamp)) == keccak256("Y"), "VestingVault: Interval Stamp can be Minutes(MIN)/Hours(H)/Days(D)/Months(M)/Years(Y)" ); uint256 interval_in_sec = getCalculatedIntervalInSeconds(interval, stamp); require( ((cliffDuration % interval_in_sec == 0) && (duration % interval_in_sec == 0)) , "VestingVault: duration & cliffDuration should multiplication of interval" ); Ownable.initialize(msg.sender); _beneficiary = beneficiary; _revocable = revocable; _vestingAmount = vestingAmount; _duration = duration; _cliff = start.add(cliffDuration); _interval = interval; _stamp = stamp; _start = start; _beneficiaryVerified = false; setCalculatedVestedAmountPerInterval(vestingAmount, duration, interval, stamp); } /** * @return the beneficiary of the tokens vesting. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the beneficiaryVerified of the tokens vesting. */ function beneficiaryVerified() public view returns (bool) { return _beneficiaryVerified; } /** * @return the vesting amount of the benefeciary. */ function vestingAmount() public view returns (uint256) { return _vestingAmount; } /** * @return the amount of token to be vested for the benefeciary per interval. */ function intervalVested() public view returns (uint256) { return _intervalVested; } /** * @return the cliff time of the token vesting. */ function cliff() public view returns (uint256) { return _cliff; } /** * @return the interval time of the token vesting in seconds. */ function interval() public view returns (uint256) { return _interval; } /** * @return the interval time is respect to Minutes(MIN)/Hours(H)/Days(D)/Months(M)/Years(Y). */ function stamp() public view returns (string memory) { return _stamp; } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _start; } /** * @return the duration of the token vesting. */ function duration() public view returns (uint256) { return _duration; } /** * @return true if the vesting is revocable. */ function revocable() public view returns (bool) { return _revocable; } /** * @return the amount of the token released. */ function released(address token) public view returns (uint256) { return _released[token]; } /** * @return true if the token is revoked. */ function revoked(address token) public view returns (bool) { return _revoked[token]; } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasable(IERC20 token) public view returns (uint256) { return _vestedAmount(token).sub(_released[address(token)]); } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(IERC20 token) public { require(_beneficiaryVerified == true, "VestingVault: Beneficiary signature not yet verified"); require(block.timestamp > _cliff, "VestingVault: you have not passed the lock period yet"); uint256 unreleased = _releasableAmount(token); require(unreleased > 0, "VestingVault: no tokens are due"); _released[address(token)] = _released[address(token)].add(unreleased); token.safeTransfer(_beneficiary, unreleased); emit TokensReleased(address(token), unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(IERC20 token) public onlyOwner { require(_revocable, "VestingVault: cannot revoke"); require( !_revoked[address(token)], "VestingVault: token already revoked" ); uint256 balance = token.balanceOf(address(this)); uint256 unreleased = _releasableAmount(token); uint256 refund = balance.sub(unreleased); _revoked[address(token)] = true; token.safeTransfer(owner(), refund); emit TokenVestingRevoked(address(token)); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function _releasableAmount(IERC20 token) private view returns (uint256) { return _vestedAmount(token).sub(_released[address(token)]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function _vestedAmount(IERC20 token) private view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(_released[address(token)]); if (block.timestamp < _cliff) { return 0; } else if ( block.timestamp >= _start.add(_duration) || _revoked[address(token)] ) { return totalBalance; } else { return getBatchTimestamp().mul(totalBalance).div(_duration); } } /** * @return Retrieves the duration passed from start till now according to interval in seconds. */ function getBatchTimestamp() private view returns (uint256) { require( block.timestamp > _start, "VestingVault: Current timestamp is smaller than start time" ); uint256 INTERVAL_TIMESTAMP = getCalculatedIntervalInSeconds(_interval,_stamp); uint256 ADJUSTED_INTERVAL = (block.timestamp.sub(_start)).div(INTERVAL_TIMESTAMP); uint256 START_TILL_NOW = ADJUSTED_INTERVAL.mul(INTERVAL_TIMESTAMP); return START_TILL_NOW; } /** * @return Timestamp in Interval. */ function getCalculatedIntervalInSeconds(uint256 interval__, string memory stamp__) public pure returns (uint256) { if (keccak256(abi.encodePacked(stamp__)) == keccak256("MIN")) { return (SECONDS_PER_MINUTE * interval__); } else if (keccak256(abi.encodePacked(stamp__)) == keccak256("H")) { return (SECONDS_PER_HOUR * interval__); } else if (keccak256(abi.encodePacked(stamp__)) == keccak256("D")) { return (SECONDS_PER_DAY * interval__); } else if (keccak256(abi.encodePacked(stamp__)) == keccak256("M")) { return (SECONDS_PER_MONTH * interval__); } else if (keccak256(abi.encodePacked(stamp__)) == keccak256("Y")) { return (SECONDS_PER_YEAR * interval__); } } /** * @dev Sets the calculated vesting amount per interval. * @param vestedAmount The total amount that is to be vested. * @param duration_ The total duration in which the veted tokens will be released. * @param interval_ The intervals at which the token will be released. * @param stamp_ The intervals mentioned are in Minutes(MIN)/Hours(H)/Days(D)/Months(M)/Years(Y). */ function setCalculatedVestedAmountPerInterval( uint256 vestedAmount, uint256 duration_, uint256 interval_, string memory stamp_ ) private { uint256 diff = vestedAmount; if (keccak256(abi.encodePacked(stamp_)) == keccak256("MIN")) { _intervalVested = ( diff.div(duration_.div(SECONDS_PER_MINUTE).div(interval_)) ); } else if (keccak256(abi.encodePacked(stamp_)) == keccak256("H")) { _intervalVested = ( diff.div(duration_.div(SECONDS_PER_HOUR).div(interval_)) ); } else if (keccak256(abi.encodePacked(stamp_)) == keccak256("D")) { _intervalVested = ( diff.div(duration_.div(SECONDS_PER_DAY).div(interval_)) ); } else if (keccak256(abi.encodePacked(stamp_)) == keccak256("M")) { _intervalVested = ( diff.div(duration_.div(SECONDS_PER_MONTH).div(interval_)) ); } else if (keccak256(abi.encodePacked(stamp_)) == keccak256("Y")) { _intervalVested = ( diff.div(duration_.div(SECONDS_PER_YEAR).div(interval_)) ); } } function getVestedAmountNow() public view returns (uint256) { return getBatchTimestamp().mul(_vestingAmount).div(_duration); } function verifyAddress(bytes32 hash, bytes memory signature) public returns (bool) { // bytes32 tmpHash = toEthSignedMessageHash(hash); address tempAddress = recover(hash, signature); require(tempAddress == _beneficiary, "VestingVault: ECDSA Recover Failed, Beneficiary Address Signature is invalid"); _beneficiaryVerified = true; emit TokenVestingBeneficiaryVerified(_beneficiary); return true; } function recover(bytes32 hash, bytes memory signature) public pure returns (address) { return hash.recover(signature); } function toEthSignedMessageHash(bytes32 hash) public pure returns (bytes32) { return hash.toEthSignedMessageHash(); } uint256[50] private ______gap; }
contract VestingVault is Initializable, Ownable { // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // cliff period of a year and a duration of four years, are safe to use. // solhint-disable not-rely-on-time using SafeMath for uint256; using SafeERC20 for IERC20; using ECDSA for bytes32; event TokensReleased(address token, uint256 amount); event TokenVestingRevoked(address token); event TokenVestingBeneficiaryVerified(address beneficiary); // beneficiary of tokens after they are released address private _beneficiary; uint256 private _vestingAmount; uint256 private _intervalVested; uint256 private _cliff; uint256 private _start; uint256 private _interval; string private _stamp; uint256 private _duration; bool private _revocable; bool private _beneficiaryVerified; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint32 private constant SECONDS_PER_MINUTE = 60; uint32 private constant MINUTES_PER_HOUR = 60; uint32 private constant SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR; uint32 private constant HOURS_PER_DAY = 24; uint32 private constant SECONDS_PER_DAY = HOURS_PER_DAY * SECONDS_PER_HOUR; // 86400 seconds per day uint32 private constant DAYS_PER_MONTH = 30; uint32 private constant SECONDS_PER_MONTH = DAYS_PER_MONTH * SECONDS_PER_DAY; // Month here is of 30 days period or 2592000 seconds per month. uint32 private constant DAYS_PER_YEAR = 365; uint32 private constant SECONDS_PER_YEAR = DAYS_PER_YEAR * SECONDS_PER_DAY; // Year here is of 365 days period. mapping(address => uint256) private _released; mapping(address => bool) private _revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @param beneficiary address of the beneficiary to whom vested tokens are transferred * @param vestingAmount vesting amount of the benefeciary to be recieved * @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest * @param start the time (as Unix time) at which point vesting starts * @param duration duration in seconds of the period in which the tokens will vest * @param interval The time period at which the tokens has to be vested * @param stamp the interval is in Minutes(MIN)/Hours(H)/Days(D)/Months(M)/Years(Y) * @param revocable whether the vesting is revocable or not */ function initialize( address beneficiary, uint256 vestingAmount, uint256 start, uint256 cliffDuration, uint256 duration, uint256 interval, string memory stamp, bool revocable ) public initializer { require( beneficiary != address(0), "VestingVault: beneficiary is the zero address" ); require(duration > 0, "VestingVault: duration is 0"); // solhint-disable-next-line max-line-length require( cliffDuration <= duration, "VestingVault: cliff is longer than duration" ); // solhint-disable-next-line max-line-length require( start.add(duration) > block.timestamp, "VestingVault: final time is before current time" ); require( keccak256(abi.encodePacked(stamp)) == keccak256("MIN") || keccak256(abi.encodePacked(stamp)) == keccak256("H") || keccak256(abi.encodePacked(stamp)) == keccak256("D") || keccak256(abi.encodePacked(stamp)) == keccak256("M") || keccak256(abi.encodePacked(stamp)) == keccak256("Y"), "VestingVault: Interval Stamp can be Minutes(MIN)/Hours(H)/Days(D)/Months(M)/Years(Y)" ); uint256 interval_in_sec = getCalculatedIntervalInSeconds(interval, stamp); require( ((cliffDuration % interval_in_sec == 0) && (duration % interval_in_sec == 0)) , "VestingVault: duration & cliffDuration should multiplication of interval" ); Ownable.initialize(msg.sender); _beneficiary = beneficiary; _revocable = revocable; _vestingAmount = vestingAmount; _duration = duration; _cliff = start.add(cliffDuration); _interval = interval; _stamp = stamp; _start = start; _beneficiaryVerified = false; setCalculatedVestedAmountPerInterval(vestingAmount, duration, interval, stamp); } /** * @return the beneficiary of the tokens vesting. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the beneficiaryVerified of the tokens vesting. */ function beneficiaryVerified() public view returns (bool) { return _beneficiaryVerified; } /** * @return the vesting amount of the benefeciary. */ function vestingAmount() public view returns (uint256) { return _vestingAmount; } /** * @return the amount of token to be vested for the benefeciary per interval. */ function intervalVested() public view returns (uint256) { return _intervalVested; } /** * @return the cliff time of the token vesting. */ function cliff() public view returns (uint256) { return _cliff; } /** * @return the interval time of the token vesting in seconds. */ function interval() public view returns (uint256) { return _interval; } /** * @return the interval time is respect to Minutes(MIN)/Hours(H)/Days(D)/Months(M)/Years(Y). */ function stamp() public view returns (string memory) { return _stamp; } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _start; } /** * @return the duration of the token vesting. */ function duration() public view returns (uint256) { return _duration; } /** * @return true if the vesting is revocable. */ function revocable() public view returns (bool) { return _revocable; } /** * @return the amount of the token released. */ function released(address token) public view returns (uint256) { return _released[token]; } /** * @return true if the token is revoked. */ function revoked(address token) public view returns (bool) { return _revoked[token]; } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasable(IERC20 token) public view returns (uint256) { return _vestedAmount(token).sub(_released[address(token)]); } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(IERC20 token) public { require(_beneficiaryVerified == true, "VestingVault: Beneficiary signature not yet verified"); require(block.timestamp > _cliff, "VestingVault: you have not passed the lock period yet"); uint256 unreleased = _releasableAmount(token); require(unreleased > 0, "VestingVault: no tokens are due"); _released[address(token)] = _released[address(token)].add(unreleased); token.safeTransfer(_beneficiary, unreleased); emit TokensReleased(address(token), unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(IERC20 token) public onlyOwner { require(_revocable, "VestingVault: cannot revoke"); require( !_revoked[address(token)], "VestingVault: token already revoked" ); uint256 balance = token.balanceOf(address(this)); uint256 unreleased = _releasableAmount(token); uint256 refund = balance.sub(unreleased); _revoked[address(token)] = true; token.safeTransfer(owner(), refund); emit TokenVestingRevoked(address(token)); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function _releasableAmount(IERC20 token) private view returns (uint256) { return _vestedAmount(token).sub(_released[address(token)]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function _vestedAmount(IERC20 token) private view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(_released[address(token)]); if (block.timestamp < _cliff) { return 0; } else if ( block.timestamp >= _start.add(_duration) || _revoked[address(token)] ) { return totalBalance; } else { return getBatchTimestamp().mul(totalBalance).div(_duration); } } /** * @return Retrieves the duration passed from start till now according to interval in seconds. */ function getBatchTimestamp() private view returns (uint256) { require( block.timestamp > _start, "VestingVault: Current timestamp is smaller than start time" ); uint256 INTERVAL_TIMESTAMP = getCalculatedIntervalInSeconds(_interval,_stamp); uint256 ADJUSTED_INTERVAL = (block.timestamp.sub(_start)).div(INTERVAL_TIMESTAMP); uint256 START_TILL_NOW = ADJUSTED_INTERVAL.mul(INTERVAL_TIMESTAMP); return START_TILL_NOW; } /** * @return Timestamp in Interval. */ function getCalculatedIntervalInSeconds(uint256 interval__, string memory stamp__) public pure returns (uint256) { if (keccak256(abi.encodePacked(stamp__)) == keccak256("MIN")) { return (SECONDS_PER_MINUTE * interval__); } else if (keccak256(abi.encodePacked(stamp__)) == keccak256("H")) { return (SECONDS_PER_HOUR * interval__); } else if (keccak256(abi.encodePacked(stamp__)) == keccak256("D")) { return (SECONDS_PER_DAY * interval__); } else if (keccak256(abi.encodePacked(stamp__)) == keccak256("M")) { return (SECONDS_PER_MONTH * interval__); } else if (keccak256(abi.encodePacked(stamp__)) == keccak256("Y")) { return (SECONDS_PER_YEAR * interval__); } } /** * @dev Sets the calculated vesting amount per interval. * @param vestedAmount The total amount that is to be vested. * @param duration_ The total duration in which the veted tokens will be released. * @param interval_ The intervals at which the token will be released. * @param stamp_ The intervals mentioned are in Minutes(MIN)/Hours(H)/Days(D)/Months(M)/Years(Y). */ function setCalculatedVestedAmountPerInterval( uint256 vestedAmount, uint256 duration_, uint256 interval_, string memory stamp_ ) private { uint256 diff = vestedAmount; if (keccak256(abi.encodePacked(stamp_)) == keccak256("MIN")) { _intervalVested = ( diff.div(duration_.div(SECONDS_PER_MINUTE).div(interval_)) ); } else if (keccak256(abi.encodePacked(stamp_)) == keccak256("H")) { _intervalVested = ( diff.div(duration_.div(SECONDS_PER_HOUR).div(interval_)) ); } else if (keccak256(abi.encodePacked(stamp_)) == keccak256("D")) { _intervalVested = ( diff.div(duration_.div(SECONDS_PER_DAY).div(interval_)) ); } else if (keccak256(abi.encodePacked(stamp_)) == keccak256("M")) { _intervalVested = ( diff.div(duration_.div(SECONDS_PER_MONTH).div(interval_)) ); } else if (keccak256(abi.encodePacked(stamp_)) == keccak256("Y")) { _intervalVested = ( diff.div(duration_.div(SECONDS_PER_YEAR).div(interval_)) ); } } function getVestedAmountNow() public view returns (uint256) { return getBatchTimestamp().mul(_vestingAmount).div(_duration); } function verifyAddress(bytes32 hash, bytes memory signature) public returns (bool) { // bytes32 tmpHash = toEthSignedMessageHash(hash); address tempAddress = recover(hash, signature); require(tempAddress == _beneficiary, "VestingVault: ECDSA Recover Failed, Beneficiary Address Signature is invalid"); _beneficiaryVerified = true; emit TokenVestingBeneficiaryVerified(_beneficiary); return true; } function recover(bytes32 hash, bytes memory signature) public pure returns (address) { return hash.recover(signature); } function toEthSignedMessageHash(bytes32 hash) public pure returns (bytes32) { return hash.toEthSignedMessageHash(); } uint256[50] private ______gap; }
38,051
2
// Internal migration id used to specify that a contract has already been initialized. /
string constant private INITIALIZED_ID = "initialized";
string constant private INITIALIZED_ID = "initialized";
37,503
14
// Get the subscriber at a given index in the set of addresses subscribed to a given registrant.Note that order is not guaranteed as updates are made. /
function subscriberAt(
function subscriberAt(
24,547
38
// modifier that allow to call function if current stage is bigger than specified
modifier stageAfter(Stage _stage) { require(uint256(currentStage) > uint256(_stage)); _; }
modifier stageAfter(Stage _stage) { require(uint256(currentStage) > uint256(_stage)); _; }
18,484
299
// `snapshotId` is the snapshot id that the value was generated at
uint256 snapshotId;
uint256 snapshotId;
27,893
0
// File: contracts\interfaces\IWitnetRequest.sol/The Witnet Data Request basic interface./The Witnet Foundation.
interface IWitnetRequest { /// A `IWitnetRequest` is constructed around a `bytes` value containing /// a well-formed Witnet Data Request using Protocol Buffers. function bytecode() external view returns (bytes memory); /// Returns SHA256 hash of Witnet Data Request as CBOR-encoded bytes. function hash() external view returns (bytes32); }
interface IWitnetRequest { /// A `IWitnetRequest` is constructed around a `bytes` value containing /// a well-formed Witnet Data Request using Protocol Buffers. function bytecode() external view returns (bytes memory); /// Returns SHA256 hash of Witnet Data Request as CBOR-encoded bytes. function hash() external view returns (bytes32); }
82,200
4
// Returns number of tokens owned by given address./_owner Address of token owner.
function balanceOf(address _owner) public override view returns (uint256 balance) { return balances[_owner]; }
function balanceOf(address _owner) public override view returns (uint256 balance) { return balances[_owner]; }
11,902
101
// Transfers `amount` tokens from `msg.sender` to `to`./to The address to move the tokens./amount of the tokens to move./ return (bool) Returns True if succeeded.
function transfer(address to, uint256 amount) public returns (bool) { // If `amount` is 0, or `msg.sender` is `to` nothing happens if (amount != 0 || msg.sender == to) { uint256 srcBalance = balanceOf[msg.sender]; require(srcBalance >= amount, "ERC20: balance too low"); if (msg.sender != to) { require(to != address(0), "ERC20: no zero address"); // Moved down so low balance calls safe some gas balanceOf[msg.sender] = srcBalance - amount; // Underflow is checked balanceOf[to] += amount; } } emit Transfer(msg.sender, to, amount); return true; }
function transfer(address to, uint256 amount) public returns (bool) { // If `amount` is 0, or `msg.sender` is `to` nothing happens if (amount != 0 || msg.sender == to) { uint256 srcBalance = balanceOf[msg.sender]; require(srcBalance >= amount, "ERC20: balance too low"); if (msg.sender != to) { require(to != address(0), "ERC20: no zero address"); // Moved down so low balance calls safe some gas balanceOf[msg.sender] = srcBalance - amount; // Underflow is checked balanceOf[to] += amount; } } emit Transfer(msg.sender, to, amount); return true; }
6,254
761
// There are no due protocol fee amounts during initialization
dueProtocolFeeAmounts = new uint256[](2);
dueProtocolFeeAmounts = new uint256[](2);
13,663
61
// Maximum possible cap in wei for phase one
uint256 public periodPreITO_mainCapInWei = periodPreITO_mainCapInUSD.mul(1 ether).div(rateETHUSD);
uint256 public periodPreITO_mainCapInWei = periodPreITO_mainCapInUSD.mul(1 ether).div(rateETHUSD);
17,816
5
// returns the price of an LP token. token0/token1 price; zero on failure
function getLPPrice( address token0, address token1, uint24 fee, uint32 secondsAgo
function getLPPrice( address token0, address token1, uint24 fee, uint32 secondsAgo
19,475
41
// Adjust this using `setReserve(...)` to keep some of the position in reserve in the strategy, to accomodate larger variations needed to sustain the strategy's core positon(s)
uint256 private reserve = 0;
uint256 private reserve = 0;
73,604
96
// CHECK: branchcond ((%a + (arg 1)) > int256 0), block18, block20
} while(a+b > 0);
} while(a+b > 0);
23,182
23
// Returns true if this contract implements the interface defined by`interfaceId`. See the correspondingto learn more about how these ids are created. This function call must use less than 30000 gas. /
function supportsInterface(bytes4 interfaceId) external view returns (bool);
function supportsInterface(bytes4 interfaceId) external view returns (bool);
3,592
9
// internal
function mintVault() internal { for (uint256 i; i < 130; i++) { _safeMint(miuFounder, totalSupply + 1 + i); } totalSupply = 130; }
function mintVault() internal { for (uint256 i; i < 130; i++) { _safeMint(miuFounder, totalSupply + 1 + i); } totalSupply = 130; }
23,971
323
// Fetch start cumulative factors
EarningsPool.Data memory startPool = cumulativeFactorsPool(_transcoder, _startRound);
EarningsPool.Data memory startPool = cumulativeFactorsPool(_transcoder, _startRound);
23,874
285
// emitted when trying to do Flash Loan. flashLoan address is 0x00 when no flash loan used
event Leverage(uint256 amountRequested, uint256 amountGiven, bool deficit, address flashLoan);
event Leverage(uint256 amountRequested, uint256 amountGiven, bool deficit, address flashLoan);
38,284
32
// Is Valid Token (internal)/Checks if given tokenId exists (Doesn't apply to mobs)/_tokenId TokenId to check
function isValidToken(uint256 _tokenId) internal view returns(bool){ return owners[_tokenId] != address(0); }
function isValidToken(uint256 _tokenId) internal view returns(bool){ return owners[_tokenId] != address(0); }
33,014
423
// Deploys a new PlatformTokenVendor contract _rewardsToken reward or platform rewards token. eg MTA or WMATICreturn address of the deployed PlatformTokenVendor contract /
function create(IERC20 _rewardsToken) public returns (address) { PlatformTokenVendor newPlatformTokenVendor = new PlatformTokenVendor(_rewardsToken); return address(newPlatformTokenVendor); }
function create(IERC20 _rewardsToken) public returns (address) { PlatformTokenVendor newPlatformTokenVendor = new PlatformTokenVendor(_rewardsToken); return address(newPlatformTokenVendor); }
23,851
293
// Verify System Signer Order
address isSystemSigner = StringLibrary.getAddress(abi.encodePacked(IERC721(asset.token), asset.assetTokenId, msg.sender, trade.buyer, IERC20(trade.erc20Token), trade.offeredPrice, trade.auctionStart, trade.auctionEnd, nonce), systemSig.v, systemSig.r, systemSig.s); require(owner() == isSystemSigner, "system signer should sign correct message");
address isSystemSigner = StringLibrary.getAddress(abi.encodePacked(IERC721(asset.token), asset.assetTokenId, msg.sender, trade.buyer, IERC20(trade.erc20Token), trade.offeredPrice, trade.auctionStart, trade.auctionEnd, nonce), systemSig.v, systemSig.r, systemSig.s); require(owner() == isSystemSigner, "system signer should sign correct message");
77,006
5
// make sure that caller owns lender note
address lender = lenderNote.ownerOf(lenderNoteId); require(lender == msg.sender, "RepaymentController: not owner of lender note");
address lender = lenderNote.ownerOf(lenderNoteId); require(lender == msg.sender, "RepaymentController: not owner of lender note");
12,443
84
// 储存所有任务的映射 mapping(address => mapping(uint => Task)) taskList;
mapping(address => Task) taskList;
mapping(address => Task) taskList;
38,746
110
// Transfer ownership to the admin address who becomes owner of the contract
transferOwnership(_admin); emit Initialize(_stakedToken, _rewardToken, _rewardPerBlock, _startBlock, _bonusEndBlock, _poolLimitPerUser, _admin, _lockStakeDate, _lockWithdrawDate, _feeAddress);
transferOwnership(_admin); emit Initialize(_stakedToken, _rewardToken, _rewardPerBlock, _startBlock, _bonusEndBlock, _poolLimitPerUser, _admin, _lockStakeDate, _lockWithdrawDate, _feeAddress);
22,788
156
// Accounting: Part of MEH contract responsible for eth accounting.
contract Accounting is MEHAccessControl { using SafeMath for uint256; // Balances of users, admin, charity mapping(address => uint256) public balances; // Emitted when a user deposits or withdraws funds from the contract event LogContractBalance(address payerOrPayee, int balanceChange); // ** PAYMENT PROCESSING ** // /// @dev Withdraws users available balance. function withdraw() external whenNotPaused { address payee = msg.sender; uint256 payment = balances[payee]; require(payment != 0); assert(address(this).balance >= payment); balances[payee] = 0; // reentrancy safe payee.transfer(payment); emit LogContractBalance(payee, int256(-payment)); } /// @dev Lets external authorized contract (operators) to transfer balances within MEH contract. /// MEH contract doesn't transfer funds on its own. Instead Market and Rentals contracts /// are granted operator access. function operatorTransferFunds( address _payer, address _recipient, uint _amount) external onlyBalanceOperators whenNotPaused { require(balances[_payer] >= _amount); _deductFrom(_payer, _amount); _depositTo(_recipient, _amount); } /// @dev Deposits eth to msg.sender balance. function depositFunds() internal whenNotPaused { _depositTo(msg.sender, msg.value); emit LogContractBalance(msg.sender, int256(msg.value)); } /// @dev Increases recipients internal balance. function _depositTo(address _recipient, uint _amount) internal { balances[_recipient] = balances[_recipient].add(_amount); } /// @dev Increases payers internal balance. function _deductFrom(address _payer, uint _amount) internal { balances[_payer] = balances[_payer].sub(_amount); } // ** ADMIN ** // /// @notice Allows admin to withdraw contract balance in emergency. And distribute manualy /// aftrewards. /// @dev As the contract is not designed to keep users funds (users can withdraw /// at anytime) it should be relatively easy to manualy transfer unclaimed funds to /// their owners. This is an alternatinve to selfdestruct allowing blocks ledger (ERC721 tokens) /// to be immutable. function adminRescueFunds() external onlyOwner whenPaused { address payee = owner; uint256 payment = address(this).balance; payee.transfer(payment); } /// @dev Checks if a msg.sender has enough balance to pay the price _needed. function canPay(uint _needed) internal view returns (bool) { return (msg.value.add(balances[msg.sender]) >= _needed); } }
contract Accounting is MEHAccessControl { using SafeMath for uint256; // Balances of users, admin, charity mapping(address => uint256) public balances; // Emitted when a user deposits or withdraws funds from the contract event LogContractBalance(address payerOrPayee, int balanceChange); // ** PAYMENT PROCESSING ** // /// @dev Withdraws users available balance. function withdraw() external whenNotPaused { address payee = msg.sender; uint256 payment = balances[payee]; require(payment != 0); assert(address(this).balance >= payment); balances[payee] = 0; // reentrancy safe payee.transfer(payment); emit LogContractBalance(payee, int256(-payment)); } /// @dev Lets external authorized contract (operators) to transfer balances within MEH contract. /// MEH contract doesn't transfer funds on its own. Instead Market and Rentals contracts /// are granted operator access. function operatorTransferFunds( address _payer, address _recipient, uint _amount) external onlyBalanceOperators whenNotPaused { require(balances[_payer] >= _amount); _deductFrom(_payer, _amount); _depositTo(_recipient, _amount); } /// @dev Deposits eth to msg.sender balance. function depositFunds() internal whenNotPaused { _depositTo(msg.sender, msg.value); emit LogContractBalance(msg.sender, int256(msg.value)); } /// @dev Increases recipients internal balance. function _depositTo(address _recipient, uint _amount) internal { balances[_recipient] = balances[_recipient].add(_amount); } /// @dev Increases payers internal balance. function _deductFrom(address _payer, uint _amount) internal { balances[_payer] = balances[_payer].sub(_amount); } // ** ADMIN ** // /// @notice Allows admin to withdraw contract balance in emergency. And distribute manualy /// aftrewards. /// @dev As the contract is not designed to keep users funds (users can withdraw /// at anytime) it should be relatively easy to manualy transfer unclaimed funds to /// their owners. This is an alternatinve to selfdestruct allowing blocks ledger (ERC721 tokens) /// to be immutable. function adminRescueFunds() external onlyOwner whenPaused { address payee = owner; uint256 payment = address(this).balance; payee.transfer(payment); } /// @dev Checks if a msg.sender has enough balance to pay the price _needed. function canPay(uint _needed) internal view returns (bool) { return (msg.value.add(balances[msg.sender]) >= _needed); } }
46,186
98
// We don't need to do any validation here, we can let the Tournament decide if the pot contribution amount derived from msg.value represents a valid power level to use for reviving this Wizard.
uint88 purchasedPower = costToPower(msg.value); uint256 potContributionValue = _potContribution(purchasedPower); tournament.revive.value(potContributionValue)(wizardId);
uint88 purchasedPower = costToPower(msg.value); uint256 potContributionValue = _potContribution(purchasedPower); tournament.revive.value(potContributionValue)(wizardId);
48,071
2
// onlyOwner
function isDelegate( address addr ) external view onlyOwner returns ( bool ){ return _delegates[addr]; }
function isDelegate( address addr ) external view onlyOwner returns ( bool ){ return _delegates[addr]; }
31,742
72
// owner 0x2B33fb0702bf19EdCC4aaAf5774dD17990781FF7
owner = 0x2B33fb0702bf19EdCC4aaAf5774dD17990781FF7; name = "NEK"; symbol = "NEK"; _mint(owner, 100000000 * 10**18);
owner = 0x2B33fb0702bf19EdCC4aaAf5774dD17990781FF7; name = "NEK"; symbol = "NEK"; _mint(owner, 100000000 * 10**18);
19,617
96
// new pointer is old + 0x20 + the footprint of the body
mstore(0x40, add(add(ptr, _footprint), 0x20)) ret := ptr
mstore(0x40, add(add(ptr, _footprint), 0x20)) ret := ptr
12,230
0
// IERC20Token - ERC20 interface /
contract IERC20Token { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
contract IERC20Token { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
77,171
184
// Prevent default sequence
if (collectionStartingIndex == 0) { collectionStartingIndex = collectionStartingIndex + 1; }
if (collectionStartingIndex == 0) { collectionStartingIndex = collectionStartingIndex + 1; }
694
56
// Sets `amount` as the allowance of `spender` over the `owner`s tokens. This is internal function is equivalent to `approve`, and can be used toe.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 {
function _approve(address owner, address spender, uint256 amount) internal virtual {
13,752
38
// ERC20 Optional Views
function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8);
function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8);
16,387
19
// Event emitted when a payment of eth is received by the Minter/sender The account making the payment/amount The amount of wei received
event PaymentReceived(address sender, uint256 amount);
event PaymentReceived(address sender, uint256 amount);
3,397
125
// Loop through each key and check whether the data point is stale.
uint256 i = 0; while (i < currencyKeys.length) {
uint256 i = 0; while (i < currencyKeys.length) {
35,643
120
// Withdraws the ether distributed to the sender./It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function withdrawDividend() public virtual override { _withdrawDividendOfUser(payable(msg.sender)); }
function withdrawDividend() public virtual override { _withdrawDividendOfUser(payable(msg.sender)); }
1,832
190
// subtract mint qty from giveAway allowance
giveAwayAllowance[subCollection][_msgSender()] = mintQty;
giveAwayAllowance[subCollection][_msgSender()] = mintQty;
14,450
25
// The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed
function quorumVotes() external pure returns (uint);
function quorumVotes() external pure returns (uint);
16,968
88
// Handle the receipt of ERC1363 tokens Any ERC1363 smart contract calls this function on the recipientafter a `transfer` or a `transferFrom`. This function MAY throw to revert and reject thetransfer. Return of other than the magic value MUST result in thetransaction being reverted.Note: the token contract address is always the message sender. operator address The address which called `transferAndCall` or `transferFromAndCall` function sender address The address which are token transferred from amount uint256 The amount of tokens transferred data bytes Additional data with no specified formatreturn `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` unless throwing /
function onTransferReceived(address operator, address sender, uint256 amount, bytes calldata data) external returns (bytes4);
function onTransferReceived(address operator, address sender, uint256 amount, bytes calldata data) external returns (bytes4);
33,470
198
// The manager has the privelege to add modules, remove, and set a new manager
address public manager;
address public manager;
6,999
286
// we have a non number
if (_hasNonNumber == false) _hasNonNumber = true;
if (_hasNonNumber == false) _hasNonNumber = true;
1,872
4
// Event emitted when access to functions is approved or unapproved Raised when setAnboto is called anboto indexed approved address to use set true if approved, otherwise false /
event SetAnboto(address indexed anboto, bool set);
event SetAnboto(address indexed anboto, bool set);
2,940
101
// grab time
uint256 _now = now;
uint256 _now = now;
16,095
57
// Lookup a customer address by project id /
function getCustomerByProject(uint _projectId) public view returns(address) { return projectRegistry[_projectId].customer; }
function getCustomerByProject(uint _projectId) public view returns(address) { return projectRegistry[_projectId].customer; }
16,158
307
// Removes a manager./manager The manager to remove.
function removeManager(address manager) public onlyOwner
function removeManager(address manager) public onlyOwner
3,678
54
// Right-align data
data = data >> (8 * (32 - len)); assembly {
data = data >> (8 * (32 - len)); assembly {
26,931