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
80
// Reason error codes for the TransactionRelayed event/OK - the transaction was successfully relayed and execution successful - never included in the event/RelayedCallFailed - the transaction was relayed, but the relayed call failed/RejectedByPreRelayed - the transaction was not relayed due to preRelatedCall reverting/RejectedByForwarder - the transaction was not relayed due to forwarder check (signature,nonce)/PostRelayedFailed - the transaction was relayed and reverted due to postRelatedCall reverting/PaymasterBalanceChanged - the transaction was relayed and reverted due to the paymaster balance change
enum RelayCallStatus { OK, RelayedCallFailed, RejectedByPreRelayed, RejectedByForwarder, RejectedByRecipientRevert, PostRelayedFailed, PaymasterBalanceChanged }
enum RelayCallStatus { OK, RelayedCallFailed, RejectedByPreRelayed, RejectedByForwarder, RejectedByRecipientRevert, PostRelayedFailed, PaymasterBalanceChanged }
6,622
33
// Calculates how many votes should be withdrawn from eachdeprecated group. withdrawal The total amount of votes that needs to be withdrawn.return deprecatedGroupsWithdrawn The array of deprecated groups to bewithdrawn from.return deprecatedWithdrawalsPerGroup The amount of votes to withdrawfrom the respective deprecated group in `deprecatedGroupsWithdrawn`.return numberDeprecatedGroupsWithdrawn The number of groups in`deprecatedGroupsWithdrawn` that have a non zero withdrawal.return remainingWithdrawal The number of votes that still need to bewithdrawn after withdrawing from deprecated groups. Non zero entries of `deprecatedWithdrawalsPerGroup` will be exactlya prefix of length `numberDeprecatedGroupsWithdrawn`. /
function getDeprecatedGroupsWithdrawalDistribution(uint256 withdrawal) internal returns ( address[] memory deprecatedGroupsWithdrawn, uint256[] memory deprecatedWithdrawalsPerGroup, uint256 numberDeprecatedGroupsWithdrawn, uint256 remainingWithdrawal )
function getDeprecatedGroupsWithdrawalDistribution(uint256 withdrawal) internal returns ( address[] memory deprecatedGroupsWithdrawn, uint256[] memory deprecatedWithdrawalsPerGroup, uint256 numberDeprecatedGroupsWithdrawn, uint256 remainingWithdrawal )
29,034
17
// Returns the amount of tokens approved by the owner that can betransferred to the spender's account tokenOwner Address of token owner we check for allowance on spender Address of spender that token owner approved to spend on his behalfreturn uint /
function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return super.allowance(tokenOwner, spender); }
function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return super.allowance(tokenOwner, spender); }
26,413
14
// update l2 latest store block number_l2StoredBlockNumber l2 latest block number/
function updateL2StoredBlockNumber(uint256 _l2StoredBlockNumber) external { require(msg.sender == sequencer, "Only the sequencer can set latest l2 block number"); l2StoredBlockNumber = _l2StoredBlockNumber; }
function updateL2StoredBlockNumber(uint256 _l2StoredBlockNumber) external { require(msg.sender == sequencer, "Only the sequencer can set latest l2 block number"); l2StoredBlockNumber = _l2StoredBlockNumber; }
1,787
22
// get reward pool for the given token
RewardPool storage pool = rewardPools[tokenAddress];
RewardPool storage pool = rewardPools[tokenAddress];
32,969
146
// Resets last validator - the one with the smallest vesting balance
function resetLastActiveValidator(ChainInfo storage chain) internal { address foundLastValidatorAcc = chain.validators.list[0]; uint256 foundLastValidatorVesting = chain.usersData[foundLastValidatorAcc].validator.vesting; address actValidatorAcc; uint256 actValidatorVesting; for (uint256 i = 1; i < chain.validators.list.length; i++) { actValidatorAcc = chain.validators.list[i]; actValidatorVesting = chain.usersData[actValidatorAcc].validator.vesting; if (actValidatorVesting <= foundLastValidatorVesting) { foundLastValidatorAcc = actValidatorAcc; foundLastValidatorVesting = actValidatorVesting; } } chain.lastValidator = foundLastValidatorAcc; }
function resetLastActiveValidator(ChainInfo storage chain) internal { address foundLastValidatorAcc = chain.validators.list[0]; uint256 foundLastValidatorVesting = chain.usersData[foundLastValidatorAcc].validator.vesting; address actValidatorAcc; uint256 actValidatorVesting; for (uint256 i = 1; i < chain.validators.list.length; i++) { actValidatorAcc = chain.validators.list[i]; actValidatorVesting = chain.usersData[actValidatorAcc].validator.vesting; if (actValidatorVesting <= foundLastValidatorVesting) { foundLastValidatorAcc = actValidatorAcc; foundLastValidatorVesting = actValidatorVesting; } } chain.lastValidator = foundLastValidatorAcc; }
18,569
15
// solium-disable-next-line indentation
uint256(keccak256(abi.encodePacked(nonceTimesGeneratorAddress, msgHash)));
uint256(keccak256(abi.encodePacked(nonceTimesGeneratorAddress, msgHash)));
44,893
37
// Add/update allowed max expiration _maxExpiration maximum expiration time of option /
function addAllowedMaxExpiration(uint256 _maxExpiration) public onlyOwner(msg.sender) { allowedMaxExpiration[_maxExpiration] = true; }
function addAllowedMaxExpiration(uint256 _maxExpiration) public onlyOwner(msg.sender) { allowedMaxExpiration[_maxExpiration] = true; }
32,819
68
// Give rewards to voters and return the outcome of the vote
function ConcludeProposal(uint vetoTime, UserManager UMI) external returns (int){ // Require that all voters are able to voter require(VotingTokensCreated == voters.getValuesLength(), "Have not created all the VotingTokens"); // Require that enough time has passed for the old account to veto an attack if (vetoTime > block.timestamp - startTime){ return -1; } uint total = 0; // Total number of votes uint yeses = 0; // Total number of yesses uint totalTimeToVote = 0; // Total time used to vote // Counts votes and find the time required for all voters to vote for (uint i = 0; i < voters.getValuesLength(); i++) { // Goes through all voters // Get voting token for voter VotingToken.Token storage temp = votingtokens[voters.getValue(i)]; // Incroment totalTimeToVote by the amount of time used by the voter totalTimeToVote += temp.getVotedTime(); // Count votes if (temp.getVoted()){ // They are a voter and they voted total++; // Incroment the total number of votes if (temp.getVote()){ // They are a voter and they voted yes yeses++; // Incroment the number of yesses } } } // Requires a certain number of voters to vote before concluding the vote if (total < (numberOfVoters*3)/4){ // If enough time has passed allow a revote if (block.timestamp - startTime > 172800){ return 60; } return -2; // Require more votes } bool outcome = (100*yeses) / total >= 66; // The outcome of the vote // Factors used in determining the requare for voters uint participationFactor = 2; // Participation factor uint correctionFactor = 2; // Correction factor uint timeFactor = 1; // Time factor // Average time used to vote uint averageTimeToVote = totalTimeToVote / total; // Rewards voters for (uint i = 0; i < voters.getValuesLength(); i++) { // Goes through all voters // Get voting token for voter VotingToken.Token storage temp = votingtokens[voters.getValue(i)]; if (temp.getVoted()){ // If the voter has voted // Reward for participating uint amount = (price / participationFactor) / total; // They voted correctly if (outcome == temp.getVote()){ if (outcome){ // Yes was the correct vote // Reward for voting correctly amount += (price / correctionFactor) / yeses; }else{ // No was the correct vote // Reward for voting correctly amount += (price / correctionFactor) / (total-yeses); } } // Reward based on the time used to vote // If they took less time than average they gain more money amount += (averageTimeToVote - temp.getVotedTime()) / timeFactor; if (amount > 0){ // The user actually did get a reward // Increases balance of the voter UMI.getUser(voters.getValue(i)).increaseBalance(amount); } } } return int((100*yeses) / total); // Return outcome of vote }
function ConcludeProposal(uint vetoTime, UserManager UMI) external returns (int){ // Require that all voters are able to voter require(VotingTokensCreated == voters.getValuesLength(), "Have not created all the VotingTokens"); // Require that enough time has passed for the old account to veto an attack if (vetoTime > block.timestamp - startTime){ return -1; } uint total = 0; // Total number of votes uint yeses = 0; // Total number of yesses uint totalTimeToVote = 0; // Total time used to vote // Counts votes and find the time required for all voters to vote for (uint i = 0; i < voters.getValuesLength(); i++) { // Goes through all voters // Get voting token for voter VotingToken.Token storage temp = votingtokens[voters.getValue(i)]; // Incroment totalTimeToVote by the amount of time used by the voter totalTimeToVote += temp.getVotedTime(); // Count votes if (temp.getVoted()){ // They are a voter and they voted total++; // Incroment the total number of votes if (temp.getVote()){ // They are a voter and they voted yes yeses++; // Incroment the number of yesses } } } // Requires a certain number of voters to vote before concluding the vote if (total < (numberOfVoters*3)/4){ // If enough time has passed allow a revote if (block.timestamp - startTime > 172800){ return 60; } return -2; // Require more votes } bool outcome = (100*yeses) / total >= 66; // The outcome of the vote // Factors used in determining the requare for voters uint participationFactor = 2; // Participation factor uint correctionFactor = 2; // Correction factor uint timeFactor = 1; // Time factor // Average time used to vote uint averageTimeToVote = totalTimeToVote / total; // Rewards voters for (uint i = 0; i < voters.getValuesLength(); i++) { // Goes through all voters // Get voting token for voter VotingToken.Token storage temp = votingtokens[voters.getValue(i)]; if (temp.getVoted()){ // If the voter has voted // Reward for participating uint amount = (price / participationFactor) / total; // They voted correctly if (outcome == temp.getVote()){ if (outcome){ // Yes was the correct vote // Reward for voting correctly amount += (price / correctionFactor) / yeses; }else{ // No was the correct vote // Reward for voting correctly amount += (price / correctionFactor) / (total-yeses); } } // Reward based on the time used to vote // If they took less time than average they gain more money amount += (averageTimeToVote - temp.getVotedTime()) / timeFactor; if (amount > 0){ // The user actually did get a reward // Increases balance of the voter UMI.getUser(voters.getValue(i)).increaseBalance(amount); } } } return int((100*yeses) / total); // Return outcome of vote }
11,461
12
// _die();
_this.emitApoptosis( receiver );
_this.emitApoptosis( receiver );
50,183
44
// BLO token contract.
BlokToken public blok;
BlokToken public blok;
26,827
11
// Transfer purchased assets to msg.sender.
transferAssetToSender(orders[0].makerAssetData, makerAssetAmountPurchased);
transferAssetToSender(orders[0].makerAssetData, makerAssetAmountPurchased);
1,166
158
// internal implementation of unstaking methods amount number of tokens to unstake gysr number of GYSR tokens applied to unstaking operationreturn number of reward tokens distributed /
function _unstake(uint256 amount, uint256 gysr) private nonReentrant returns (uint256)
function _unstake(uint256 amount, uint256 gysr) private nonReentrant returns (uint256)
38,125
503
// A modifier which checks if whitelisted for minting.
modifier onlyWhitelisted() { require(whiteList[msg.sender], "Transmuter: !whitelisted"); _; }
modifier onlyWhitelisted() { require(whiteList[msg.sender], "Transmuter: !whitelisted"); _; }
35,673
295
// Storage for the `oracleId` results dataCache[oracleId][timestamp] => data
mapping (address => mapping(uint256 => uint256)) public dataCache;
mapping (address => mapping(uint256 => uint256)) public dataCache;
34,314
23
// ERC721TradableERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. /
abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable { using SafeMath for uint256; address proxyRegistryAddress; mapping (address => bool) operators; mapping (uint256 => uint256) tokenToSeries; struct Series { string name; string baseURI; uint256 start; uint256 current; uint256 supply; } Series[] collections; event NewCollection(uint256 collection_id,string name,string baseURI,uint256 start,uint256 supply); constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; _initializeEIP712(_name); } modifier ownerOrOperator() { require(msgSender() == owner() || operators[msgSender()],"caller is neither the owner nor the operator"); _; } function setOperator(address _operator, bool status) external onlyOwner { if (status) { operators[_operator] = status; } else { delete operators[_operator]; } } function addSeries( string[] memory _names, string[] memory baseURIs, uint256[] memory _starts, uint256[] memory _supplys ) external onlyOwner { require (_names.length == baseURIs.length, "len 1 & 2 not equal"); require (_names.length == _starts.length, "len 1 & 3 not equal"); require (_names.length == _supplys.length, "len 1 & 4 not equal"); for (uint j = 0; j < _names.length; j++){ collections.push(Series(_names[j],baseURIs[j],_starts[j],0, _supplys[j])); emit NewCollection(collections.length-1,_names[j],baseURIs[j],_starts[j], _supplys[j]); } } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function preMintTo(address _to, uint256[] memory _seriesz) public ownerOrOperator { for (uint j = 0; j < _seriesz.length; j++){ uint256 collection = _seriesz[j]; require(collection < collections.length, "Invalid Collection"); uint256 newTokenId = _getNextTokenId(collection); _mint(_to, newTokenId); tokenToSeries[newTokenId] = collection; } } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function mintTo(address _to, uint256 collection) public ownerOrOperator { require(collection < collections.length, "Invalid Collection"); uint256 newTokenId = _getNextTokenId(collection); _mint(_to, newTokenId); tokenToSeries[newTokenId] = collection; } function privateMint(address _to, uint256 collection) public onlyOwner { require(collections[collection].supply == 250,"Wrong collection"); for (uint i = 0; i < 25; i++) { uint256 newTokenId = _getNextTokenId(collection); _mint(_to, newTokenId); tokenToSeries[newTokenId] = collection; } } /** * @dev calculates the next token ID based on value of _currentTokenId * @return uint256 for the next token ID */ function _getNextTokenId(uint256 collection) private returns (uint256) { Series storage coll = collections[collection]; uint pointer = coll.current++; require(pointer < coll.supply, "No tokens available"); uint256 reply = coll.start + pointer; return reply; } /** * @dev increments the value of _currentTokenId */ function baseTokenURI() virtual public view returns (string memory); function seriesURI(uint256 collection) public view returns (string memory) { require(collection < collections.length, "Invalid Collection"); return collections[collection].baseURI; } function seriesStart(uint256 collection) internal view returns (uint256) { require(collection < collections.length, "Invalid Collection"); return collections[collection].start; } function seriesName(uint256 collection) public view returns (string memory) { require(collection < collections.length, "Invalid Collection"); return collections[collection].name; } function tokenURI(uint256 _tokenId) override public view returns (string memory) { require(_exists(_tokenId),"Token does not exist"); uint256 collection = tokenToSeries[_tokenId]; uint256 adjustedID = _tokenId - seriesStart(collection)+1; return string(abi.encodePacked(baseTokenURI(),seriesURI(collection),"/", Strings.toString(adjustedID))); } function numSeries() external view returns (uint256) { return collections.length; } function available(uint256 collectionId) external view returns (uint256) { require(collectionId < collections.length, "Invalid Collection"); Series memory coll = collections[collectionId]; return coll.supply - coll.current; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address _owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == operator) { return true; } return super.isApprovedForAll(_owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } }
abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable { using SafeMath for uint256; address proxyRegistryAddress; mapping (address => bool) operators; mapping (uint256 => uint256) tokenToSeries; struct Series { string name; string baseURI; uint256 start; uint256 current; uint256 supply; } Series[] collections; event NewCollection(uint256 collection_id,string name,string baseURI,uint256 start,uint256 supply); constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; _initializeEIP712(_name); } modifier ownerOrOperator() { require(msgSender() == owner() || operators[msgSender()],"caller is neither the owner nor the operator"); _; } function setOperator(address _operator, bool status) external onlyOwner { if (status) { operators[_operator] = status; } else { delete operators[_operator]; } } function addSeries( string[] memory _names, string[] memory baseURIs, uint256[] memory _starts, uint256[] memory _supplys ) external onlyOwner { require (_names.length == baseURIs.length, "len 1 & 2 not equal"); require (_names.length == _starts.length, "len 1 & 3 not equal"); require (_names.length == _supplys.length, "len 1 & 4 not equal"); for (uint j = 0; j < _names.length; j++){ collections.push(Series(_names[j],baseURIs[j],_starts[j],0, _supplys[j])); emit NewCollection(collections.length-1,_names[j],baseURIs[j],_starts[j], _supplys[j]); } } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function preMintTo(address _to, uint256[] memory _seriesz) public ownerOrOperator { for (uint j = 0; j < _seriesz.length; j++){ uint256 collection = _seriesz[j]; require(collection < collections.length, "Invalid Collection"); uint256 newTokenId = _getNextTokenId(collection); _mint(_to, newTokenId); tokenToSeries[newTokenId] = collection; } } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function mintTo(address _to, uint256 collection) public ownerOrOperator { require(collection < collections.length, "Invalid Collection"); uint256 newTokenId = _getNextTokenId(collection); _mint(_to, newTokenId); tokenToSeries[newTokenId] = collection; } function privateMint(address _to, uint256 collection) public onlyOwner { require(collections[collection].supply == 250,"Wrong collection"); for (uint i = 0; i < 25; i++) { uint256 newTokenId = _getNextTokenId(collection); _mint(_to, newTokenId); tokenToSeries[newTokenId] = collection; } } /** * @dev calculates the next token ID based on value of _currentTokenId * @return uint256 for the next token ID */ function _getNextTokenId(uint256 collection) private returns (uint256) { Series storage coll = collections[collection]; uint pointer = coll.current++; require(pointer < coll.supply, "No tokens available"); uint256 reply = coll.start + pointer; return reply; } /** * @dev increments the value of _currentTokenId */ function baseTokenURI() virtual public view returns (string memory); function seriesURI(uint256 collection) public view returns (string memory) { require(collection < collections.length, "Invalid Collection"); return collections[collection].baseURI; } function seriesStart(uint256 collection) internal view returns (uint256) { require(collection < collections.length, "Invalid Collection"); return collections[collection].start; } function seriesName(uint256 collection) public view returns (string memory) { require(collection < collections.length, "Invalid Collection"); return collections[collection].name; } function tokenURI(uint256 _tokenId) override public view returns (string memory) { require(_exists(_tokenId),"Token does not exist"); uint256 collection = tokenToSeries[_tokenId]; uint256 adjustedID = _tokenId - seriesStart(collection)+1; return string(abi.encodePacked(baseTokenURI(),seriesURI(collection),"/", Strings.toString(adjustedID))); } function numSeries() external view returns (uint256) { return collections.length; } function available(uint256 collectionId) external view returns (uint256) { require(collectionId < collections.length, "Invalid Collection"); Series memory coll = collections[collectionId]; return coll.supply - coll.current; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address _owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == operator) { return true; } return super.isApprovedForAll(_owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } }
4,092
89
// List ntoken information by page/offset Skip previous (offset) records/count Return (count) records/order Order. 0 reverse order, non-0 positive order/ return ntoken information by page
function list(uint offset, uint count, uint order) external view returns (NTokenTag[] memory);
function list(uint offset, uint count, uint order) external view returns (NTokenTag[] memory);
37,237
26
// Returns the minimum input asset amount required to buy the given output asset amount and the prices amountOut Amount of reserveOut reserveIn Address of the asset to be swap from reserveOut Address of the asset to be swap toreturn uint256 Amount in of the reserveInreturn uint256 The price of in amount denominated in the reserveOut currency (18 decimals)return uint256 In amount of reserveIn value denominated in USD (8 decimals)return uint256 Out amount of reserveOut value denominated in USD (8 decimals) /
function getAmountsIn( uint256 amountOut, address reserveIn, address reserveOut ) external view override returns ( uint256,
function getAmountsIn( uint256 amountOut, address reserveIn, address reserveOut ) external view override returns ( uint256,
11,926
38
// Withdraw everything from external pool
function exitRewardPool() internal virtual { uint bal = _rewardPoolBalance(); if (bal != 0) { withdrawAndClaimFromPool(bal); } }
function exitRewardPool() internal virtual { uint bal = _rewardPoolBalance(); if (bal != 0) { withdrawAndClaimFromPool(bal); } }
11,612
37
// Unstakes the given token IDs and claim $WRAB rewards.Merkle proofs are used to validate rarityMultipliers and prevent usersfrom claiming more rewards than they are supposed to from the contractdirectly by inputting a false rarity multiplier. /
function _unstake( uint256[] calldata tokenIds, uint256[] calldata rarityMultipliers, bytes32[][] calldata merkleProofs, bool revertIfNotEnoughWRAB
function _unstake( uint256[] calldata tokenIds, uint256[] calldata rarityMultipliers, bytes32[][] calldata merkleProofs, bool revertIfNotEnoughWRAB
17,770
0
// Interface for a middleware / service that may look at past stake amounts. Layr Labs, Inc. Specifically, this interface is designed for services that consult stake amounts up to `BLOCK_STALE_MEASURE`blocks in the past. This may be necessary due to, e.g., network processing & communication delays, or to avoid race conditionsthat could be present with coordinating aggregate operator signatures while service operators are registering & de-registering. To clarify edge cases, the middleware can look `BLOCK_STALE_MEASURE` blocks into the past, i.e. it may trust stakes from the interval[block.number - BLOCK_STALE_MEASURE, block.number] (specifically, inclusive of the block that is `BLOCK_STALE_MEASURE` before the current
interface IDelayedService { /// @notice The maximum amount of blocks in the past that the service will consider stake amounts to still be 'valid'. function BLOCK_STALE_MEASURE() external view returns(uint32); }
interface IDelayedService { /// @notice The maximum amount of blocks in the past that the service will consider stake amounts to still be 'valid'. function BLOCK_STALE_MEASURE() external view returns(uint32); }
29,767
12
// Runs a while loop to continue minting for the set amount asked.
for (uint8 counter = 0; counter < _amount; counter++) {
for (uint8 counter = 0; counter < _amount; counter++) {
25,453
61
// Initiate the account of destinations[i] with values[i]. The function must only be called when the contract is paused. The caller must check that destinations are unique addresses. For a large number of destinations, separate the balances initialization in different calls to batchTransfer.destinations List of addresses to set the valuesvalues List of values to set/
function batchTransfer(address[] memory destinations, uint256[] memory values) public onlyOwner whenPaused { require(destinations.length == values.length); uint256 length = destinations.length; uint i; for (i=0; i < length; i++) { rewards[destinations[i]] = values[i]; } }
function batchTransfer(address[] memory destinations, uint256[] memory values) public onlyOwner whenPaused { require(destinations.length == values.length); uint256 length = destinations.length; uint i; for (i=0; i < length; i++) { rewards[destinations[i]] = values[i]; } }
5,980
73
// Mapping from NFT ID to approved address. /
mapping (uint256 => address) internal idToApproval;
mapping (uint256 => address) internal idToApproval;
21,026
581
// Burns tokens from msg.sender, decreases totalSupply, initSupply, and a users balance./
function burn(uint256 amount) override external returns (bool)
function burn(uint256 amount) override external returns (bool)
7,996
44
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo; uint256 public rewardPerSecond; IERC20 public masterLpToken; uint256 private constant ACC_TOKEN_PRECISION = 1e12; address public immutable MASTERCHEF_V2; uint256 internal unlocked;
mapping (uint256 => mapping (address => UserInfo)) public userInfo; uint256 public rewardPerSecond; IERC20 public masterLpToken; uint256 private constant ACC_TOKEN_PRECISION = 1e12; address public immutable MASTERCHEF_V2; uint256 internal unlocked;
9,452
31
// We do not want the validator to ever prevent reporting, so we limit its gas usage and catch any errors that may arise.
try vc.validator.validate{gas: vc.gasLimit}(
try vc.validator.validate{gas: vc.gasLimit}(
28,259
58
// if address is 0, then it's ETH
if (_addr == address(0x0)) { decimals = 18; } else if (isContract(_addr)) {
if (_addr == address(0x0)) { decimals = 18; } else if (isContract(_addr)) {
53,336
134
// ============ Private/Internal Functions ============ //Participant enters the pool and enter amount is transferred from the user to the pool. /
function _enterPool() internal returns(uint256 _participantIndex) { participants.push(msg.sender); totalEnteredAmount = totalEnteredAmount.add(poolConfig.enterAmount); if (participants.length == poolConfig.participantLimit) { emit MaxParticipationCompleted(msg.sender); _getRandomNumber(poolConfig.randomSeed); } _participantIndex = (participants.length).sub(1); emit EnteredPool(msg.sender, poolConfig.enterAmount, _participantIndex); }
function _enterPool() internal returns(uint256 _participantIndex) { participants.push(msg.sender); totalEnteredAmount = totalEnteredAmount.add(poolConfig.enterAmount); if (participants.length == poolConfig.participantLimit) { emit MaxParticipationCompleted(msg.sender); _getRandomNumber(poolConfig.randomSeed); } _participantIndex = (participants.length).sub(1); emit EnteredPool(msg.sender, poolConfig.enterAmount, _participantIndex); }
54,340
5
// BEP20
function name() public pure returns (string memory) { return _name; }
function name() public pure returns (string memory) { return _name; }
94
20
// send / withdraw _amount to _payee_payee the address where the funds are going to go_amount the amount of Ether that will be sent/
function withdrawFromContract(address _payee, uint _amount) external onlyOwner { require(_payee != address(0) && _payee != address(this)); require(contractBalance >= _amount, INSUFICIENT_BALANCE); require(_amount > 0 && _amount <= address(this).balance, NOT_EHOUGH_ETHER); //we check if somebody has hacked the contract, in which case we send all the funds to //the owner of the contract if(contractBalance != address(this).balance){ contractBalance = 0; payable(owner).transfer(address(this).balance); emit SecurityWithdrawal(owner, _amount); }else{ contractBalance -= _amount; payable(_payee).transfer(_amount); emit Sent(_payee, _amount); } }
function withdrawFromContract(address _payee, uint _amount) external onlyOwner { require(_payee != address(0) && _payee != address(this)); require(contractBalance >= _amount, INSUFICIENT_BALANCE); require(_amount > 0 && _amount <= address(this).balance, NOT_EHOUGH_ETHER); //we check if somebody has hacked the contract, in which case we send all the funds to //the owner of the contract if(contractBalance != address(this).balance){ contractBalance = 0; payable(owner).transfer(address(this).balance); emit SecurityWithdrawal(owner, _amount); }else{ contractBalance -= _amount; payable(_payee).transfer(_amount); emit Sent(_payee, _amount); } }
20,092
1
// Owner of the contract
address private _upgradeabilityOwner;
address private _upgradeabilityOwner;
37,469
18
// Array of all snaps
SnapEntry[] public snaps;
SnapEntry[] public snaps;
7,157
112
// make the swap Due to the characteristics of the project, it is not possible to define a minimum amount receivable.
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); return true;
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); return true;
31,004
37
// save the address of the offer
mapOffers[nCurrentId] = objOffer;
mapOffers[nCurrentId] = objOffer;
20,329
37
// Sets the vote-unready threshold/ voteUnreadyPercentMilleThreshold - the minimum threshold in percent-mille (0-100,000)
function setVoteUnreadyPercentMilleThreshold(uint32 voteUnreadyPercentMilleThreshold) external /* onlyFunctionalManager onlyWhenActive */;
function setVoteUnreadyPercentMilleThreshold(uint32 voteUnreadyPercentMilleThreshold) external /* onlyFunctionalManager onlyWhenActive */;
8,452
7
// 소유주의 본부 ID들을 반환합니다.
function getOwnerHQIds(address owner) view external returns (uint[] memory);
function getOwnerHQIds(address owner) view external returns (uint[] memory);
48,776
36
// Deposit payout
if(to_payout > 0) { if(users[msg.sender].payouts + to_payout > max_payout) { to_payout = max_payout - users[msg.sender].payouts; }
if(to_payout > 0) { if(users[msg.sender].payouts + to_payout > max_payout) { to_payout = max_payout - users[msg.sender].payouts; }
1,899
164
// Prevents other msg.sender than controller or vault addresses
modifier onlyControllerOrVault() { require( _msgSender() == controller || _msgSender() == IController(controller).vaults(_want), "!controller|vault" ); _; }
modifier onlyControllerOrVault() { require( _msgSender() == controller || _msgSender() == IController(controller).vaults(_want), "!controller|vault" ); _; }
80,893
38
// burn div
bool public _closeFee = false; uint256 public _burndiv = 2; string private _name = 'EarnDefiCoin'; string private _symbol = 'EDC'; uint8 private _decimals = 9;
bool public _closeFee = false; uint256 public _burndiv = 2; string private _name = 'EarnDefiCoin'; string private _symbol = 'EDC'; uint8 private _decimals = 9;
49,050
431
// Returns C-OP mapping contract/
function copMapping() private view returns (CopMappingInterface){ return CopMappingInterface(_copMappingAddress); }
function copMapping() private view returns (CopMappingInterface){ return CopMappingInterface(_copMappingAddress); }
32,698
188
// Check whether the account has been changed before and mark it as changed if not. We need this because "nuisance gas" only applies to the first time that an account is changed.
bool _wasAccountAlreadyChanged = ovmStateManager.testAndSetAccountChanged( _address );
bool _wasAccountAlreadyChanged = ovmStateManager.testAndSetAccountChanged( _address );
45,580
220
// Contract initializer/
function init(string memory __name, string memory __symbol, uint __decimals, uint __totalSupply, address __owner, address __admin) internal initializer { __Ownable_init(); __ERC20PresetMinterPauser_init(__name, __symbol); _setupDecimals(uint8(__decimals)); _decimalsMultiplier = 10 ** __decimals; transferOwnership(__owner); _setupRole(DEFAULT_ADMIN_ROLE, __owner); _setupRole(MINTER_ROLE, __owner); _setupRole(DEFAULT_ADMIN_ROLE, __admin); _setupRole(MINTER_ROLE, __admin); _membersCount = 0; setBuyPrice(0); setByuPriceDecimals(0); _mint(__owner, __totalSupply.mul(_decimalsMultiplier)); }
function init(string memory __name, string memory __symbol, uint __decimals, uint __totalSupply, address __owner, address __admin) internal initializer { __Ownable_init(); __ERC20PresetMinterPauser_init(__name, __symbol); _setupDecimals(uint8(__decimals)); _decimalsMultiplier = 10 ** __decimals; transferOwnership(__owner); _setupRole(DEFAULT_ADMIN_ROLE, __owner); _setupRole(MINTER_ROLE, __owner); _setupRole(DEFAULT_ADMIN_ROLE, __admin); _setupRole(MINTER_ROLE, __admin); _membersCount = 0; setBuyPrice(0); setByuPriceDecimals(0); _mint(__owner, __totalSupply.mul(_decimalsMultiplier)); }
76,236
68
// An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
12,156
8
// Transfer `tokens` tokens from `src` to `dst` by `spender` Called by both `transfer` and `transferFrom` internally spender The address of the account performing the transfer src The address of the source account dst The address of the destination account tokens The number of tokens to transferreturn Whether or not the transfer succeeded /
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); comptroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); }
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); comptroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); }
16,188
199
// move tokens to the team multisig wallet
16,871
8
// bytes32 theAddress = stringToBytes32(_address1);
address retAddress= bytesToAddress(stringToByte(_address1)); return retAddress;
address retAddress= bytesToAddress(stringToByte(_address1)); return retAddress;
39,832
55
// import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
using SafeERC20 for IERC20; address constant ETHER = address(0); event LogWithdraw( address indexed _from, address indexed _assetAddress, uint amount );
using SafeERC20 for IERC20; address constant ETHER = address(0); event LogWithdraw( address indexed _from, address indexed _assetAddress, uint amount );
1,432
7
// return name the name of the token /
function name() external view returns(string memory);
function name() external view returns(string memory);
29,569
208
// set the implementation for the admin, this needs to be in a base class else we cannot set it newImpl address pf the implementation /
function setAdminImpl(address newImpl) external onlyGovernor { bytes32 position = adminImplPosition; assembly { sstore(position, newImpl) } }
function setAdminImpl(address newImpl) external onlyGovernor { bytes32 position = adminImplPosition; assembly { sstore(position, newImpl) } }
72,144
112
// Take one off the poolId
poolId = offsetPoolId - 1;
poolId = offsetPoolId - 1;
60,601
106
// specify the only account that can resolve blueprint prediction states and transfer RBLX tokens from a blueprint contract to buyer, creator, or fee collection admin can change address of oracle to be used for blueprints created thereafter, see NOTE5 for clarifications
rblxOracleAddress = _rblxOracleAddress;
rblxOracleAddress = _rblxOracleAddress;
20,178
236
// Exit early if all debt was allocated.
if (debtToBeAttributedPoints == 0) { break; }
if (debtToBeAttributedPoints == 0) { break; }
30,022
36
// internal
function _approve(address to, uint tokenId) internal{ _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); }
function _approve(address to, uint tokenId) internal{ _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); }
69,148
16
// otherwise, use the default ERC721.isApprovedForAll()
return ERC721.isApprovedForAll(_owner, _operator);
return ERC721.isApprovedForAll(_owner, _operator);
3,671
10
// Prevent account from minting tokens and voting _address The address to add to the blacklist /
function addToBlacklist(address _address) public onlyOwner { blacklist[_address] = true; }
function addToBlacklist(address _address) public onlyOwner { blacklist[_address] = true; }
31,966
25
// function addPharmacyCompany( address _pharmacyCompany, string memory _name, uint256 _pharmacyCompanyId
// ) public { // require( // allPharmacyCompany[_pharmacyCompany].isAdded == false, // "you already added yourself" // ); // PharmacyCompany storage newPharmacyCompany = allPharmacyCompany[ // _pharmacyCompany // ]; // newPharmacyCompany.pharmacyCompany = _pharmacyCompany; // newPharmacyCompany.name = _name; // newPharmacyCompany.pharmacyCompanyId = _pharmacyCompanyId; // newPharmacyCompany.isAdded = true; // allPharmacyCompanyAddress.push(_pharmacyCompany); // }
// ) public { // require( // allPharmacyCompany[_pharmacyCompany].isAdded == false, // "you already added yourself" // ); // PharmacyCompany storage newPharmacyCompany = allPharmacyCompany[ // _pharmacyCompany // ]; // newPharmacyCompany.pharmacyCompany = _pharmacyCompany; // newPharmacyCompany.name = _name; // newPharmacyCompany.pharmacyCompanyId = _pharmacyCompanyId; // newPharmacyCompany.isAdded = true; // allPharmacyCompanyAddress.push(_pharmacyCompany); // }
26,192
89
// X-CARD /
) public override onlyAdmin { ERC721State.ERC721LAState storage state = ERC721State ._getERC721LAState(); state._xCardContractAddress = xCardContractAddress; }
) public override onlyAdmin { ERC721State.ERC721LAState storage state = ERC721State ._getERC721LAState(); state._xCardContractAddress = xCardContractAddress; }
40,242
48
// tokenId => (child address => array of child tokens)
mapping(uint256 => mapping(address => EnumerableSet.UintSet)) private childTokens;
mapping(uint256 => mapping(address => EnumerableSet.UintSet)) private childTokens;
9,026
69
// Elliptic Curve Digital Signature Algorithm (ECDSA) operations. These functions can be used to verify that a message was signed by the holderof the private keys of a given address. /
library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } }
library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } }
422
107
// Provides an interface to the ratio unitreturn Ratio scale unit (1e8 or 1108) /
function getRatioScale() internal pure returns (uint256) { return RATIO_SCALE; }
function getRatioScale() internal pure returns (uint256) { return RATIO_SCALE; }
9,961
22
// Misc
uint256 internal constant SHOULD_NOT_HAPPEN = 999;
uint256 internal constant SHOULD_NOT_HAPPEN = 999;
3,298
263
// EnumerableSet of all msdTokens
EnumerableSetUpgradeable.AddressSet internal msdTokens;
EnumerableSetUpgradeable.AddressSet internal msdTokens;
52,197
246
// Returns the total rewards currently available for withdrawal. (For calling from inside the contract) /
function _calculateWithdrawableAmount(address _property, address _user) private view returns (uint256 _amount, uint256 _price)
function _calculateWithdrawableAmount(address _property, address _user) private view returns (uint256 _amount, uint256 _price)
35,077
14
// Revokes a prior confirmation of the given operation
function revoke(bytes32 _operation) external { uint memberIndex = m_memberIndex[uint(msg.sender)]; // make sure they're an member if (memberIndex == 0) return; uint memberIndexBit = 2**memberIndex; var pending = m_pending[_operation]; if (pending.membersDone & memberIndexBit > 0) { pending.yetNeeded++; pending.membersDone -= memberIndexBit; Revoke(msg.sender, _operation); } }
function revoke(bytes32 _operation) external { uint memberIndex = m_memberIndex[uint(msg.sender)]; // make sure they're an member if (memberIndex == 0) return; uint memberIndexBit = 2**memberIndex; var pending = m_pending[_operation]; if (pending.membersDone & memberIndexBit > 0) { pending.yetNeeded++; pending.membersDone -= memberIndexBit; Revoke(msg.sender, _operation); } }
45,347
47
// Token contract - Implements Standard Token Interface but adds Charity Support :)/Rishab Hegde - <contact@rishabhegde.com>
contract FoolToken is StandardToken, Escapable { /* * Token meta data */ string constant public name = "FoolToken"; string constant public symbol = "FOOL"; uint8 constant public decimals = 18; bool public alive = true; Campaign public beneficiary; // expected to be a Giveth campaign /// @dev Contract constructor function sets Giveth campaign function FoolToken( Campaign _beneficiary, address _escapeHatchCaller, address _escapeHatchDestination ) Escapable(_escapeHatchCaller, _escapeHatchDestination) { beneficiary = _beneficiary; } /* * Contract functions */ /// @dev Allows user to create tokens if token creation is still going /// and cap was not reached. Returns token count. function () public payable { require(alive); require(msg.value != 0) ; require(beneficiary.proxyPayment.value(msg.value)(msg.sender)); uint tokenCount = div(1 ether * 10 ** 18, msg.value); balances[msg.sender] = add(balances[msg.sender], tokenCount); Transfer(0, msg.sender, tokenCount); } /// @dev Allows founder to shut down the contract function killswitch() onlyOwner public { alive = false; } }
contract FoolToken is StandardToken, Escapable { /* * Token meta data */ string constant public name = "FoolToken"; string constant public symbol = "FOOL"; uint8 constant public decimals = 18; bool public alive = true; Campaign public beneficiary; // expected to be a Giveth campaign /// @dev Contract constructor function sets Giveth campaign function FoolToken( Campaign _beneficiary, address _escapeHatchCaller, address _escapeHatchDestination ) Escapable(_escapeHatchCaller, _escapeHatchDestination) { beneficiary = _beneficiary; } /* * Contract functions */ /// @dev Allows user to create tokens if token creation is still going /// and cap was not reached. Returns token count. function () public payable { require(alive); require(msg.value != 0) ; require(beneficiary.proxyPayment.value(msg.value)(msg.sender)); uint tokenCount = div(1 ether * 10 ** 18, msg.value); balances[msg.sender] = add(balances[msg.sender], tokenCount); Transfer(0, msg.sender, tokenCount); } /// @dev Allows founder to shut down the contract function killswitch() onlyOwner public { alive = false; } }
30,307
49
// Allows the current admin to set the admin in one tx. Useful initial deployment. newAdmin The address to transfer ownership to. /
function transferAdminQuickly(address newAdmin) public onlyAdmin { require(newAdmin != address(0), "admin 0"); emit TransferAdminPending(newAdmin); emit AdminClaimed(newAdmin, admin); admin = newAdmin; }
function transferAdminQuickly(address newAdmin) public onlyAdmin { require(newAdmin != address(0), "admin 0"); emit TransferAdminPending(newAdmin); emit AdminClaimed(newAdmin, admin); admin = newAdmin; }
29,155
3
// grows too big for a single call of {ERC721AQueryable-tokensOfOwner}. Requirements: - `start` < `stop` /
function tokensOfOwnerIn( address owner, uint256 start, uint256 stop ) external view returns (uint256[] memory) { unchecked { if (start >= stop) revert InvalidQueryRange(); uint256 tokenIdsIdx; uint256 stopLimit = _currentIndex;
function tokensOfOwnerIn( address owner, uint256 start, uint256 stop ) external view returns (uint256[] memory) { unchecked { if (start >= stop) revert InvalidQueryRange(); uint256 tokenIdsIdx; uint256 stopLimit = _currentIndex;
3,793
5
// 2Rt/d
Decimal.D256 memory start = Decimal.ratio(_totalReward, _duration).mul(2).mul(_time);
Decimal.D256 memory start = Decimal.ratio(_totalReward, _duration).mul(2).mul(_time);
2,042
161
// Get all tokens owned by owner. /
function ownerTokens(address owner) public view returns (uint256[] memory) { uint256 tokenCount = ERC721Sequencial.balanceOf(owner); require(tokenCount != 0, "ERC721Enumerable: owner owns no tokens"); uint256 length = _owners.length; uint256[] memory tokenIds = new uint256[](tokenCount); unchecked { uint256 i = 0; for (uint256 tokenId = 0; tokenId < length; ++tokenId) { if (_owners[tokenId] == owner) { tokenIds[i++] = tokenId; } } } return tokenIds; }
function ownerTokens(address owner) public view returns (uint256[] memory) { uint256 tokenCount = ERC721Sequencial.balanceOf(owner); require(tokenCount != 0, "ERC721Enumerable: owner owns no tokens"); uint256 length = _owners.length; uint256[] memory tokenIds = new uint256[](tokenCount); unchecked { uint256 i = 0; for (uint256 tokenId = 0; tokenId < length; ++tokenId) { if (_owners[tokenId] == owner) { tokenIds[i++] = tokenId; } } } return tokenIds; }
78,984
87
// @notify Pull funds from the dripper/
function pullFunds() public { rewardDripper.dripReward(address(rewardPool)); }
function pullFunds() public { rewardDripper.dripReward(address(rewardPool)); }
38,135
18
// function to get current limit (per-person proposable number of projects) /return current upper limit
function get_proposal_limit() public view returns (uint256){ return Proposal_limit; }
function get_proposal_limit() public view returns (uint256){ return Proposal_limit; }
6,942
28
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
case 0 { revert(0, returndatasize()) }
8,268
613
// Decompose an ABI-encoded SignatureError./encoded ABI-encoded revert error./ return errorCode The error code./ return signerAddress The expected signer of the hash./ return signature The full signature.
function decodeSignatureError(bytes memory encoded) internal pure returns ( LibExchangeRichErrors.SignatureErrorCodes errorCode, bytes32 hash, address signerAddress, bytes memory signature )
function decodeSignatureError(bytes memory encoded) internal pure returns ( LibExchangeRichErrors.SignatureErrorCodes errorCode, bytes32 hash, address signerAddress, bytes memory signature )
55,001
436
// Duration of the lockreturn Returns the duration of the lock in blocks. /
function lockDuration() public view returns (uint256) { return blocklock.lockDuration; }
function lockDuration() public view returns (uint256) { return blocklock.lockDuration; }
55,337
246
// We calculate the new borrower and total borrow balancesaccountBorrowsNew = accountBorrows - actualRepayAmount
(vars.mathErr, vars.accountBorrowsNew) = subUInt( vars.accountBorrows, vars.repayAmount ); require(vars.mathErr == MathError.NO_ERROR, "Repay borrow new account balance calculation failed");
(vars.mathErr, vars.accountBorrowsNew) = subUInt( vars.accountBorrows, vars.repayAmount ); require(vars.mathErr == MathError.NO_ERROR, "Repay borrow new account balance calculation failed");
24,070
14
// see IVoting interface
( bool open, bool executed,
( bool open, bool executed,
36,047
321
// We can skip the period, as no debt minted during period (next period's startingDebtIndex is still 0)
if (nextPeriodStartingDebtIndex > 0 && lastFeeWithdrawal < _recentFeePeriodsStorage(i).feePeriodId) {
if (nextPeriodStartingDebtIndex > 0 && lastFeeWithdrawal < _recentFeePeriodsStorage(i).feePeriodId) {
4,787
29
// Thrown if the bond hasn't matured yet, or redeeming is paused
error BondNotRedeemable();
error BondNotRedeemable();
35,403
257
// calculates the amount of collateral needed in ETH to cover a new borrow. _reserve the reserve from which the user wants to borrow _amount the amount the user wants to borrow _fee the fee for the amount that the user needs to cover _userCurrentBorrowBalanceTH the current borrow balance of the user (before the borrow) _userCurrentLtv the average ltv of the user given his current collateralreturn the total amount of collateral in ETH to cover the current borrow balance + the new amount + fee /
) external view returns (uint256) { uint256 reserveDecimals = core.getReserveDecimals(_reserve); IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle()); uint256 requestedBorrowAmountETH = oracle .getAssetPrice(_reserve) .mul(_amount.add(_fee)) .div(10 ** reserveDecimals); //price is in ether //add the current already borrowed amount to the amount requested to calculate the total collateral needed. uint256 collateralNeededInETH = _userCurrentBorrowBalanceTH .add(_userCurrentFeesETH) .add(requestedBorrowAmountETH) .mul(100) .div(_userCurrentLtv); //LTV is calculated in percentage return collateralNeededInETH; }
) external view returns (uint256) { uint256 reserveDecimals = core.getReserveDecimals(_reserve); IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle()); uint256 requestedBorrowAmountETH = oracle .getAssetPrice(_reserve) .mul(_amount.add(_fee)) .div(10 ** reserveDecimals); //price is in ether //add the current already borrowed amount to the amount requested to calculate the total collateral needed. uint256 collateralNeededInETH = _userCurrentBorrowBalanceTH .add(_userCurrentFeesETH) .add(requestedBorrowAmountETH) .mul(100) .div(_userCurrentLtv); //LTV is calculated in percentage return collateralNeededInETH; }
6,909
17
// Restricted data (refernce from the VolumeRestrictionLib library )
RestrictedData holderData;
RestrictedData holderData;
18,003
32
// ------------------------------Fallback------------------------------ Fallback function: just throw an exception to stop execution.
function (){ throw; }
function (){ throw; }
10,781
98
// 33 IN DATA / SET DATA / GET DATA / STRING / PUBLIC / ONLY OWNER / CONSTANT
string inCCH_edit_33 = " une première phrase " ;
string inCCH_edit_33 = " une première phrase " ;
83,901
5
// Emitted when a transfer has its external data executed transferId - The unique identifier of the crosschain transfer. success - Whether calldata succeeded returnData - Return bytes from the IXReceiver /
event ExternalCalldataExecuted(bytes32 indexed transferId, bool success, bytes returnData);
event ExternalCalldataExecuted(bytes32 indexed transferId, bool success, bytes returnData);
29,981
5
// `value` tokens were transfered from the bank to `to`/the balance of `from` was decreased by `value`/is triggered on any successful call to `transferTokens`/from the account/contract that called `transferTokens` and/got their balance decreased by `value`/to the one that received `value` tokens from the bank/value amount of tokens that were transfered
event Transfer(address indexed from, address to, uint256 value);
event Transfer(address indexed from, address to, uint256 value);
15,056
542
// We alow anyone to withdraw these funds for the account owner
function withdrawFromMerkleTree( ExchangeData.State storage S, ExchangeData.MerkleProof calldata merkleProof ) public
function withdrawFromMerkleTree( ExchangeData.State storage S, ExchangeData.MerkleProof calldata merkleProof ) public
24,208
6
// give us the juice
IERC20(_protocolToken).transfer(address(this), _totalTokenAmount);
IERC20(_protocolToken).transfer(address(this), _totalTokenAmount);
8,859
22
// compressedData key
struct Player { address addr; // player address uint256 gen; // general vault uint256 percent; // gen percent vault }
struct Player { address addr; // player address uint256 gen; // general vault uint256 percent; // gen percent vault }
18,271
7
// create deposit
stablecoin.safeTransferFrom( _creator, address(this), _initialDepositAmount ); stablecoin.safeIncreaseAllowance(address(pool), type(uint256).max); uint256 interestAmount; (depositID, interestAmount) = pool.deposit( _initialDepositAmount, maturationTimestamp
stablecoin.safeTransferFrom( _creator, address(this), _initialDepositAmount ); stablecoin.safeIncreaseAllowance(address(pool), type(uint256).max); uint256 interestAmount; (depositID, interestAmount) = pool.deposit( _initialDepositAmount, maturationTimestamp
52,195
109
// Changes the username for a user /
function changeUsername(string memory newName) public { address sender = _msgSender(); require(validateName(newName) == true, "Not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_usernames[sender])), "New username is same as the current one"); require(isUserNameReserved(newName) == false, "Username already reserved"); ISPT(_sptAddress).transferFrom(msg.sender, _sptAddress, usernameChangePrice); // If already named, dereserve old name if (bytes(_usernames[sender]).length > 0) { toggleReserveUsername(_usernames[sender], false); } toggleReserveUsername(newName, true); _usernames[sender] = newName; emit UsernameChange(sender, newName); }
function changeUsername(string memory newName) public { address sender = _msgSender(); require(validateName(newName) == true, "Not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_usernames[sender])), "New username is same as the current one"); require(isUserNameReserved(newName) == false, "Username already reserved"); ISPT(_sptAddress).transferFrom(msg.sender, _sptAddress, usernameChangePrice); // If already named, dereserve old name if (bytes(_usernames[sender]).length > 0) { toggleReserveUsername(_usernames[sender], false); } toggleReserveUsername(newName, true); _usernames[sender] = newName; emit UsernameChange(sender, newName); }
11,150
38
// update mappings with custom token
bytes29 _tokenId = BridgeMessage.formatTokenId(_domain, _id); representationToCanonical[_custom].domain = _tokenId.domain(); representationToCanonical[_custom].id = _tokenId.id(); bytes32 _idHash = _tokenId.keccak(); canonicalToRepresentation[_idHash] = _custom;
bytes29 _tokenId = BridgeMessage.formatTokenId(_domain, _id); representationToCanonical[_custom].domain = _tokenId.domain(); representationToCanonical[_custom].id = _tokenId.id(); bytes32 _idHash = _tokenId.keccak(); canonicalToRepresentation[_idHash] = _custom;
14,614
7
// Let user to add liquidity by supplying stable coin, access: ANY/_liqudityAmount is amount of stable coin tokens to secure
function addLiquidity(uint256 _liqudityAmount) external;
function addLiquidity(uint256 _liqudityAmount) external;
55,692
12
// This function is used to send ether to winner address
function transferAmount() public payable { // check ether value should be greater than &#39;.0001&#39; require(msg.value > .0001 ether); // Check the sender address should be equal to organizer address // since the organizer can only send ether to winner require(msg.sender == organizer); // check isWinnerSelected should be &#39;true&#39; require(isWinnerSelected); // send ether to winner sendAmount(msg.value, winnerAddress); }
function transferAmount() public payable { // check ether value should be greater than &#39;.0001&#39; require(msg.value > .0001 ether); // Check the sender address should be equal to organizer address // since the organizer can only send ether to winner require(msg.sender == organizer); // check isWinnerSelected should be &#39;true&#39; require(isWinnerSelected); // send ether to winner sendAmount(msg.value, winnerAddress); }
18,190
71
// How dividends work: - A "point" is a fraction of a Wei (1e-32), it's used to reduce rounding errors. - totalPointsPerToken represents how many points each token is entitled to from all the dividends ever received. Each time a new deposit is made, it is incremented by the points oweable per token at the time of deposit: (depositAmtInWeiPOINTS_PER_WEI) / totalSupply - Each account has a `creditedPoints` and `lastPointsPerToken` - lastPointsPerToken: The value of totalPointsPerToken the last time `creditedPoints` was changed. - creditedPoints: How many points have been credited to the user. This is incremented by: (`totalPointsPerToken` - `lastPointsPerToken`balance) via `.updateCreditedPoints(account)`.
uint constant POINTS_PER_WEI = 1e32; uint public dividendsTotal; uint public dividendsCollected; uint public totalPointsPerToken; uint public totalBurned; mapping (address => uint) public creditedPoints; mapping (address => uint) public lastPointsPerToken;
uint constant POINTS_PER_WEI = 1e32; uint public dividendsTotal; uint public dividendsCollected; uint public totalPointsPerToken; uint public totalBurned; mapping (address => uint) public creditedPoints; mapping (address => uint) public lastPointsPerToken;
46,000
6
// Returns the multiplication of two unsigned integers, reverting on overflow. Counterpart to Solidity's `` operator. Requirements: - Multiplication cannot overflow./
// function mul(uint256 a, uint256 b) internal pure returns (uint256) { // // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // // benefit is lost if 'b' is also tested. // // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 // if (a == 0) { // return 0; // } // uint256 c = a * b; // require(c / a == b, "SafeMath: multiplication overflow"); // return c; // }
// 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; // }
59,142
2
// function sliceRoleMembers(bytes32 role,uint256 start,uint256 end)external view returns(address[] memory);
function getRoleAdmin( bytes32 role )external view returns( bytes32 );
function getRoleAdmin( bytes32 role )external view returns( bytes32 );
1,323
21
// Store the refund amount
refunds[lotteryId][player] = refundAmount;
refunds[lotteryId][player] = refundAmount;
29,504
44
// See {IERC721-ownerOf}. /
function ownerOf(uint256 tokenId) public view override returns (address) { return address(uint160(_packedOwnershipOf(tokenId))); }
function ownerOf(uint256 tokenId) public view override returns (address) { return address(uint160(_packedOwnershipOf(tokenId))); }
13,185
12
// Withdraw the specified amount of tokens from the gauge. And use all the resulting tokensto remove liquidity from metapool num3CrvTokens Number of 3CRV tokens to withdraw from metapool /
function _lpWithdraw(uint256 num3CrvTokens) internal override { ICurvePool curvePool = ICurvePool(platformAddress); /* The rate between coins in the metapool determines the rate at which metapool returns * tokens when doing balanced removal (remove_liquidity call). And by knowing how much 3crvLp * we want we can determine how much of OUSD we receive by removing liquidity. * * Because we are doing balanced removal we should be making profit when removing liquidity in a * pool tilted to either side. * * Important: A downside is that the Strategist / Governor needs to be * cognisant of not removing too much liquidity. And while the proposal to remove liquidity * is being voted on the pool tilt might change so much that the proposal that has been valid while * created is no longer valid. */ uint256 crvPoolBalance = metapool.balances(crvCoinIndex); /* K is multiplied by 1e36 which is used for higher precision calculation of required * metapool LP tokens. Without it the end value can have rounding errors up to precision of * 10 digits. This way we move the decimal point by 36 places when doing the calculation * and again by 36 places when we are done with it. */ uint256 k = (1e36 * metapoolLPToken.totalSupply()) / crvPoolBalance; // simplifying below to: `uint256 diff = (num3CrvTokens - 1) * k` causes loss of precision // prettier-ignore // slither-disable-next-line divide-before-multiply uint256 diff = crvPoolBalance * k - (crvPoolBalance - num3CrvTokens - 1) * k; uint256 lpToBurn = diff / 1e36; uint256 gaugeTokens = IRewardStaking(cvxRewardStakerAddress).balanceOf( address(this) ); require( lpToBurn <= gaugeTokens, string( bytes.concat( bytes("Attempting to withdraw "), bytes(Strings.toString(lpToBurn)), bytes(", metapoolLP but only "), bytes(Strings.toString(gaugeTokens)), bytes(" available.") ) ) ); // withdraw and unwrap with claim takes back the lpTokens and also collects the rewards for deposit IRewardStaking(cvxRewardStakerAddress).withdrawAndUnwrap( lpToBurn, true ); // calculate the min amount of OUSD expected for the specified amount of LP tokens uint256 minOUSDAmount = lpToBurn.mulTruncate( metapool.get_virtual_price() ) - num3CrvTokens.mulTruncate(curvePool.get_virtual_price()) - 1; // withdraw the liquidity from metapool uint256[2] memory _removedAmounts = metapool.remove_liquidity( lpToBurn, [minOUSDAmount, num3CrvTokens] ); IVault(vaultAddress).burnForStrategy(_removedAmounts[mainCoinIndex]); }
function _lpWithdraw(uint256 num3CrvTokens) internal override { ICurvePool curvePool = ICurvePool(platformAddress); /* The rate between coins in the metapool determines the rate at which metapool returns * tokens when doing balanced removal (remove_liquidity call). And by knowing how much 3crvLp * we want we can determine how much of OUSD we receive by removing liquidity. * * Because we are doing balanced removal we should be making profit when removing liquidity in a * pool tilted to either side. * * Important: A downside is that the Strategist / Governor needs to be * cognisant of not removing too much liquidity. And while the proposal to remove liquidity * is being voted on the pool tilt might change so much that the proposal that has been valid while * created is no longer valid. */ uint256 crvPoolBalance = metapool.balances(crvCoinIndex); /* K is multiplied by 1e36 which is used for higher precision calculation of required * metapool LP tokens. Without it the end value can have rounding errors up to precision of * 10 digits. This way we move the decimal point by 36 places when doing the calculation * and again by 36 places when we are done with it. */ uint256 k = (1e36 * metapoolLPToken.totalSupply()) / crvPoolBalance; // simplifying below to: `uint256 diff = (num3CrvTokens - 1) * k` causes loss of precision // prettier-ignore // slither-disable-next-line divide-before-multiply uint256 diff = crvPoolBalance * k - (crvPoolBalance - num3CrvTokens - 1) * k; uint256 lpToBurn = diff / 1e36; uint256 gaugeTokens = IRewardStaking(cvxRewardStakerAddress).balanceOf( address(this) ); require( lpToBurn <= gaugeTokens, string( bytes.concat( bytes("Attempting to withdraw "), bytes(Strings.toString(lpToBurn)), bytes(", metapoolLP but only "), bytes(Strings.toString(gaugeTokens)), bytes(" available.") ) ) ); // withdraw and unwrap with claim takes back the lpTokens and also collects the rewards for deposit IRewardStaking(cvxRewardStakerAddress).withdrawAndUnwrap( lpToBurn, true ); // calculate the min amount of OUSD expected for the specified amount of LP tokens uint256 minOUSDAmount = lpToBurn.mulTruncate( metapool.get_virtual_price() ) - num3CrvTokens.mulTruncate(curvePool.get_virtual_price()) - 1; // withdraw the liquidity from metapool uint256[2] memory _removedAmounts = metapool.remove_liquidity( lpToBurn, [minOUSDAmount, num3CrvTokens] ); IVault(vaultAddress).burnForStrategy(_removedAmounts[mainCoinIndex]); }
29,718
270
// Let it experience taxes and reflections again.
wallets[newExchanges[i]].isExcludedFromTaxAndReflections = false;
wallets[newExchanges[i]].isExcludedFromTaxAndReflections = false;
26,677