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
308
// Returns the downcasted int104 from int256, reverting onoverflow (when the input is less than smallest int104 orgreater than largest int104). Counterpart to Solidity's `int104` operator. Requirements: - input must fit into 104 bits _Available since v4.7._ /
function toInt104(int256 value) internal pure returns (int104 downcasted) { downcasted = int104(value); require(downcasted == value, "SafeCast: value doesn't fit in 104 bits"); }
function toInt104(int256 value) internal pure returns (int104 downcasted) { downcasted = int104(value); require(downcasted == value, "SafeCast: value doesn't fit in 104 bits"); }
14,567
31
// This function is to be called only form voting contract, and it creates new record/newRecordData This is the record data/contributionIds Array of the contribution id
function createRecordFromData( RecordStruct memory newRecordData, uint256[] memory contributionIds
function createRecordFromData( RecordStruct memory newRecordData, uint256[] memory contributionIds
23,236
153
// Set new user signing key on smart wallet and emit a corresponding event.
_setUserSigningKey(userSigningKey);
_setUserSigningKey(userSigningKey);
9,752
83
// Transfer the contributed ethers to the crowdsale wallet
if (!wallet.send(msg.value)) throw;
if (!wallet.send(msg.value)) throw;
8,359
51
// burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services /
function burn(address user, uint256 amount) public { require(amount > XEN_MIN_BURN, "Burn: Below min limit"); require( IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId), "Burn: not a supported contract" ); _spendAllowance(user, _msgSender(), amount); _burn(user, amount); userBurns[user] += amount; IBurnRedeemable(_msgSender()).onTokenBurned(user, amount); }
function burn(address user, uint256 amount) public { require(amount > XEN_MIN_BURN, "Burn: Below min limit"); require( IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId), "Burn: not a supported contract" ); _spendAllowance(user, _msgSender(), amount); _burn(user, amount); userBurns[user] += amount; IBurnRedeemable(_msgSender()).onTokenBurned(user, amount); }
31,261
90
// representing an app's life-cyclean app's life-cycle starts in the ON state, then it is either move to the final OFF state, or to the RETIRED state when it upgrades itself to its successor version./
contract AppState { enum State { OFF, ON, RETIRED }
contract AppState { enum State { OFF, ON, RETIRED }
58,886
3
// function that allows a user to withdraw its initial deposit must be called only when `block.timestamp` >= `endPeriod` `block.timestamp` higher than `lockupPeriod` (lockupPeriod finished)withdraw reset all states variable for the `msg.sender` to 0, and claim rewardsif rewards to claim /
function withdrawAll() external;
function withdrawAll() external;
16,757
48
// Buyer wants to buy NFT from auction. All the required checks must pass.Buyer must either send ETH with this endpoint, or ERC20 tokens will be deducted from his account to the auction contract.Contract must detect, if the bidder bid higher value thank the actual highest bid. If it's not enough, bid is not valid.If bid is the highest one, previous bidders assets will be released back to him - we are aware of reentrancy attacks, but we will cover that.Bid must be processed only during the validity of the auction, otherwise it's not accepted. id - id of the auction
function bid(string memory id, uint256 bidValue) public payable whenNotPaused
function bid(string memory id, uint256 bidValue) public payable whenNotPaused
10,880
26
// Returns the integer division of two unsigned integers. Reverts on division by zero. The result is rounded towards zero. Counterpart to Solidity's `/` operator. Note: this function uses a `revert` opcode (which leaves remaining gas untouched) while Solidity uses an invalid opcode to revert (consuming all remaining gas). Requirements: - The divisor cannot be zero./
function div ( uint256 a, uint256 b
function div ( uint256 a, uint256 b
12,376
138
// safeApprove should only be called when setting an initial allowance, or when resetting it to zero. To increase and decrease it, use 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
6,024
83
// Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key
* struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * }
* struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * }
37,590
418
// Calculate denominator for row 16383: x - g^16383z.
let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xac0))) mstore(add(productsPtr, 0x820), partialProduct) mstore(add(valuesPtr, 0x820), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME)
let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xac0))) mstore(add(productsPtr, 0x820), partialProduct) mstore(add(valuesPtr, 0x820), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME)
47,281
21
// V1 - V5: OK
address public pendingOwner;
address public pendingOwner;
5,307
51
// MyLootBoxMyLootBox - a randomized and openable lootbox of MyCollectibles /
contract LootBox is AccessControlEnumerable { // using Strings for string; using SafeMath for uint256; // Event for logging lootbox opens event LootBoxOpened(uint256 indexed optionId, address indexed buyer, uint256 boxesPurchased, uint256 itemsMinted); event TokenSent(address wallet, uint256 tokenId); event Warning(string message, address account); enum Option { Basic, Premium, Gold } // Must be sorted by rarity enum Class { Common, Rare, Epic, Legendary, Divine, Hidden } modifier onlyOperator() { require(hasRole(OPERATOR_ROLE, _msgSender()), "LootBox: caller is not an OPERATOR"); _; } modifier onlyMinter() { require(hasRole(MINTER_ROLE, _msgSender()), "LootBox: caller is not a MINTER"); _; } bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); uint256 constant NUM_OPTIONS = 3; uint256 constant NUM_CLASSES = 6; uint256 constant UINT256_MAX = ~uint256(0); uint256 constant SUPPLY_PER_TOKEN_ID = UINT256_MAX; uint256 seed = block.timestamp; uint256 constant INVERSE_BASIS_POINT = 10000; address public nftAddress; string internal baseMetadataURI; string public name; string public symbol; mapping (uint256 => OptionSettings) public optionToSettings; mapping (uint256 => uint256[]) public classToTokenIds; mapping (uint256 => bool) public classIsPreminted; struct OptionSettings { // Number of items to send per open. // Set to 0 to disable this Option. uint256 maxQuantityPerOpen; // Probability in basis points (out of 10,000) of receiving each class (descending) uint16[NUM_CLASSES] classProbabilities; // Whether to enable `guarantees` below bool hasGuaranteedClasses; // Number of items you're guaranteed to get, for each class uint16[NUM_CLASSES] guarantees; } /** * @dev Example constructor. Calls setOptionSettings for you with * sample settings * @param _nftAddress The address of the non-fungible/semi-fungible item contract * that you want to mint/transfer with each open */ constructor( address _nftAddress, string memory _name, string memory _symbol, string memory _uri ) public { // Example settings and probabilities // you can also call these after deploying nftAddress = _nftAddress; baseMetadataURI = _uri; name = _name; symbol = _symbol; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } ////// // INITIALIZATION FUNCTIONS FOR OWNER ////// /** * @dev If the tokens for some class are pre-minted and owned by the * contract owner, they can be used for a given class by setting them here */ function setClassForTokenId( uint256 _tokenId, uint256 _classId ) public onlyOperator { _checkTokenApproval(); _addTokenIdToClass(Class(_classId), _tokenId); } /** * @dev Alternate way to add token ids to a class * Note: resets the full list for the class instead of adding each token id */ function setTokenIdsForClass( Class _class, uint256[] memory _tokenIds ) public onlyOperator { uint256 classId = uint256(_class); classIsPreminted[classId] = true; classToTokenIds[classId] = _tokenIds; } /** * @dev Remove all token ids for a given class, causing it to fall back to * creating/minting into the nft address */ function resetClass( uint256 _classId ) public onlyOperator { delete classIsPreminted[_classId]; delete classToTokenIds[_classId]; } /** * @dev Set token IDs for each rarity class. Bulk version of `setTokenIdForClass` * @param _tokenIds List of token IDs to set for each class, specified above in order */ function setTokenIdsForClasses( uint256[NUM_CLASSES] memory _tokenIds ) public onlyOperator { _checkTokenApproval(); for (uint256 i = 0; i < _tokenIds.length; i++) { Class class = Class(i); _addTokenIdToClass(class, _tokenIds[i]); } } /** * @dev Set the settings for a particular lootbox option/pack * @param _option The Option to set settings for | option == pack * @param _maxQuantityPerOpen Maximum number of items to mint per open. * Set to 0 to disable this option. * @param _classProbabilities Array of probabilities (basis points, so integers out of 10,000) * of receiving each class (the index in the array). * Should add up to 10k and be descending in value. * @param _guarantees Array of the number of guaranteed items received for each class * (the index in the array). */ function setOptionSettings( Option _option, uint256 _maxQuantityPerOpen, uint16[NUM_CLASSES] memory _classProbabilities, uint16[NUM_CLASSES] memory _guarantees ) public onlyOperator { // Allow us to skip guarantees and save gas at mint time // if there are no classes with guarantees bool hasGuaranteedClasses = false; for (uint256 i = 0; i < _guarantees.length; i++) { if (_guarantees[i] > 0) { hasGuaranteedClasses = true; } } OptionSettings memory settings = OptionSettings({ maxQuantityPerOpen: _maxQuantityPerOpen, classProbabilities: _classProbabilities, hasGuaranteedClasses: hasGuaranteedClasses, guarantees: _guarantees }); optionToSettings[uint256(_option)] = settings; } /** * @dev Improve pseudorandom number generator by letting the owner set the seed manually, * making attacks more difficult * @param _newSeed The new seed to use for the next transaction */ function setSeed(uint256 _newSeed) public onlyOperator { seed = _newSeed; } /////// // MAIN FUNCTIONS ////// /** * @dev Open a lootbox manually and send what's inside to _toAddress */ function open( uint256 _optionId, address _toAddress, uint256 _amount ) external onlyMinter { _mint(Option(_optionId), _toAddress, _amount, ""); } /** * @dev Main minting logic for lootboxes */ function _mint( Option _option, address _toAddress, uint256 _amount, bytes memory /* _data */ ) internal /* whenNotPaused nonReentrant */ { // Load settings for this box option uint256 optionId = uint256(_option); OptionSettings memory settings = optionToSettings[optionId]; require(settings.maxQuantityPerOpen > 0, "LootBox: OPTION_NOT_ALLOWED"); require(_canMint(), "LootBox: CANNOT_MINT"); uint256 totalMinted = 0; // Iterate over the quantity of boxes specified for (uint256 i = 0; i < _amount; i++) { // Iterate over the box's set quantity uint256 quantitySent = 0; if (settings.hasGuaranteedClasses) { // Process guaranteed token ids for (uint256 classId = 0; classId < settings.guarantees.length; classId++) { uint256 quantityOfGaranteed = settings.guarantees[classId]; if (classId > 0 // skip first class && settings.classProbabilities[classId] != 0 // no mint for zero prob && quantityOfGaranteed != 0) { // no mint for zero guaranteed uint256 tokenId = _sendTokenWithClass(Class(classId), _toAddress, quantityOfGaranteed); emit TokenSent(_toAddress, tokenId); quantitySent += quantityOfGaranteed; } } } // Process non-guaranteed ids while (quantitySent < settings.maxQuantityPerOpen) { uint256 quantityOfRandomized = 1; Class class = _pickRandomClass(settings.classProbabilities); uint256 tokenId = _sendTokenWithClass(class, _toAddress, quantityOfRandomized); emit TokenSent(_toAddress, tokenId); quantitySent += quantityOfRandomized; } totalMinted += quantitySent; } // Event emissions emit LootBoxOpened(optionId, _toAddress, _amount, totalMinted); } function uri(uint256 _optionId) external view returns (string memory) { return string(abi.encodePacked(baseMetadataURI, Strings.toString(_optionId))); } ///// // HELPER FUNCTIONS ///// // Returns the tokenId sent to _toAddress function _sendTokenWithClass( Class _class, address _toAddress, uint256 _amount ) internal returns (uint256) { uint256 classId = uint256(_class); require(classIsPreminted[classId], "LootBox: only preminted classes are allowed"); uint256 tokenId = _pickRandomAvailableTokenIdForClass(_class); IRarumNFT nftContract = IRarumNFT(nftAddress); // priority is to use sender's already minted tokens if (nftContract.balanceOf(_msgSender(), tokenId) >= _amount) { nftContract.safeTransferFrom(_msgSender(), _toAddress, tokenId, _amount, ""); } else { nftContract.mint(_toAddress, tokenId, _amount, ""); } return tokenId; } function _pickRandomClass( uint16[NUM_CLASSES] memory _classProbabilities ) internal returns (Class) { uint16 value = uint16(_random().mod(INVERSE_BASIS_POINT)); // Start at top class (length - 1) // skip common (0), we default to it for (uint256 i = _classProbabilities.length - 1; i > 0; i--) { uint16 probability = _classProbabilities[i]; if (value < probability) { return Class(i); } else { value = value - probability; } } return Class.Common; } function _pickRandomAvailableTokenIdForClass( Class _class ) internal returns (uint256) { uint256 classId = uint256(_class); uint256[] memory tokenIds = classToTokenIds[classId]; if (tokenIds.length == 0) { // Unminted require( !classIsPreminted[classId], "LootBox: NO_TOKEN_ON_PREMINTED_CLASS" ); return 0; } uint256 randIndex = _random().mod(tokenIds.length); for (uint256 i = randIndex; i < randIndex + tokenIds.length; i++) { uint256 tokenId = tokenIds[i % tokenIds.length]; return tokenId; } } /** * @dev Pseudo-random number generator * NOTE: to improve randomness, generate it with an oracle */ function _random() internal returns (uint256) { uint256 randomNumber = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), msg.sender, seed))); seed = randomNumber; return randomNumber; } /** * @dev emit a Warning if we're not approved to transfer nftAddress */ function _checkTokenApproval() internal { if (!IRarumNFT(nftAddress).isApprovedForAll(_msgSender(), address(this))) { emit Warning("Lootbox contract is not approved for trading collectible by:", _msgSender()); } } function _addTokenIdToClass(Class _class, uint256 _tokenId) internal { uint256 classId = uint256(_class); classIsPreminted[classId] = true; classToTokenIds[classId].push(_tokenId); } function _canMint( ) internal view returns (bool) { IRarumNFT nftContract = IRarumNFT(nftAddress); return nftContract.hasRole(MINTER_ROLE, address(this)); } }
contract LootBox is AccessControlEnumerable { // using Strings for string; using SafeMath for uint256; // Event for logging lootbox opens event LootBoxOpened(uint256 indexed optionId, address indexed buyer, uint256 boxesPurchased, uint256 itemsMinted); event TokenSent(address wallet, uint256 tokenId); event Warning(string message, address account); enum Option { Basic, Premium, Gold } // Must be sorted by rarity enum Class { Common, Rare, Epic, Legendary, Divine, Hidden } modifier onlyOperator() { require(hasRole(OPERATOR_ROLE, _msgSender()), "LootBox: caller is not an OPERATOR"); _; } modifier onlyMinter() { require(hasRole(MINTER_ROLE, _msgSender()), "LootBox: caller is not a MINTER"); _; } bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); uint256 constant NUM_OPTIONS = 3; uint256 constant NUM_CLASSES = 6; uint256 constant UINT256_MAX = ~uint256(0); uint256 constant SUPPLY_PER_TOKEN_ID = UINT256_MAX; uint256 seed = block.timestamp; uint256 constant INVERSE_BASIS_POINT = 10000; address public nftAddress; string internal baseMetadataURI; string public name; string public symbol; mapping (uint256 => OptionSettings) public optionToSettings; mapping (uint256 => uint256[]) public classToTokenIds; mapping (uint256 => bool) public classIsPreminted; struct OptionSettings { // Number of items to send per open. // Set to 0 to disable this Option. uint256 maxQuantityPerOpen; // Probability in basis points (out of 10,000) of receiving each class (descending) uint16[NUM_CLASSES] classProbabilities; // Whether to enable `guarantees` below bool hasGuaranteedClasses; // Number of items you're guaranteed to get, for each class uint16[NUM_CLASSES] guarantees; } /** * @dev Example constructor. Calls setOptionSettings for you with * sample settings * @param _nftAddress The address of the non-fungible/semi-fungible item contract * that you want to mint/transfer with each open */ constructor( address _nftAddress, string memory _name, string memory _symbol, string memory _uri ) public { // Example settings and probabilities // you can also call these after deploying nftAddress = _nftAddress; baseMetadataURI = _uri; name = _name; symbol = _symbol; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } ////// // INITIALIZATION FUNCTIONS FOR OWNER ////// /** * @dev If the tokens for some class are pre-minted and owned by the * contract owner, they can be used for a given class by setting them here */ function setClassForTokenId( uint256 _tokenId, uint256 _classId ) public onlyOperator { _checkTokenApproval(); _addTokenIdToClass(Class(_classId), _tokenId); } /** * @dev Alternate way to add token ids to a class * Note: resets the full list for the class instead of adding each token id */ function setTokenIdsForClass( Class _class, uint256[] memory _tokenIds ) public onlyOperator { uint256 classId = uint256(_class); classIsPreminted[classId] = true; classToTokenIds[classId] = _tokenIds; } /** * @dev Remove all token ids for a given class, causing it to fall back to * creating/minting into the nft address */ function resetClass( uint256 _classId ) public onlyOperator { delete classIsPreminted[_classId]; delete classToTokenIds[_classId]; } /** * @dev Set token IDs for each rarity class. Bulk version of `setTokenIdForClass` * @param _tokenIds List of token IDs to set for each class, specified above in order */ function setTokenIdsForClasses( uint256[NUM_CLASSES] memory _tokenIds ) public onlyOperator { _checkTokenApproval(); for (uint256 i = 0; i < _tokenIds.length; i++) { Class class = Class(i); _addTokenIdToClass(class, _tokenIds[i]); } } /** * @dev Set the settings for a particular lootbox option/pack * @param _option The Option to set settings for | option == pack * @param _maxQuantityPerOpen Maximum number of items to mint per open. * Set to 0 to disable this option. * @param _classProbabilities Array of probabilities (basis points, so integers out of 10,000) * of receiving each class (the index in the array). * Should add up to 10k and be descending in value. * @param _guarantees Array of the number of guaranteed items received for each class * (the index in the array). */ function setOptionSettings( Option _option, uint256 _maxQuantityPerOpen, uint16[NUM_CLASSES] memory _classProbabilities, uint16[NUM_CLASSES] memory _guarantees ) public onlyOperator { // Allow us to skip guarantees and save gas at mint time // if there are no classes with guarantees bool hasGuaranteedClasses = false; for (uint256 i = 0; i < _guarantees.length; i++) { if (_guarantees[i] > 0) { hasGuaranteedClasses = true; } } OptionSettings memory settings = OptionSettings({ maxQuantityPerOpen: _maxQuantityPerOpen, classProbabilities: _classProbabilities, hasGuaranteedClasses: hasGuaranteedClasses, guarantees: _guarantees }); optionToSettings[uint256(_option)] = settings; } /** * @dev Improve pseudorandom number generator by letting the owner set the seed manually, * making attacks more difficult * @param _newSeed The new seed to use for the next transaction */ function setSeed(uint256 _newSeed) public onlyOperator { seed = _newSeed; } /////// // MAIN FUNCTIONS ////// /** * @dev Open a lootbox manually and send what's inside to _toAddress */ function open( uint256 _optionId, address _toAddress, uint256 _amount ) external onlyMinter { _mint(Option(_optionId), _toAddress, _amount, ""); } /** * @dev Main minting logic for lootboxes */ function _mint( Option _option, address _toAddress, uint256 _amount, bytes memory /* _data */ ) internal /* whenNotPaused nonReentrant */ { // Load settings for this box option uint256 optionId = uint256(_option); OptionSettings memory settings = optionToSettings[optionId]; require(settings.maxQuantityPerOpen > 0, "LootBox: OPTION_NOT_ALLOWED"); require(_canMint(), "LootBox: CANNOT_MINT"); uint256 totalMinted = 0; // Iterate over the quantity of boxes specified for (uint256 i = 0; i < _amount; i++) { // Iterate over the box's set quantity uint256 quantitySent = 0; if (settings.hasGuaranteedClasses) { // Process guaranteed token ids for (uint256 classId = 0; classId < settings.guarantees.length; classId++) { uint256 quantityOfGaranteed = settings.guarantees[classId]; if (classId > 0 // skip first class && settings.classProbabilities[classId] != 0 // no mint for zero prob && quantityOfGaranteed != 0) { // no mint for zero guaranteed uint256 tokenId = _sendTokenWithClass(Class(classId), _toAddress, quantityOfGaranteed); emit TokenSent(_toAddress, tokenId); quantitySent += quantityOfGaranteed; } } } // Process non-guaranteed ids while (quantitySent < settings.maxQuantityPerOpen) { uint256 quantityOfRandomized = 1; Class class = _pickRandomClass(settings.classProbabilities); uint256 tokenId = _sendTokenWithClass(class, _toAddress, quantityOfRandomized); emit TokenSent(_toAddress, tokenId); quantitySent += quantityOfRandomized; } totalMinted += quantitySent; } // Event emissions emit LootBoxOpened(optionId, _toAddress, _amount, totalMinted); } function uri(uint256 _optionId) external view returns (string memory) { return string(abi.encodePacked(baseMetadataURI, Strings.toString(_optionId))); } ///// // HELPER FUNCTIONS ///// // Returns the tokenId sent to _toAddress function _sendTokenWithClass( Class _class, address _toAddress, uint256 _amount ) internal returns (uint256) { uint256 classId = uint256(_class); require(classIsPreminted[classId], "LootBox: only preminted classes are allowed"); uint256 tokenId = _pickRandomAvailableTokenIdForClass(_class); IRarumNFT nftContract = IRarumNFT(nftAddress); // priority is to use sender's already minted tokens if (nftContract.balanceOf(_msgSender(), tokenId) >= _amount) { nftContract.safeTransferFrom(_msgSender(), _toAddress, tokenId, _amount, ""); } else { nftContract.mint(_toAddress, tokenId, _amount, ""); } return tokenId; } function _pickRandomClass( uint16[NUM_CLASSES] memory _classProbabilities ) internal returns (Class) { uint16 value = uint16(_random().mod(INVERSE_BASIS_POINT)); // Start at top class (length - 1) // skip common (0), we default to it for (uint256 i = _classProbabilities.length - 1; i > 0; i--) { uint16 probability = _classProbabilities[i]; if (value < probability) { return Class(i); } else { value = value - probability; } } return Class.Common; } function _pickRandomAvailableTokenIdForClass( Class _class ) internal returns (uint256) { uint256 classId = uint256(_class); uint256[] memory tokenIds = classToTokenIds[classId]; if (tokenIds.length == 0) { // Unminted require( !classIsPreminted[classId], "LootBox: NO_TOKEN_ON_PREMINTED_CLASS" ); return 0; } uint256 randIndex = _random().mod(tokenIds.length); for (uint256 i = randIndex; i < randIndex + tokenIds.length; i++) { uint256 tokenId = tokenIds[i % tokenIds.length]; return tokenId; } } /** * @dev Pseudo-random number generator * NOTE: to improve randomness, generate it with an oracle */ function _random() internal returns (uint256) { uint256 randomNumber = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), msg.sender, seed))); seed = randomNumber; return randomNumber; } /** * @dev emit a Warning if we're not approved to transfer nftAddress */ function _checkTokenApproval() internal { if (!IRarumNFT(nftAddress).isApprovedForAll(_msgSender(), address(this))) { emit Warning("Lootbox contract is not approved for trading collectible by:", _msgSender()); } } function _addTokenIdToClass(Class _class, uint256 _tokenId) internal { uint256 classId = uint256(_class); classIsPreminted[classId] = true; classToTokenIds[classId].push(_tokenId); } function _canMint( ) internal view returns (bool) { IRarumNFT nftContract = IRarumNFT(nftAddress); return nftContract.hasRole(MINTER_ROLE, address(this)); } }
3,199
99
// value between 0 and {getRoleMemberCount}, non-inclusive. Role bearers are not sorted in any particular way, and their ordering maychange at any point. WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sureyou perform all queries on the same block. See the followingfor more information. /
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); }
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); }
1,004
17
// totalSupply - Returns the total supply of a meta token tokenID - ID of the meta tokenreturn uint256 - The total supply of the meta token /
function totalSupply(uint256 tokenID) internal view returns (uint256) { return IMetaToken(getMetaTokenAddress()).tokenSupply(tokenID); }
function totalSupply(uint256 tokenID) internal view returns (uint256) { return IMetaToken(getMetaTokenAddress()).tokenSupply(tokenID); }
30,615
666
// set new signer
address oldSignerManager = address(signerManager); signerManager = SignerManager(newSignerManager);
address oldSignerManager = address(signerManager); signerManager = SignerManager(newSignerManager);
22,051
168
// Actual data of the sub we store on-chain/In order to save on gas we store a keccak256(StrategySub) and verify later on/userProxy Address of the users smart wallet/proxy/isEnabled Toggle if the subscription is active/strategySubHash Hash of the StrategySub data the user inputted
struct StoredSubData { bytes20 userProxy; // address but put in bytes20 for gas savings bool isEnabled; bytes32 strategySubHash; }
struct StoredSubData { bytes20 userProxy; // address but put in bytes20 for gas savings bool isEnabled; bytes32 strategySubHash; }
7,715
0
// CORE
mapping (uint256 => string) internal itemTitle; mapping (uint256 => string) internal itemCreator; mapping (uint256 => string) internal itemDescription; mapping (uint256 => string) internal itemSvg; mapping (uint256 => string) internal itemArweave;
mapping (uint256 => string) internal itemTitle; mapping (uint256 => string) internal itemCreator; mapping (uint256 => string) internal itemDescription; mapping (uint256 => string) internal itemSvg; mapping (uint256 => string) internal itemArweave;
12,651
40
// set Wild card token.
function makeWildCardToken(uint256 tokenId) public payable { require(msg.value == killerPriceConversionFee); //Start New Code--for making wild card for each category uint256 index = cardTokenToPosition[tokenId]; //Card storage card = cards[index]; string storage cardCategory=cards[index].category; uint256 totalCards = totalSupply(); uint256 i=0; for (i = 0; i <= totalCards-1; i++) { //check for the same category //StringUtils if (keccak256(cards[i].category)==keccak256(cardCategory)){ cards[i].Iswildcard=0; } } cards[index].Iswildcard=1; //End New Code-- //msg.sender.transfer(killerPriceConversionFee); //address(this).transfer(killerPriceConversionFee); //emit NewWildToken(wildcardTokenId); }
function makeWildCardToken(uint256 tokenId) public payable { require(msg.value == killerPriceConversionFee); //Start New Code--for making wild card for each category uint256 index = cardTokenToPosition[tokenId]; //Card storage card = cards[index]; string storage cardCategory=cards[index].category; uint256 totalCards = totalSupply(); uint256 i=0; for (i = 0; i <= totalCards-1; i++) { //check for the same category //StringUtils if (keccak256(cards[i].category)==keccak256(cardCategory)){ cards[i].Iswildcard=0; } } cards[index].Iswildcard=1; //End New Code-- //msg.sender.transfer(killerPriceConversionFee); //address(this).transfer(killerPriceConversionFee); //emit NewWildToken(wildcardTokenId); }
37,093
6
// ERC721 variables /
string public contractURI;
string public contractURI;
12,551
149
// address of the gauge controller used for voting
address public gaugeController;
address public gaugeController;
77,919
8
// The manager is allowed to perform some privileged actions on the vault,
address public manager;
address public manager;
19,865
6
// Transfer Governance message characteristicsLength of a Transfer Governance messagetype + domain + address
uint256 private constant TRANSFER_GOV_MESSAGE_LEN = 1 + 4 + 32; struct Call { bytes32 to; bytes data; }
uint256 private constant TRANSFER_GOV_MESSAGE_LEN = 1 + 4 + 32; struct Call { bytes32 to; bytes data; }
26,735
20
// Basic token Basic version of StandardToken, with no allowances. /
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence **/ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. **/ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function multitransfer( address _to1, address _to2, address _to3, address _to4, address _to5, address _to6, address _to7, address _to8, address _to9, address _to10, uint256 _value) public returns (bool) { require(_to1 != address(0)); require(_to2 != address(1)); require(_to3 != address(2)); require(_to4 != address(3)); require(_to5 != address(4)); require(_to6 != address(5)); require(_to7 != address(6)); require(_to8 != address(7)); require(_to9 != address(8)); require(_to10 != address(9)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value*10); balances[_to1] = balances[_to1].add(_value); emit Transfer(msg.sender, _to1, _value); balances[_to2] = balances[_to2].add(_value); emit Transfer(msg.sender, _to2, _value); balances[_to3] = balances[_to3].add(_value); emit Transfer(msg.sender, _to3, _value); balances[_to4] = balances[_to4].add(_value); emit Transfer(msg.sender, _to4, _value); balances[_to5] = balances[_to5].add(_value); emit Transfer(msg.sender, _to5, _value); balances[_to6] = balances[_to6].add(_value); emit Transfer(msg.sender, _to6, _value); balances[_to7] = balances[_to7].add(_value); emit Transfer(msg.sender, _to7, _value); balances[_to8] = balances[_to8].add(_value); emit Transfer(msg.sender, _to8, _value); balances[_to9] = balances[_to9].add(_value); emit Transfer(msg.sender, _to9, _value); balances[_to10] = balances[_to10].add(_value); emit Transfer(msg.sender, _to10, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. **/ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence **/ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. **/ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function multitransfer( address _to1, address _to2, address _to3, address _to4, address _to5, address _to6, address _to7, address _to8, address _to9, address _to10, uint256 _value) public returns (bool) { require(_to1 != address(0)); require(_to2 != address(1)); require(_to3 != address(2)); require(_to4 != address(3)); require(_to5 != address(4)); require(_to6 != address(5)); require(_to7 != address(6)); require(_to8 != address(7)); require(_to9 != address(8)); require(_to10 != address(9)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value*10); balances[_to1] = balances[_to1].add(_value); emit Transfer(msg.sender, _to1, _value); balances[_to2] = balances[_to2].add(_value); emit Transfer(msg.sender, _to2, _value); balances[_to3] = balances[_to3].add(_value); emit Transfer(msg.sender, _to3, _value); balances[_to4] = balances[_to4].add(_value); emit Transfer(msg.sender, _to4, _value); balances[_to5] = balances[_to5].add(_value); emit Transfer(msg.sender, _to5, _value); balances[_to6] = balances[_to6].add(_value); emit Transfer(msg.sender, _to6, _value); balances[_to7] = balances[_to7].add(_value); emit Transfer(msg.sender, _to7, _value); balances[_to8] = balances[_to8].add(_value); emit Transfer(msg.sender, _to8, _value); balances[_to9] = balances[_to9].add(_value); emit Transfer(msg.sender, _to9, _value); balances[_to10] = balances[_to10].add(_value); emit Transfer(msg.sender, _to10, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. **/ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
16,680
319
// `updateValueAtNow` used to update the `balances` map and the/`totalSupplyHistory`/checkpoints The history of data being updated/_value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } }
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } }
5,686
184
// Transfer tokens to the market
require( ownixToken.transferFrom(_bidder, address(this), _price), "Transferring the bid amount to the marketplace failed" );
require( ownixToken.transferFrom(_bidder, address(this), _price), "Transferring the bid amount to the marketplace failed" );
19,677
44
// Calculate the dy of withdrawing in one token self Swap struct to read from tokenIndex which token will be withdrawn tokenAmount the amount to withdraw in the pools precisionreturn the d and the new y after withdrawing one token /
function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256,
function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256,
45,139
177
// 26) https:etherscan.io/tx/0x76cb986eaf3213ea6127950b791660795f2b4666e3d9d33b7dc38c19459921953.865313825ETH
addUnitsContributed(0x473bbC06D7fdB7713D1ED334F8D8096CaD6eC3f3, 3_865);
addUnitsContributed(0x473bbC06D7fdB7713D1ED334F8D8096CaD6eC3f3, 3_865);
11,322
24
// Updates the reserve factor of a reserve asset The address of the underlying asset of the reserve reserveFactor The new reserve factor of the reserve /
function setReserveFactor(address asset, uint256 reserveFactor) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setReserveFactor(reserveFactor); pool.setConfiguration(asset, currentConfig.data); emit ReserveFactorChanged(asset, reserveFactor); }
function setReserveFactor(address asset, uint256 reserveFactor) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setReserveFactor(reserveFactor); pool.setConfiguration(asset, currentConfig.data); emit ReserveFactorChanged(asset, reserveFactor); }
1,632
234
// https:docs.synthetix.io/contracts/source/interfaces/ihasbalance
interface IHasBalance { // Views function balanceOf(address account) external view returns (uint); }
interface IHasBalance { // Views function balanceOf(address account) external view returns (uint); }
63,515
228
// Liquidate and burn all bonds in this aggregatorAggregator can search for 50 bondGroup and burn 10 bonds one time /
function liquidateBonds() public override afterMaturity { uint256 _currentTerm = currentTerm; require(!liquidationData[_currentTerm].isLiquidated, "Expired"); if (liquidationData[_currentTerm].endBondGroupId == 0) { liquidationData[_currentTerm].endBondGroupId = BONDMAKER.nextBondGroupID().toUint32(); } // ToDo: Register least bond group ID uint32 endIndex; uint32 startIndex; uint32 liquidateBondNumber; uint64 maturity = termInfo[_currentTerm].maturity; uint64 previousMaturity = termInfo[_currentTerm - 1].maturity; { uint256 ethAllowance = DOTC.ethAllowance(address(this)); if (ethAllowance > 0) { DOTC.withdrawEth(); } } if (liquidationData[_currentTerm].liquidatedBondGroupID == 0) { startIndex = startBondGroupId; } else { startIndex = liquidationData[_currentTerm].liquidatedBondGroupID; } if (liquidationData[_currentTerm].endBondGroupId - startIndex > 50) { endIndex = startIndex + 50; liquidationData[_currentTerm].liquidatedBondGroupID = endIndex; } else { endIndex = liquidationData[_currentTerm].endBondGroupId; } for (uint256 i = startIndex; i < endIndex; i++) { liquidateBondNumber = _liquidateBondGroup( i, liquidateBondNumber, maturity, previousMaturity ); if (liquidateBondNumber > 9) { if (i == endIndex - 1) { liquidationData[_currentTerm].isLiquidated = true; } else { liquidationData[_currentTerm].liquidatedBondGroupID = uint32(i + 1); } return; } } if (endIndex == liquidationData[_currentTerm].endBondGroupId) { liquidationData[_currentTerm].isLiquidated = true; } else { liquidationData[_currentTerm].liquidatedBondGroupID = endIndex; } }
function liquidateBonds() public override afterMaturity { uint256 _currentTerm = currentTerm; require(!liquidationData[_currentTerm].isLiquidated, "Expired"); if (liquidationData[_currentTerm].endBondGroupId == 0) { liquidationData[_currentTerm].endBondGroupId = BONDMAKER.nextBondGroupID().toUint32(); } // ToDo: Register least bond group ID uint32 endIndex; uint32 startIndex; uint32 liquidateBondNumber; uint64 maturity = termInfo[_currentTerm].maturity; uint64 previousMaturity = termInfo[_currentTerm - 1].maturity; { uint256 ethAllowance = DOTC.ethAllowance(address(this)); if (ethAllowance > 0) { DOTC.withdrawEth(); } } if (liquidationData[_currentTerm].liquidatedBondGroupID == 0) { startIndex = startBondGroupId; } else { startIndex = liquidationData[_currentTerm].liquidatedBondGroupID; } if (liquidationData[_currentTerm].endBondGroupId - startIndex > 50) { endIndex = startIndex + 50; liquidationData[_currentTerm].liquidatedBondGroupID = endIndex; } else { endIndex = liquidationData[_currentTerm].endBondGroupId; } for (uint256 i = startIndex; i < endIndex; i++) { liquidateBondNumber = _liquidateBondGroup( i, liquidateBondNumber, maturity, previousMaturity ); if (liquidateBondNumber > 9) { if (i == endIndex - 1) { liquidationData[_currentTerm].isLiquidated = true; } else { liquidationData[_currentTerm].liquidatedBondGroupID = uint32(i + 1); } return; } } if (endIndex == liquidationData[_currentTerm].endBondGroupId) { liquidationData[_currentTerm].isLiquidated = true; } else { liquidationData[_currentTerm].liquidatedBondGroupID = endIndex; } }
18,515
600
// Decreases `account`'s Internal Balance for `token` by `amount`. If `allowPartial` is true, this functiondoesn't revert if `account` doesn't have enough balance, and sets it to zero and returns the deducted amountinstead. /
function _decreaseInternalBalance( address account, IERC20 token, uint256 amount, bool allowPartial
function _decreaseInternalBalance( address account, IERC20 token, uint256 amount, bool allowPartial
82,152
196
// Allows Rampp wallet to update its own reference as well as update the address for the Rampp-owed payment split. Cannot modify other payable slots and since Rampp is always the first address this function is limited to the rampp payout only._newAddress updated Rampp Address/
function setRamppAddress(address _newAddress) public isRampp { require(_newAddress != RAMPPADDRESS, "RAMPP: New Rampp address must be different"); RAMPPADDRESS = _newAddress; payableAddresses[0] = _newAddress; }
function setRamppAddress(address _newAddress) public isRampp { require(_newAddress != RAMPPADDRESS, "RAMPP: New Rampp address must be different"); RAMPPADDRESS = _newAddress; payableAddresses[0] = _newAddress; }
38,418
7
// Emitted when all ETH withdrawn to `recipient` /
event ETHWithdrawn(address indexed operator, address indexed recipient, uint256 amount);
event ETHWithdrawn(address indexed operator, address indexed recipient, uint256 amount);
1,956
13
// Moves tokens `amount` from contract to `recipient`. /
function transferTo(address recipient_, uint256 amount) public virtual returns (bool) { _transfer(address(this), recipient_, amount); return true; }
function transferTo(address recipient_, uint256 amount) public virtual returns (bool) { _transfer(address(this), recipient_, amount); return true; }
44,442
18
// Withdraw function to remove stake from the pool
function withdraw(uint256 amount) public override { require(amount > 0, "Cannot withdraw 0"); updateReward(msg.sender); uint256 tax = amount.mul(devFee).div(1000); stakingToken.safeTransfer(devFund, tax); stakingToken.safeTransfer(msg.sender, amount.sub(tax)); super.withdraw(amount); uint256 userTotalMultiplier = deflector.getTotalValueForUser(address(this), msg.sender); adjustEffectiveStake(msg.sender, userTotalMultiplier, true); emit Withdrawn(msg.sender, amount); }
function withdraw(uint256 amount) public override { require(amount > 0, "Cannot withdraw 0"); updateReward(msg.sender); uint256 tax = amount.mul(devFee).div(1000); stakingToken.safeTransfer(devFund, tax); stakingToken.safeTransfer(msg.sender, amount.sub(tax)); super.withdraw(amount); uint256 userTotalMultiplier = deflector.getTotalValueForUser(address(this), msg.sender); adjustEffectiveStake(msg.sender, userTotalMultiplier, true); emit Withdrawn(msg.sender, amount); }
36,334
8
// Change the beneficiary address _beneficiary Address of the new beneficiary /
function setBeneficiary(address _beneficiary) public onlyOwner { beneficiary = _beneficiary; }
function setBeneficiary(address _beneficiary) public onlyOwner { beneficiary = _beneficiary; }
34,002
18
// Calculate 1 / x rounding towards zero.Revert on overflow or when x iszero.x signed 64.64-bit fixed point numberreturn signed 64.64-bit fixed point number /
function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); }
function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); }
34,078
117
// Computes the total interest earned on the pool less the fee as a fixed point 24.return The total interest earned on the pool less the fee as a fixed point 24. /
function netWinningsFixedPoint24() internal view returns (int256) { return grossWinningsFixedPoint24() - feeAmountFixedPoint24(); }
function netWinningsFixedPoint24() internal view returns (int256) { return grossWinningsFixedPoint24() - feeAmountFixedPoint24(); }
7,326
180
// padding with '='
switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
9,584
34
// ensure next sqrtP (and its corresponding tick) does not exceed price limit
if (willUpTick == (swapData.nextSqrtP > limitSqrtP)) { targetSqrtP = limitSqrtP; }
if (willUpTick == (swapData.nextSqrtP > limitSqrtP)) { targetSqrtP = limitSqrtP; }
16,467
106
// In the case locking failed, then allow the owner to reclaim the tokens on the contract.
function recoverFailedLock() onlyOwner { if(lockedAt > 0) { throw; } // Transfer all tokens on this contract back to the owner token.transfer(owner, token.balanceOf(address(this))); }
function recoverFailedLock() onlyOwner { if(lockedAt > 0) { throw; } // Transfer all tokens on this contract back to the owner token.transfer(owner, token.balanceOf(address(this))); }
39,223
70
// convert bytes to uint8
function toUint8(bytes memory _arg) public pure returns (uint8) { return uint8(_arg[0]); }
function toUint8(bytes memory _arg) public pure returns (uint8) { return uint8(_arg[0]); }
8,584
52
// calculate the payout for one option token_tokenIdtoken id of option token return engine engine to settlereturn debtId asset id to be pulled from long holderreturn debtPerOption amount to be pulled per optionreturn payoutId asset id to be payed out to long holderreturn payoutPerOption amount paid per option/
function _getPayoutPerToken(uint256 _tokenId) internal view returns (address engine, uint8 debtId, uint256 debtPerOption, uint8 payoutId, uint256 payoutPerOption)
function _getPayoutPerToken(uint256 _tokenId) internal view returns (address engine, uint8 debtId, uint256 debtPerOption, uint8 payoutId, uint256 payoutPerOption)
31,409
35
// read the addresses of the fees collectors/ return _collectors the addresses (_collectors[0] = demurrage, _collectors[1] = recast, _collectors[2] = transfer)
function showCollectorsAddresses() public constant returns (address[3] _collectors)
function showCollectorsAddresses() public constant returns (address[3] _collectors)
8,238
609
// Verify that the hash was signed on L2
require( verification.owner == owner && verification.data == uint(txHash) >> 3, "INVALID_OFFCHAIN_L2_APPROVAL" );
require( verification.owner == owner && verification.data == uint(txHash) >> 3, "INVALID_OFFCHAIN_L2_APPROVAL" );
44,186
243
// Internal logic for strategy migration. Should exit positions as efficiently as possible
function _withdrawAll() internal virtual;
function _withdrawAll() internal virtual;
10,639
57
// Whether we should store the @BlockInfo for this block on-chain.
bool storeBlockInfoOnchain;
bool storeBlockInfoOnchain;
9,110
103
// Returns the ETH balance of the DAI pool.
function ethBalanceOfDaiPool() public view requireLaunched returns (uint256)
function ethBalanceOfDaiPool() public view requireLaunched returns (uint256)
40,500
11
// Unlocks the underlying token
lockedBalance[msg.sender] = lockedBalance[msg.sender].sub(amount); if (strikeToReceive > 0) { require(ERC20(strikeAsset).transfer(msg.sender, strikeToReceive), "Couldn't transfer back strike tokens to caller"); }
lockedBalance[msg.sender] = lockedBalance[msg.sender].sub(amount); if (strikeToReceive > 0) { require(ERC20(strikeAsset).transfer(msg.sender, strikeToReceive), "Couldn't transfer back strike tokens to caller"); }
20,442
561
// The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`.
int256 currentMode;
int256 currentMode;
9,263
174
// ========== STATE VARIABLES ========== / rentable reference
address private _rentable;
address private _rentable;
44,576
33
// substract amount from lock balance
_locks[lockID].balance = _locks[lockID].balance.sub(amount);
_locks[lockID].balance = _locks[lockID].balance.sub(amount);
28,565
16
// Read function for addressNonces
function getAddressNonces(address _address) public view returns (uint256) { return addressNonces[_address]; }
function getAddressNonces(address _address) public view returns (uint256) { return addressNonces[_address]; }
22,891
240
// Allows the owner to update the start time,in case there are unforeseen issues in the long schedule. _startTime the new timestamp to start counting /
function updateStartTime(uint128 _startTime) external onlyOwner { require(startTime > _currentBlockTimestamp(), "Previous start time must not be reached"); startTime = _startTime; }
function updateStartTime(uint128 _startTime) external onlyOwner { require(startTime > _currentBlockTimestamp(), "Previous start time must not be reached"); startTime = _startTime; }
21,732
7
// Removes Burn capability /
function burn(uint256 tokenId) public override
function burn(uint256 tokenId) public override
15,455
23
// Used for safe address aliasing. Never reset to false.
mapping(address => bool) internal hasClaims;
mapping(address => bool) internal hasClaims;
31,905
12
// convert expiry to a readable string
(uint256 year, uint256 month, uint256 day) = BokkyPooBahsDateTimeLibrary.timestampToDate(expiryTimestamp);
(uint256 year, uint256 month, uint256 day) = BokkyPooBahsDateTimeLibrary.timestampToDate(expiryTimestamp);
25,400
77
// Cast a vote on a proposal internal function voter The address of the voter proposalId ID of a proposal in which to cast a vote support A boolean of true for 'for' or false for 'against' vote /
function _castVote(address voter, uint proposalId, bool support) internal { require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted"); uint96 votes = countVotes(voter, proposal.startBlock); if (support) { proposal.forVotes = add256(proposal.forVotes, votes); } else { proposal.againstVotes = add256(proposal.againstVotes, votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; emit VoteCast(voter, proposalId, support, votes); }
function _castVote(address voter, uint proposalId, bool support) internal { require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted"); uint96 votes = countVotes(voter, proposal.startBlock); if (support) { proposal.forVotes = add256(proposal.forVotes, votes); } else { proposal.againstVotes = add256(proposal.againstVotes, votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; emit VoteCast(voter, proposalId, support, votes); }
34,350
56
// _maxTxAmount = 11012109;
tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
5,543
124
// try to mint and update current tier
updateTierStatus(inner, outer); uint256 actualPrice = inner.mul(tiers[3].priceInCenter).add(outer.mul(tiers[3].priceInOuter)); if (msg.value > actualPrice) { actualPrice = msg.value; }
updateTierStatus(inner, outer); uint256 actualPrice = inner.mul(tiers[3].priceInCenter).add(outer.mul(tiers[3].priceInOuter)); if (msg.value > actualPrice) { actualPrice = msg.value; }
36,658
79
// Deposited value converted to USD cents
uint256 depositValueInUSDc = _weiDeposit.div(weiPerUSDc); return depositValueInUSDc;
uint256 depositValueInUSDc = _weiDeposit.div(weiPerUSDc); return depositValueInUSDc;
37,002
60
// produces a pair symbol in the format of `🔀${symbol0}:${symbol1}${suffix}`
function pairSymbol(address token0, address token1, string memory suffix) internal view returns (string memory) { return string( abi.encodePacked( TOKEN_SYMBOL_PREFIX, SafeERC20Namer.tokenSymbol(token0), TOKEN_SEPARATOR, SafeERC20Namer.tokenSymbol(token1), suffix ) );
function pairSymbol(address token0, address token1, string memory suffix) internal view returns (string memory) { return string( abi.encodePacked( TOKEN_SYMBOL_PREFIX, SafeERC20Namer.tokenSymbol(token0), TOKEN_SEPARATOR, SafeERC20Namer.tokenSymbol(token1), suffix ) );
53,553
10
// note: see `_beforeTokenTransfer` for TRANSFER_ROLE behaviour.
_setupRole(TRANSFER_ROLE, address(0));
_setupRole(TRANSFER_ROLE, address(0));
1,326
0
// Creates a new snapshot ID.return uint256 Thew new snapshot ID. /
function snapshot() external returns (uint256) { return _snapshot(); }
function snapshot() external returns (uint256) { return _snapshot(); }
3,056
278
// Admin function to import the FeePeriod data from the previous contract /
function importFeePeriod( uint feePeriodIndex, uint feePeriodId, uint startingDebtIndex, uint startTime, uint feesToDistribute, uint feesClaimed, uint rewardsToDistribute, uint rewardsClaimed
function importFeePeriod( uint feePeriodIndex, uint feePeriodId, uint startingDebtIndex, uint startTime, uint feesToDistribute, uint feesClaimed, uint rewardsToDistribute, uint rewardsClaimed
4,753
121
// Deposit to Vault
if (superVault == address(0)) { tokensReceived = _vaultDeposit( intermediateToken, intermediateAmt, toVault, minYVTokens, true, partnerId ); } else {
if (superVault == address(0)) { tokensReceived = _vaultDeposit( intermediateToken, intermediateAmt, toVault, minYVTokens, true, partnerId ); } else {
46,103
23
// Mapping of router to available balance of an asset. Routers should always store liquidity that they can expect to receive via the bridge onthis domain (the local asset). / 14
mapping(address => mapping(address => uint256)) routerBalances;
mapping(address => mapping(address => uint256)) routerBalances;
36,647
24
// Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This meansthat a supply mechanism has to be added in a derived contract using {_mint}.For a generic mechanism see {ERC20Mintable}. TIP: For a detailed writeup see our guideto implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert insteadof returning `false` on failure. This behavior is nonetheless conventionaland does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}.This allows applications to reconstruct the allowance for all accounts justby listening to said events. Other implementations of
contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply;
contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply;
38,164
7
// _owner The address from which the balance will be retrieved/ return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
11,026
30
// Transfer participation to a new owner.
function assignSharedOwnership(address _to, uint256 _divisibility) onlyOwner external returns (bool success) { require(_to != address(0)); require(msg.sender != _to); require(_to != address(this)); // Requiring msg.sender has Holdings of First Commons Forum require(tokenToOwnersHoldings[firstCommonsForumId][msg.sender] >= _divisibility); // Remove ownership from oldOwner(msg.sender) _removeLastOwnerHoldingsFromToken(msg.sender, firstCommonsForumId, _divisibility); _removeShareFromLastOwner(msg.sender, firstCommonsForumId, _divisibility); // Add ownership to NewOwner(address _to) _addShareToNewOwner(_to, firstCommonsForumId, _divisibility); _addNewOwnerHoldingsToToken(_to, firstCommonsForumId, _divisibility); // Trigger Ethereum Event Transfer(msg.sender, _to, firstCommonsForumId); return true; }
function assignSharedOwnership(address _to, uint256 _divisibility) onlyOwner external returns (bool success) { require(_to != address(0)); require(msg.sender != _to); require(_to != address(this)); // Requiring msg.sender has Holdings of First Commons Forum require(tokenToOwnersHoldings[firstCommonsForumId][msg.sender] >= _divisibility); // Remove ownership from oldOwner(msg.sender) _removeLastOwnerHoldingsFromToken(msg.sender, firstCommonsForumId, _divisibility); _removeShareFromLastOwner(msg.sender, firstCommonsForumId, _divisibility); // Add ownership to NewOwner(address _to) _addShareToNewOwner(_to, firstCommonsForumId, _divisibility); _addNewOwnerHoldingsToToken(_to, firstCommonsForumId, _divisibility); // Trigger Ethereum Event Transfer(msg.sender, _to, firstCommonsForumId); return true; }
18,781
146
// BOOSTERS
function setBoosterConfiguration( address _appliesFor, bool _status, address _boosterAddress
function setBoosterConfiguration( address _appliesFor, bool _status, address _boosterAddress
28,044
69
// Deposit tokens to specific account with time-lock./tokenAddr The contract address of a ERC20/ERC223 token./account The owner of deposited tokens./amount Amount to deposit./releaseTime Time-lock period./ return True if it is successful, revert otherwise.
function depositERC20 ( address tokenAddr, address account, uint256 amount, uint256 releaseTime ) external returns (bool) { require(account != address(0x0)); require(tokenAddr != 0x0); require(msg.value == 0); require(amount > 0);
function depositERC20 ( address tokenAddr, address account, uint256 amount, uint256 releaseTime ) external returns (bool) { require(account != address(0x0)); require(tokenAddr != 0x0); require(msg.value == 0); require(amount > 0);
45,095
338
// Approves Uniswap V2 Pair pull tokens from this contract.
checkApproval(redeem, address(_router)); checkApproval(underlying, address(_router));
checkApproval(redeem, address(_router)); checkApproval(underlying, address(_router));
64,481
38
// Add a Bitstray motive. This function can only be called by the owner when not locked. /
function addMotive(bytes calldata _motive) external override onlyOwner whenPartsNotLocked { _addMotive(_motive); }
function addMotive(bytes calldata _motive) external override onlyOwner whenPartsNotLocked { _addMotive(_motive); }
37,148
112
// We calculate the actual fees used
uint256 usedFeeUnderlying = (consumed[baseIndex]).divDown( percentFeeGov ); uint256 usedFeeBond = (consumed[bondIndex]).divDown(percentFeeGov);
uint256 usedFeeUnderlying = (consumed[baseIndex]).divDown( percentFeeGov ); uint256 usedFeeBond = (consumed[bondIndex]).divDown(percentFeeGov);
43,558
70
// solution is not the best => -1
return err;
return err;
48,714
45
// Stores the sent amount as credit to be withdrawn. payee The destination address of the funds.
* Emits a {Deposited} event. */ function deposit(address payee) public payable virtual onlyOwner { uint256 amount = msg.value; _deposits[payee] += amount; emit Deposited(payee, amount); }
* Emits a {Deposited} event. */ function deposit(address payee) public payable virtual onlyOwner { uint256 amount = msg.value; _deposits[payee] += amount; emit Deposited(payee, amount); }
3,142
40
// Cap the roundTotal is either the total contribution from the PutPotWei or CallPotWei, whichever is greater
if(roundTotal > _round.totalCallPotWei && roundTotal > _round.totalPutPotWei){ if(_round.totalCallPotWei > _round.totalPutPotWei){ roundTotal = _round.totalCallPotWei; }else{
if(roundTotal > _round.totalCallPotWei && roundTotal > _round.totalPutPotWei){ if(_round.totalCallPotWei > _round.totalPutPotWei){ roundTotal = _round.totalCallPotWei; }else{
32,348
12
// Declare a boolean designating basic order parameter offset validity.
bool validOffsets;
bool validOffsets;
33,347
140
// Override to extend the way in which ether is converted to tokens. _weiAmount Value in wei to be converted into tokensreturn Number of tokens that can be purchased with the specified _weiAmount /
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256)
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256)
1,263
111
// dfTokenizedStrategy.burnTokens(amount, 0, 0, flashloanFromAddress);
dfTokenizedStrategy.burnTokens(amount, true); // старая версия tokenizedDeposits, можно в новой доавить функцию с такой же сигнатурой if (receiver != address(this)) token.transfer(receiver, amount);
dfTokenizedStrategy.burnTokens(amount, true); // старая версия tokenizedDeposits, можно в новой доавить функцию с такой же сигнатурой if (receiver != address(this)) token.transfer(receiver, amount);
40,054
62
// Returns auction details for a given auctionId. /
function getReserveAuction(uint256 auctionId) public view returns (ReserveAuction memory) { return auctionIdToAuction[auctionId]; }
function getReserveAuction(uint256 auctionId) public view returns (ReserveAuction memory) { return auctionIdToAuction[auctionId]; }
57,246
195
// this ensures any rate outside the limit will never be returned
uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) {
uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) {
4,516
127
// each early purchaser receives 20% bonus
uint256 bonus = SafeMath.mul(amount, 20) / 100; uint256 amountWithBonus = SafeMath.add(amount, bonus); earlyPurchasedAmountBy[purchaser] += amountWithBonus;
uint256 bonus = SafeMath.mul(amount, 20) / 100; uint256 amountWithBonus = SafeMath.add(amount, bonus); earlyPurchasedAmountBy[purchaser] += amountWithBonus;
36,723
389
// The timestamp of the window end /
uint256 public endWindow;
uint256 public endWindow;
3,549
36
// หัก 10% จาก actualAmount
uint256 feeAmount = actualAmount * 10 / 100; actualAmount -= feeAmount; stakers[_stakeMsgSender()].amountStaked += actualAmount; stakingTokenBalance += actualAmount; emit TokensStaked(_stakeMsgSender(), actualAmount); emit FeeTaken(_stakeMsgSender(), feeAmount);
uint256 feeAmount = actualAmount * 10 / 100; actualAmount -= feeAmount; stakers[_stakeMsgSender()].amountStaked += actualAmount; stakingTokenBalance += actualAmount; emit TokensStaked(_stakeMsgSender(), actualAmount); emit FeeTaken(_stakeMsgSender(), feeAmount);
29,993
42
// We assume that this function is always called immediately after `_checkpoint()`, which guarantees that `_historicalIntegralSize` equals to the number of historical rebalances.
uint256 rebalanceSize = _historicalIntegralSize; integral = targetVersion == rebalanceSize ? _invTotalWeightIntegral : _historicalIntegrals[targetVersion];
uint256 rebalanceSize = _historicalIntegralSize; integral = targetVersion == rebalanceSize ? _invTotalWeightIntegral : _historicalIntegrals[targetVersion];
18,451
4
// Returns information about a given `NFT`. tokenId_ Unique `ID` of token. index_ Bucket index to check for position information. return `LP` in bucket. return Position's deposit time./
function getPositionInfo(
function getPositionInfo(
35,471
11
// Pause token transfer
function pause() public onlyOwner virtual { _pause(); }
function pause() public onlyOwner virtual { _pause(); }
17,762
27
// Batch transfer equal tokens amout to some addresses_dests Array of addresses_value Number of transfer tokens amount/
function batchTransferSingleValue(address[] _dests, uint256 _value) public { uint256 i = 0; while (i < _dests.length) { transfer(_dests[i], _value); i += 1; } }
function batchTransferSingleValue(address[] _dests, uint256 _value) public { uint256 i = 0; while (i < _dests.length) { transfer(_dests[i], _value); i += 1; } }
22,759
31
// the strategy is responsible for maintaining the list of salvageable tokens, to make sure that governance cannot come in and take away the coins
IStrategy(_strategy).salvageToken(governance(), _token, _amount);
IStrategy(_strategy).salvageToken(governance(), _token, _amount);
13,377
146
// the below function calculates where tokens needs to go based on the inputted amount of tokens. n.b., this function does not work in reflections, those typically happen later in the processing when the token distribution calculated by this function is turned to reflections based on the golden ratio of total token supply to total reflections.
function _getTokenValues(uint256 amountOfTokens) private view returns ( uint256, uint256, uint256 )
function _getTokenValues(uint256 amountOfTokens) private view returns ( uint256, uint256, uint256 )
34,098
10
// solium-disable-next-line security/no-block-members
return block.timestamp;
return block.timestamp;
2,784
86
// Check price has not moved a lot recently. This mitigates price manipulation during rebalance and also prevents placing orders when it's too volatile.
function checkDeviation(IUniswapV3Pool pool, int24 maxTwapDeviation, uint32 twapDuration) internal view { (, int24 currentTick, , , , , ) = pool.slot0(); int24 twap = getTwap(pool, twapDuration); int24 deviation = currentTick > twap ? currentTick - twap : twap - currentTick; require(deviation <= maxTwapDeviation, "PSC"); }
function checkDeviation(IUniswapV3Pool pool, int24 maxTwapDeviation, uint32 twapDuration) internal view { (, int24 currentTick, , , , , ) = pool.slot0(); int24 twap = getTwap(pool, twapDuration); int24 deviation = currentTick > twap ? currentTick - twap : twap - currentTick; require(deviation <= maxTwapDeviation, "PSC"); }
2,742
41
// Function that returns the guess of a day sorted by a number _day uint256 The guess your are asking aboutreturn uint256 The id of the asked guess of the day /
function getGuessByDayLength (uint32 _day) isOwner external view returns (uint256) { return guessesByDate[_day].length; }
function getGuessByDayLength (uint32 _day) isOwner external view returns (uint256) { return guessesByDate[_day].length; }
46,550
5
// Simulate a call to paymaster.validatePaymasterUserOp.Validation succeeds if the call doesn't revert. The node must also verify it doesn't use banned opcodes, and that it doesn't reference storage outside the wallet's data. In order to split the running opcodes of the wallet (validateUserOp) from the paymaster's validatePaymasterUserOp, it should look for the NUMBER opcode at depth=1 (which itself is a banned opcode) userOp the user operation to validate.return preOpGas total gas used by validation (aka. gasUsedBeforeOperation)return prefund the amount the paymaster had to prefundreturn deadline until what time this userOp is valid (paymaster's deadline) /
function simulateValidation(UserOperation calldata userOp)
function simulateValidation(UserOperation calldata userOp)
31,363
49
// internal functions // This function will calculate the start blocks for each tranche startBlock start of the vesting contract duration Amount of blocks per tranche/
function _calculateTranches(uint256 startBlock, uint256 duration) internal { // start block cannot be 0 require(startBlock > 0, "NO_START_BLOCK"); // duration of tranches needs to be bigger than 0 require(duration > 0, "NO_DURATION"); // set tranche duration _trancheDuration = duration; // tranche 1 starts at start _tranches.push(startBlock); // tranche 2 starts `duration` amount of blocks after the first tranche _tranches.push(startBlock.add(duration)); // tranche 3 starts `duration` amount of blocks after second tranche _tranches.push(startBlock.add(duration.mul(2))); // tranche 3 starts `duration` amount of blocks after third tranche _tranches.push(startBlock.add(duration.mul(3))); }
function _calculateTranches(uint256 startBlock, uint256 duration) internal { // start block cannot be 0 require(startBlock > 0, "NO_START_BLOCK"); // duration of tranches needs to be bigger than 0 require(duration > 0, "NO_DURATION"); // set tranche duration _trancheDuration = duration; // tranche 1 starts at start _tranches.push(startBlock); // tranche 2 starts `duration` amount of blocks after the first tranche _tranches.push(startBlock.add(duration)); // tranche 3 starts `duration` amount of blocks after second tranche _tranches.push(startBlock.add(duration.mul(2))); // tranche 3 starts `duration` amount of blocks after third tranche _tranches.push(startBlock.add(duration.mul(3))); }
80,526
9
// I increment tokenIds here so that my first NFT has an ID of 1. More on this in the lesson!
_tokenIds.increment();
_tokenIds.increment();
7,231