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
11
// Overflow detection/protection:
require(value/msg.value == rateMe); token.transfer(msg.sender, value);
require(value/msg.value == rateMe); token.transfer(msg.sender, value);
60,181
104
// We need to check if the contributor has made a contribution on each phase, presale and partner
Allocation storage presaleA = presaleAllocations[msg.sender]; if (presaleA.amountGranted > 0 && canClaimPresaleTokens) { amountToTransfer = amountToTransfer.add(presaleA.amountGranted); presaleA.amountGranted = 0; }
Allocation storage presaleA = presaleAllocations[msg.sender]; if (presaleA.amountGranted > 0 && canClaimPresaleTokens) { amountToTransfer = amountToTransfer.add(presaleA.amountGranted); presaleA.amountGranted = 0; }
5,780
33
// If `account` had been granted `role`, emits a {RoleRevoked} event// Requirements:/ - the caller must have ``role``'s admin role/
function revokeRole( address target, bytes32 role, address account )internal { _requireSupportsInterface(target); (bool success, ) = target.call( abi.encodeWithSignature(
function revokeRole( address target, bytes32 role, address account )internal { _requireSupportsInterface(target); (bool success, ) = target.call( abi.encodeWithSignature(
49,398
8
// Function to vote on a proposal
function vote( uint256 _proposalId, bool _approve, address nftAddress
function vote( uint256 _proposalId, bool _approve, address nftAddress
19,418
2
// Reverts if the current function context is not inside of a constructor.
modifier onlyConstructor() { if (address(this).code.length != 0) { revert OnlyConstructorError(); } _; }
modifier onlyConstructor() { if (address(this).code.length != 0) { revert OnlyConstructorError(); } _; }
31,427
1,096
// 550
entry "reverberatingly" : ENG_ADVERB
entry "reverberatingly" : ENG_ADVERB
21,386
131
// The AO set the NameTAOPosition Address _nameTAOPositionAddress The address of NameTAOPosition /
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(nameTAOPositionAddress); }
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(nameTAOPositionAddress); }
32,402
3,310
// 1656
entry "unslanted" : ENG_ADJECTIVE
entry "unslanted" : ENG_ADJECTIVE
18,268
29
// When the protocol is recollateralizing, we need to give a discount of FXS to hit the new CR target Thus, if the target collateral ratio is higher than the actual value of collateral, minters get FXS for adding collateral This function simply rewards anyone that sends collateral to a pool with the same amount of FXS + the bonus rate Anyone can call this function to recollateralize the protocol and take the extra FXS value from the bonus rate as an arb opportunity
function recollateralizeFRAX(uint256 collateral_amount, uint256 FXS_out_min) external { require(recollateralizePaused == false, "Recollateralize is paused"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); uint256 fxs_price = FRAX.fxs_price(); uint256 frax_total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); (uint256 collateral_units, uint256 amount_to_recollat) = FraxPoolLibrary.calcRecollateralizeFRAXInner( collateral_amount_d18, getCollateralPrice(), global_collat_value, frax_total_supply, global_collateral_ratio ); uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals); uint256 fxs_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate).sub(recollat_fee)).div(fxs_price); require(FXS_out_min <= fxs_paid_back, "Slippage limit reached"); TransferHelper.safeTransferFrom(address(collateral_token), msg.sender, address(this), collateral_units_precision); FXS.pool_mint(msg.sender, fxs_paid_back); }
function recollateralizeFRAX(uint256 collateral_amount, uint256 FXS_out_min) external { require(recollateralizePaused == false, "Recollateralize is paused"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); uint256 fxs_price = FRAX.fxs_price(); uint256 frax_total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); (uint256 collateral_units, uint256 amount_to_recollat) = FraxPoolLibrary.calcRecollateralizeFRAXInner( collateral_amount_d18, getCollateralPrice(), global_collat_value, frax_total_supply, global_collateral_ratio ); uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals); uint256 fxs_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate).sub(recollat_fee)).div(fxs_price); require(FXS_out_min <= fxs_paid_back, "Slippage limit reached"); TransferHelper.safeTransferFrom(address(collateral_token), msg.sender, address(this), collateral_units_precision); FXS.pool_mint(msg.sender, fxs_paid_back); }
18,665
1
// function balanceOf(address _owner, uint256 _id) external view returns (uint256);
function createAndFundMarket(address _creator, bytes32 _eventIdentifier) external; function buy(uint amount0, uint amount1, address to, bytes32 marketIdentifier) external; function sell(uint amount, address to, bytes32 marketIdentifier) external; function stakeOutcome(uint8 _for, bytes32 marketIdentifier, address to) external; function redeemWinning(address to, bytes32 marketIdentifier) external; function redeemStake(bytes32 marketIdentifier, address to) external; function setOutcome(uint8 outcome, bytes32 marketIdentifier) external; function claimOutcomeReserves(bytes32 marketIdentifier) external; function updateMarketConfig(
function createAndFundMarket(address _creator, bytes32 _eventIdentifier) external; function buy(uint amount0, uint amount1, address to, bytes32 marketIdentifier) external; function sell(uint amount, address to, bytes32 marketIdentifier) external; function stakeOutcome(uint8 _for, bytes32 marketIdentifier, address to) external; function redeemWinning(address to, bytes32 marketIdentifier) external; function redeemStake(bytes32 marketIdentifier, address to) external; function setOutcome(uint8 outcome, bytes32 marketIdentifier) external; function claimOutcomeReserves(bytes32 marketIdentifier) external; function updateMarketConfig(
49,082
3
// Constructor - accepts ETH to initialise a balance for subsequent Oraclize queries/
constructor() public payable { // Use 50 gwei for now oraclize_setCustomGasPrice(50 * 10 ** 9); }
constructor() public payable { // Use 50 gwei for now oraclize_setCustomGasPrice(50 * 10 ** 9); }
29,208
6
// contract for locking reward
IKyberRewardLocker public immutable rewardLocker;
IKyberRewardLocker public immutable rewardLocker;
25,579
4
// Mapping from vendor's EIN to Offer
mapping (uint => Offer) private offers; uint maxGiftCardId;
mapping (uint => Offer) private offers; uint maxGiftCardId;
13,525
2
// escapeContract is where the escaped tokens go
address public escapeContract; address public triage;
address public escapeContract; address public triage;
58,857
7
// Transfer index to vesting contract
IERC20(index).safeTransfer(address(vesting), indexAmount);
IERC20(index).safeTransfer(address(vesting), indexAmount);
13,135
110
// Event fired when the proxy access is revoked or unrevoked. //Create an AuthenticatedProxyaddrUser Address of user on whose behalf this proxy will act addrRegistry Address of ProxyRegistry contract which will manage this proxy /
function AuthenticatedProxy(address addrUser, ProxyRegistry addrRegistry) public { user = addrUser; registry = addrRegistry; }
function AuthenticatedProxy(address addrUser, ProxyRegistry addrRegistry) public { user = addrUser; registry = addrRegistry; }
35,319
66
// transfer tokens to company
uint256 _companyTokens = _soldTokens * companyPercent / soldPercent; issueTokens(company, _companyTokens); token.lockAddress(company, 730 days);
uint256 _companyTokens = _soldTokens * companyPercent / soldPercent; issueTokens(company, _companyTokens); token.lockAddress(company, 730 days);
70,429
12
// Percentage of collateralisation where 100% = 1e18
uint128 collateralisationRatio;
uint128 collateralisationRatio;
87,748
6
// get log2 size of epoch voucher memory range
function getEpochVoucherLog2Size() external pure returns (uint256);
function getEpochVoucherLog2Size() external pure returns (uint256);
29,803
20
// check if the total amount is within the overall capacity (ETH/DAI, from Capital Pool)
require(ICapitalPool(capitalPool).canBuyCover(helperParameters[0], currency), "GPCHK: 7");
require(ICapitalPool(capitalPool).canBuyCover(helperParameters[0], currency), "GPCHK: 7");
66,631
156
// Step 2: Hash to try and increment (outputs a hashed value, a finite EC point in G)
uint256[2] memory hPoint; (hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message);
uint256[2] memory hPoint; (hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message);
12,648
152
// Sets the collateralFactor for a marketAdmin function to set per-market collateralFactorcToken The market to set the factor onnewCollateralFactorMantissa The new collateral factor, scaled by 1e18 return uint 0=success, otherwise a failure. (See ErrorReporter for details)/
function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); }
function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); }
10,649
41
// Check if font is valid for a Renderer contract./renderer Renderer contract address./font Font to check validity of./ return true True if font is valid.
function isValidFontForRenderer(Font memory font, address renderer) public view returns (bool)
function isValidFontForRenderer(Font memory font, address renderer) public view returns (bool)
9,447
102
// Voting for multiple proposals./ids_ ids of proposals to vote for./votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override { // Check that arrays of the same length have been supplied. require(ids_.length == votes_.length); // Check that voter has enough tokens staked to vote. uint256 balance = _governingToken.stakedOf(msg.sender); uint256 weight = voteWeight(); require(balance >= weight); // Get number of votes that msg.sender has. uint256 votesCount = balance / weight; // Iterate over voted proposals. for (uint256 i = 0; i < ids_.length; i++) { uint256 id = ids_[i]; bool currentVote = votes_[i]; Proposal storage proposal = _proposals[id]; // Check that proposal hasn't been voted for by msg.sender and that it's still active. if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) { // Add votes. proposal.voterAddresses.add(msg.sender); if (currentVote) { proposal.votesFor = proposal.votesFor.add(votesCount); } else { proposal.votesAgainst = proposal.votesAgainst.add(votesCount); } proposal.votes = proposal.votes.add(1); } // Emit event that a proposal has been voted for. emit Vote(id); } }
function vote(uint256[] memory ids_, bool[] memory votes_) public override { // Check that arrays of the same length have been supplied. require(ids_.length == votes_.length); // Check that voter has enough tokens staked to vote. uint256 balance = _governingToken.stakedOf(msg.sender); uint256 weight = voteWeight(); require(balance >= weight); // Get number of votes that msg.sender has. uint256 votesCount = balance / weight; // Iterate over voted proposals. for (uint256 i = 0; i < ids_.length; i++) { uint256 id = ids_[i]; bool currentVote = votes_[i]; Proposal storage proposal = _proposals[id]; // Check that proposal hasn't been voted for by msg.sender and that it's still active. if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) { // Add votes. proposal.voterAddresses.add(msg.sender); if (currentVote) { proposal.votesFor = proposal.votesFor.add(votesCount); } else { proposal.votesAgainst = proposal.votesAgainst.add(votesCount); } proposal.votes = proposal.votes.add(1); } // Emit event that a proposal has been voted for. emit Vote(id); } }
13,280
128
// Creating piToken using underling token and router factory. _underlyingToken Token, which will be wrapped by piToken. _routerFactory Router factory, to creating router by buildRouter function. _routerArgs Router args, depends on router implementation. _name Name of piToken. _name Symbol of piToken. /
function createPiToken( address _underlyingToken, address _routerFactory, bytes memory _routerArgs, string calldata _name, string calldata _symbol
function createPiToken( address _underlyingToken, address _routerFactory, bytes memory _routerArgs, string calldata _name, string calldata _symbol
10,496
22
// Returns true iff all the details passed match the _offer.
function detailsMatch(Offer memory _offer, uint256 _epoch, uint256 _numCoupons, uint256 _totalUSDCRequiredFromSeller) public pure returns (bool) { return ( _offer.epoch == _epoch && _offer.numCoupons == _numCoupons && _offer.totalUSDCRequiredFromSeller == _totalUSDCRequiredFromSeller ); }
function detailsMatch(Offer memory _offer, uint256 _epoch, uint256 _numCoupons, uint256 _totalUSDCRequiredFromSeller) public pure returns (bool) { return ( _offer.epoch == _epoch && _offer.numCoupons == _numCoupons && _offer.totalUSDCRequiredFromSeller == _totalUSDCRequiredFromSeller ); }
30,600
4
// Part of the Governor Bravo's interface. /
function quorumVotes() public view virtual returns (uint256);
function quorumVotes() public view virtual returns (uint256);
11,975
38
// Decreases the long exposure of the hedge contract.exchangeGlobals The ExchangeGlobals. amount The amount of baseAsset to sell. /
function decreaseLong( ILyraGlobals.ExchangeGlobals memory exchangeGlobals, uint amount, uint currentBalance
function decreaseLong( ILyraGlobals.ExchangeGlobals memory exchangeGlobals, uint amount, uint currentBalance
35,742
119
// generate event
TimeLocked(address(timeLock), amount, releaseTime, wallet);
TimeLocked(address(timeLock), amount, releaseTime, wallet);
8,113
64
// function to lock team/devs/advisors tokens
function lockTeamTokens(address _beneficiary, uint256 _tokensAmount) public onlyAdmin { require(_tokensAmount.mod(2) == 0); uint256 _half = _tokensAmount.div(2); _lockTokens(address(teamAdvisorsTokensVault), false, _beneficiary, _half); _lockTokens(address(teamAdvisorsTokensVault), true, _beneficiary, _half); }
function lockTeamTokens(address _beneficiary, uint256 _tokensAmount) public onlyAdmin { require(_tokensAmount.mod(2) == 0); uint256 _half = _tokensAmount.div(2); _lockTokens(address(teamAdvisorsTokensVault), false, _beneficiary, _half); _lockTokens(address(teamAdvisorsTokensVault), true, _beneficiary, _half); }
25,243
66
// `transfer`. {sendValue} removes this limitation.IMPORTANT: because control is transferred to `recipient`, care must betaken to not create reentrancy vulnerabilities. Consider using{ReentrancyGuard} or the /
function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance");
function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance");
10,173
19
// Register caller as a candidate to be selected as keep member/ for the provided customer application./If caller is already registered it returns without any changes./_application Address of the application.
function registerMemberCandidate(address _application) external { require( candidatesPools[_application] != address(0), "No pool found for the application" ); BondedSortitionPool candidatesPool = BondedSortitionPool( candidatesPools[_application] ); address operator = msg.sender; if (!candidatesPool.isOperatorInPool(operator)) { candidatesPool.joinPool(operator); } }
function registerMemberCandidate(address _application) external { require( candidatesPools[_application] != address(0), "No pool found for the application" ); BondedSortitionPool candidatesPool = BondedSortitionPool( candidatesPools[_application] ); address operator = msg.sender; if (!candidatesPool.isOperatorInPool(operator)) { candidatesPool.joinPool(operator); } }
11,598
17
// if we have rewards, see what the address is
function extraRewards(uint256 _reward) external view returns (address);
function extraRewards(uint256 _reward) external view returns (address);
2,726
45
// Private variables
uint256 _currentLevelEth; uint256 _currentLevelPrice; uint256 _nextLevelEth; uint256 _nextLevelPrice; uint256 _firstLevelPrice; uint256 _secondLevelPrice; uint256 _thirdLevelPrice; uint256 _capLevelPrice; uint256 _currentSupply; uint256 remainig;
uint256 _currentLevelEth; uint256 _currentLevelPrice; uint256 _nextLevelEth; uint256 _nextLevelPrice; uint256 _firstLevelPrice; uint256 _secondLevelPrice; uint256 _thirdLevelPrice; uint256 _capLevelPrice; uint256 _currentSupply; uint256 remainig;
32,609
60
// Transfers ownership of the contract to a new account ('newOwner').Can only be called by the current owner. /
function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); }
function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); }
19,770
213
// return The number of ticks for this market. The number of ticks determines the possible on chain prices for Shares of the market. (e.g. A Market with 10 ticks can have prices 1-9 and a complete set will cost 10) /
function getNumTicks() public view returns (uint256) { return numTicks; }
function getNumTicks() public view returns (uint256) { return numTicks; }
31,655
87
// Safe function for depositing funds.Returns boolean for whether the deposit was successful/self The Bank instance to operate on./accountAddress The address of the account the funds should be added to./value The amount that should be added to the account.
function deposit(Bank storage self, address accountAddress, uint value) public returns (bool) { addFunds(self, accountAddress, value); return true; }
function deposit(Bank storage self, address accountAddress, uint value) public returns (bool) { addFunds(self, accountAddress, value); return true; }
17,575
23
// Withdraw tokens.
function withdraw(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); payReward(_pid); if (_amount > 0) { user.amount = user.amount - _amount; if (user.amount == 0) { stakerCount--; pool.stakerCount--; } uint256 mul = getTierMultiply(user.amount); pool.totalMultipliedSupply = pool.totalMultipliedSupply - user.multipliedAmount + (user.amount * mul) / 100; pool.tvl = pool.tvl - _amount; user.multipliedAmount = (user.amount * mul) / 100; user.rewardDebt = user.multipliedAmount * pool.accRewardPerShare / 1e12; safeStakingTokenTransfer(msg.sender, _amount); } emit Withdraw(msg.sender, _pid, _amount); }
function withdraw(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); payReward(_pid); if (_amount > 0) { user.amount = user.amount - _amount; if (user.amount == 0) { stakerCount--; pool.stakerCount--; } uint256 mul = getTierMultiply(user.amount); pool.totalMultipliedSupply = pool.totalMultipliedSupply - user.multipliedAmount + (user.amount * mul) / 100; pool.tvl = pool.tvl - _amount; user.multipliedAmount = (user.amount * mul) / 100; user.rewardDebt = user.multipliedAmount * pool.accRewardPerShare / 1e12; safeStakingTokenTransfer(msg.sender, _amount); } emit Withdraw(msg.sender, _pid, _amount); }
29,728
27
// todo
for (uint i = 0; i < proposedEdition.fieldNamesCount; i++) { if (fieldNameAlreadyPresent[proposedEdition.fieldNames[i]] == 0) { fieldNameAlreadyPresent[proposedEdition.fieldNames[i]] = fieldNamesCount; allFieldNames[fieldNamesCount] = proposedEdition.fieldNames[i]; fieldNamesCount += 1; }
for (uint i = 0; i < proposedEdition.fieldNamesCount; i++) { if (fieldNameAlreadyPresent[proposedEdition.fieldNames[i]] == 0) { fieldNameAlreadyPresent[proposedEdition.fieldNames[i]] = fieldNamesCount; allFieldNames[fieldNamesCount] = proposedEdition.fieldNames[i]; fieldNamesCount += 1; }
29,882
2
// Function to deposit Ether into this contract. Call this function along with some Ether. The balance of this contract will be automatically updated.
function deposit() public payable { }
function deposit() public payable { }
8,354
52
// Events /
event TokenRegistered(address addr, string symbol); event TokenUnregistered(address addr, string symbol);
event TokenRegistered(address addr, string symbol); event TokenUnregistered(address addr, string symbol);
37,943
124
// refund if invalid value sent.
DefinedGame memory dGame = definedGames[_index]; if (msg.value != dGame.initialPrize) { _error("Value sent does not match initialPrize."); require(msg.sender.call.value(msg.value)()); return; }
DefinedGame memory dGame = definedGames[_index]; if (msg.value != dGame.initialPrize) { _error("Value sent does not match initialPrize."); require(msg.sender.call.value(msg.value)()); return; }
38,562
277
// Mints BitMates/
function mintApe(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint BitMate"); require(numberOfTokens <= maxApePurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= maxBitMates, "Purchase would exceed max supply of BitMates"); require(bitMatePrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < maxBitMates) { _safeMint(msg.sender, mintIndex); } } }
function mintApe(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint BitMate"); require(numberOfTokens <= maxApePurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= maxBitMates, "Purchase would exceed max supply of BitMates"); require(bitMatePrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < maxBitMates) { _safeMint(msg.sender, mintIndex); } } }
77,020
21
// overriding CrowdsalevalidPurchase to add extra cap logic return true if investors can mint at the moment
function validMintPurchase(uint256 _value) internal constant returns (bool) { bool withinCap = weiRaised.add(_value) <= cap; return super.validMintPurchase(_value) && withinCap; }
function validMintPurchase(uint256 _value) internal constant returns (bool) { bool withinCap = weiRaised.add(_value) <= cap; return super.validMintPurchase(_value) && withinCap; }
3,241
2
// An external function that accepted Term Repo rollover instructions/termRepoRolloverElectionSubmission A struct containing borrower rollover instructions
function electRollover( TermRepoRolloverElectionSubmission calldata termRepoRolloverElectionSubmission ) external;
function electRollover( TermRepoRolloverElectionSubmission calldata termRepoRolloverElectionSubmission ) external;
27,963
126
// SodaVault is owned by Timelock
contract SodaVault is ERC20, Ownable { using SafeMath for uint256; uint256 constant PER_SHARE_SIZE = 1e12; mapping (address => uint256) public lockedAmount; mapping (address => mapping(uint256 => uint256)) public rewards; mapping (address => mapping(uint256 => uint256)) public debts; IStrategy[] public strategies; SodaMaster public sodaMaster; constructor (SodaMaster _sodaMaster, string memory _name, string memory _symbol) ERC20(_name, _symbol) public { sodaMaster = _sodaMaster; } function setStrategies(IStrategy[] memory _strategies) public onlyOwner { delete strategies; for (uint256 i = 0; i < _strategies.length; ++i) { strategies.push(_strategies[i]); } } function getStrategyCount() view public returns(uint count) { return strategies.length; } /// @notice Creates `_amount` token to `_to`. Must only be called by SodaPool. function mintByPool(address _to, uint256 _amount) public { require(_msgSender() == sodaMaster.pool(), "not pool"); _deposit(_amount); _updateReward(_to); if (_amount > 0) { _mint(_to, _amount); } _updateDebt(_to); } // Must only be called by SodaPool. function burnByPool(address _account, uint256 _amount) public { require(_msgSender() == sodaMaster.pool(), "not pool"); uint256 balance = balanceOf(_account); require(lockedAmount[_account] + _amount <= balance, "Vault: burn too much"); _withdraw(_amount); _updateReward(_account); _burn(_account, _amount); _updateDebt(_account); } // Must only be called by SodaBank. function transferByBank(address _from, address _to, uint256 _amount) public { require(_msgSender() == sodaMaster.bank(), "not bank"); uint256 balance = balanceOf(_from); require(lockedAmount[_from] + _amount <= balance); _claim(); _updateReward(_from); _updateReward(_to); _transfer(_from, _to, _amount); _updateDebt(_to); _updateDebt(_from); } // Any user can transfer to another user. function transfer(address _to, uint256 _amount) public override returns (bool) { uint256 balance = balanceOf(_msgSender()); require(lockedAmount[_msgSender()] + _amount <= balance, "transfer: <= balance"); _updateReward(_msgSender()); _updateReward(_to); _transfer(_msgSender(), _to, _amount); _updateDebt(_to); _updateDebt(_msgSender()); return true; } // Must only be called by SodaBank. function lockByBank(address _account, uint256 _amount) public { require(_msgSender() == sodaMaster.bank(), "not bank"); uint256 balance = balanceOf(_account); require(lockedAmount[_account] + _amount <= balance, "Vault: lock too much"); lockedAmount[_account] += _amount; } // Must only be called by SodaBank. function unlockByBank(address _account, uint256 _amount) public { require(_msgSender() == sodaMaster.bank(), "not bank"); require(_amount <= lockedAmount[_account], "Vault: unlock too much"); lockedAmount[_account] -= _amount; } // Must only be called by SodaPool. function clearRewardByPool(address _who) public { require(_msgSender() == sodaMaster.pool(), "not pool"); for (uint256 i = 0; i < strategies.length; ++i) { rewards[_who][i] = 0; } } function getPendingReward(address _who, uint256 _index) public view returns (uint256) { uint256 total = totalSupply(); if (total == 0 || _index >= strategies.length) { return 0; } uint256 value = strategies[_index].getValuePerShare(address(this)); uint256 pending = strategies[_index].pendingValuePerShare(address(this)); uint256 balance = balanceOf(_who); return balance.mul(value.add(pending)).div(PER_SHARE_SIZE).sub(debts[_who][_index]); } function _deposit(uint256 _amount) internal { for (uint256 i = 0; i < strategies.length; ++i) { strategies[i].deposit(address(this), _amount); } } function _withdraw(uint256 _amount) internal { for (uint256 i = 0; i < strategies.length; ++i) { strategies[i].withdraw(address(this), _amount); } } function _claim() internal { for (uint256 i = 0; i < strategies.length; ++i) { strategies[i].claim(address(this)); } } function _updateReward(address _who) internal { uint256 balance = balanceOf(_who); if (balance > 0) { for (uint256 i = 0; i < strategies.length; ++i) { uint256 value = strategies[i].getValuePerShare(address(this)); rewards[_who][i] = rewards[_who][i].add(balance.mul( value).div(PER_SHARE_SIZE).sub(debts[_who][i])); } } } function _updateDebt(address _who) internal { uint256 balance = balanceOf(_who); for (uint256 i = 0; i < strategies.length; ++i) { uint256 value = strategies[i].getValuePerShare(address(this)); debts[_who][i] = balance.mul(value).div(PER_SHARE_SIZE); } } }
contract SodaVault is ERC20, Ownable { using SafeMath for uint256; uint256 constant PER_SHARE_SIZE = 1e12; mapping (address => uint256) public lockedAmount; mapping (address => mapping(uint256 => uint256)) public rewards; mapping (address => mapping(uint256 => uint256)) public debts; IStrategy[] public strategies; SodaMaster public sodaMaster; constructor (SodaMaster _sodaMaster, string memory _name, string memory _symbol) ERC20(_name, _symbol) public { sodaMaster = _sodaMaster; } function setStrategies(IStrategy[] memory _strategies) public onlyOwner { delete strategies; for (uint256 i = 0; i < _strategies.length; ++i) { strategies.push(_strategies[i]); } } function getStrategyCount() view public returns(uint count) { return strategies.length; } /// @notice Creates `_amount` token to `_to`. Must only be called by SodaPool. function mintByPool(address _to, uint256 _amount) public { require(_msgSender() == sodaMaster.pool(), "not pool"); _deposit(_amount); _updateReward(_to); if (_amount > 0) { _mint(_to, _amount); } _updateDebt(_to); } // Must only be called by SodaPool. function burnByPool(address _account, uint256 _amount) public { require(_msgSender() == sodaMaster.pool(), "not pool"); uint256 balance = balanceOf(_account); require(lockedAmount[_account] + _amount <= balance, "Vault: burn too much"); _withdraw(_amount); _updateReward(_account); _burn(_account, _amount); _updateDebt(_account); } // Must only be called by SodaBank. function transferByBank(address _from, address _to, uint256 _amount) public { require(_msgSender() == sodaMaster.bank(), "not bank"); uint256 balance = balanceOf(_from); require(lockedAmount[_from] + _amount <= balance); _claim(); _updateReward(_from); _updateReward(_to); _transfer(_from, _to, _amount); _updateDebt(_to); _updateDebt(_from); } // Any user can transfer to another user. function transfer(address _to, uint256 _amount) public override returns (bool) { uint256 balance = balanceOf(_msgSender()); require(lockedAmount[_msgSender()] + _amount <= balance, "transfer: <= balance"); _updateReward(_msgSender()); _updateReward(_to); _transfer(_msgSender(), _to, _amount); _updateDebt(_to); _updateDebt(_msgSender()); return true; } // Must only be called by SodaBank. function lockByBank(address _account, uint256 _amount) public { require(_msgSender() == sodaMaster.bank(), "not bank"); uint256 balance = balanceOf(_account); require(lockedAmount[_account] + _amount <= balance, "Vault: lock too much"); lockedAmount[_account] += _amount; } // Must only be called by SodaBank. function unlockByBank(address _account, uint256 _amount) public { require(_msgSender() == sodaMaster.bank(), "not bank"); require(_amount <= lockedAmount[_account], "Vault: unlock too much"); lockedAmount[_account] -= _amount; } // Must only be called by SodaPool. function clearRewardByPool(address _who) public { require(_msgSender() == sodaMaster.pool(), "not pool"); for (uint256 i = 0; i < strategies.length; ++i) { rewards[_who][i] = 0; } } function getPendingReward(address _who, uint256 _index) public view returns (uint256) { uint256 total = totalSupply(); if (total == 0 || _index >= strategies.length) { return 0; } uint256 value = strategies[_index].getValuePerShare(address(this)); uint256 pending = strategies[_index].pendingValuePerShare(address(this)); uint256 balance = balanceOf(_who); return balance.mul(value.add(pending)).div(PER_SHARE_SIZE).sub(debts[_who][_index]); } function _deposit(uint256 _amount) internal { for (uint256 i = 0; i < strategies.length; ++i) { strategies[i].deposit(address(this), _amount); } } function _withdraw(uint256 _amount) internal { for (uint256 i = 0; i < strategies.length; ++i) { strategies[i].withdraw(address(this), _amount); } } function _claim() internal { for (uint256 i = 0; i < strategies.length; ++i) { strategies[i].claim(address(this)); } } function _updateReward(address _who) internal { uint256 balance = balanceOf(_who); if (balance > 0) { for (uint256 i = 0; i < strategies.length; ++i) { uint256 value = strategies[i].getValuePerShare(address(this)); rewards[_who][i] = rewards[_who][i].add(balance.mul( value).div(PER_SHARE_SIZE).sub(debts[_who][i])); } } } function _updateDebt(address _who) internal { uint256 balance = balanceOf(_who); for (uint256 i = 0; i < strategies.length; ++i) { uint256 value = strategies[i].getValuePerShare(address(this)); debts[_who][i] = balance.mul(value).div(PER_SHARE_SIZE); } } }
41,948
187
// File: hasWalletCap.sol
abstract contract hasWalletCap is Teams { mapping (uint256 => bool) private walletCapEnabled; mapping (uint256 => uint256) private walletMaxes; mapping (address => mapping(uint256 => uint256)) private walletMints; /** * @dev establish the inital settings of the wallet cap upon creation * @param _id token id * @param _initWalletCapStatus initial state of wallet cap * @param _initWalletMax initial state of wallet cap limit */ function setWalletCap(uint256 _id, bool _initWalletCapStatus, uint256 _initWalletMax) internal { walletCapEnabled[_id] = _initWalletCapStatus; walletMaxes[_id] = _initWalletMax; } function enableWalletCap(uint256 _id) public onlyTeamOrOwner { walletCapEnabled[_id] = true; } function disableWalletCap(uint256 _id) public onlyTeamOrOwner { walletCapEnabled[_id] = false; } function addTokenMints(uint256 _id, address _address, uint256 _amount) internal { walletMints[_address][_id] = (walletMints[_address][_id] + _amount); } /** * @dev Allow contract owner to reset the amount of tokens claimed to be minted per address * @param _id token id * @param _address address to reset counter of */ function resetMints(uint256 _id, address _address) public onlyTeamOrOwner { walletMints[_address][_id] = 0; } /** * @dev update the wallet max per wallet per token * @param _id token id * @param _newMax the new wallet max per wallet */ function setTokenWalletMax(uint256 _id, uint256 _newMax) public onlyTeamOrOwner { require(_newMax >= 1, "Token wallet max must be greater than or equal to one."); walletMaxes[_id] = _newMax; } /** * @dev Check if wallet over maximum mint * @param _id token id to query against * @param _address address in question to check if minted count exceeds max */ function canMintAmount(uint256 _id, address _address, uint256 _amount) public view returns(bool) { if(isWalletCapEnabled(_id) == false) { return true; } require(_amount >= 1, "Amount must be greater than or equal to 1"); return (currentMintCount(_id, _address) + _amount) <= tokenWalletCap(_id); } /** * @dev Get current wallet cap for token * @param _id token id to query against */ function tokenWalletCap(uint256 _id) public view returns(uint256) { return walletMaxes[_id]; } /** * @dev Check if token is enforcing wallet caps * @param _id token id to query against */ function isWalletCapEnabled(uint256 _id) public view returns(bool) { return walletCapEnabled[_id] == true; } /** * @dev Check current mint count for token and address * @param _id token id to query against * @param _address address to check mint count of */ function currentMintCount(uint256 _id, address _address) public view returns(uint256) { return walletMints[_address][_id]; } }
abstract contract hasWalletCap is Teams { mapping (uint256 => bool) private walletCapEnabled; mapping (uint256 => uint256) private walletMaxes; mapping (address => mapping(uint256 => uint256)) private walletMints; /** * @dev establish the inital settings of the wallet cap upon creation * @param _id token id * @param _initWalletCapStatus initial state of wallet cap * @param _initWalletMax initial state of wallet cap limit */ function setWalletCap(uint256 _id, bool _initWalletCapStatus, uint256 _initWalletMax) internal { walletCapEnabled[_id] = _initWalletCapStatus; walletMaxes[_id] = _initWalletMax; } function enableWalletCap(uint256 _id) public onlyTeamOrOwner { walletCapEnabled[_id] = true; } function disableWalletCap(uint256 _id) public onlyTeamOrOwner { walletCapEnabled[_id] = false; } function addTokenMints(uint256 _id, address _address, uint256 _amount) internal { walletMints[_address][_id] = (walletMints[_address][_id] + _amount); } /** * @dev Allow contract owner to reset the amount of tokens claimed to be minted per address * @param _id token id * @param _address address to reset counter of */ function resetMints(uint256 _id, address _address) public onlyTeamOrOwner { walletMints[_address][_id] = 0; } /** * @dev update the wallet max per wallet per token * @param _id token id * @param _newMax the new wallet max per wallet */ function setTokenWalletMax(uint256 _id, uint256 _newMax) public onlyTeamOrOwner { require(_newMax >= 1, "Token wallet max must be greater than or equal to one."); walletMaxes[_id] = _newMax; } /** * @dev Check if wallet over maximum mint * @param _id token id to query against * @param _address address in question to check if minted count exceeds max */ function canMintAmount(uint256 _id, address _address, uint256 _amount) public view returns(bool) { if(isWalletCapEnabled(_id) == false) { return true; } require(_amount >= 1, "Amount must be greater than or equal to 1"); return (currentMintCount(_id, _address) + _amount) <= tokenWalletCap(_id); } /** * @dev Get current wallet cap for token * @param _id token id to query against */ function tokenWalletCap(uint256 _id) public view returns(uint256) { return walletMaxes[_id]; } /** * @dev Check if token is enforcing wallet caps * @param _id token id to query against */ function isWalletCapEnabled(uint256 _id) public view returns(bool) { return walletCapEnabled[_id] == true; } /** * @dev Check current mint count for token and address * @param _id token id to query against * @param _address address to check mint count of */ function currentMintCount(uint256 _id, address _address) public view returns(uint256) { return walletMints[_address][_id]; } }
12,069
8
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
30,136
356
// /
extraRewards.add(_extraToken); rewardsTokenConfig[_extraToken] = _rewardsConfig; emit ExtraRewardsTokenSet( _extraToken, _rewardsConfig.autoCompoundingBps, _rewardsConfig.autoCompoundingPerfFee, _rewardsConfig.treeDistributionPerfFee, _rewardsConfig.tendConvertTo,
extraRewards.add(_extraToken); rewardsTokenConfig[_extraToken] = _rewardsConfig; emit ExtraRewardsTokenSet( _extraToken, _rewardsConfig.autoCompoundingBps, _rewardsConfig.autoCompoundingPerfFee, _rewardsConfig.treeDistributionPerfFee, _rewardsConfig.tendConvertTo,
8,289
12
// Total number of tokens. /
function totalSupply() public view override returns (uint256) { return totalTokenSupply; }
function totalSupply() public view override returns (uint256) { return totalTokenSupply; }
11,235
282
// Used to renounce emergency powers. Cannot be undone. /
function finalize() external onlyGovernance { finalized = true; }
function finalize() external onlyGovernance { finalized = true; }
11,920
17
// 200 LP token provider can reach 50 usdt -> direct proportion with 200&50;
uint256 rma = _tokens.mul(10 ** uint256(decimals)); require(rma > 1 * 10 ** uint256(decimals)); //minimum 1 LPtoken require require(ERC20(erushLPtoken).balanceOf(msg.sender) >= rma); require(fdetails[msg.sender]._amount == 0); ERC20(erushLPtoken).transferFrom(msg.sender, address(this), rma); uint256 myusdtincome = _tokens.mul(50).div(150); ERC20(tetherAddress).transfer(msg.sender, myusdtincome * 10 ** uint256(tetherDecimal) ); fdetails[msg.sender] = fdetailz(rma, block.number); emit NewFarmer(msg.sender, _tokens);
uint256 rma = _tokens.mul(10 ** uint256(decimals)); require(rma > 1 * 10 ** uint256(decimals)); //minimum 1 LPtoken require require(ERC20(erushLPtoken).balanceOf(msg.sender) >= rma); require(fdetails[msg.sender]._amount == 0); ERC20(erushLPtoken).transferFrom(msg.sender, address(this), rma); uint256 myusdtincome = _tokens.mul(50).div(150); ERC20(tetherAddress).transfer(msg.sender, myusdtincome * 10 ** uint256(tetherDecimal) ); fdetails[msg.sender] = fdetailz(rma, block.number); emit NewFarmer(msg.sender, _tokens);
19,111
128
// function setSafetyVars( bool _areBidsActive, bool _isInTesting, uint112 _ethBoost, address _nyanConnector
// ) public _onlyOwner delegatedOnly { // areBidsActive = _areBidsActive; // isInTesting = _isInTesting; // ethBoost = _ethBoost; // nyanConnector = _nyanConnector; // }
// ) public _onlyOwner delegatedOnly { // areBidsActive = _areBidsActive; // isInTesting = _isInTesting; // ethBoost = _ethBoost; // nyanConnector = _nyanConnector; // }
18,620
11
// _safeTransfer(t1, senderadd, amountToRepay); withdraw from TestUniswapFlashSwap contract2 to user
_safeTransfer(t1, pair, amountToRepay); //withdraw from TestUniswapFlashSwap contract2 to pair contract1
_safeTransfer(t1, pair, amountToRepay); //withdraw from TestUniswapFlashSwap contract2 to pair contract1
11,151
22
// the nonce of this validator set
uint256 valsetNonce;
uint256 valsetNonce;
45,171
223
// calulates tribute amount
uint _tribute = getTribute(_amount); walletBalance[_recipient] += _amount; walletTokenBalance[address(soul)][_recipient] = walletTokenBalance[address(soul)][_recipient] + _amount;
uint _tribute = getTribute(_amount); walletBalance[_recipient] += _amount; walletTokenBalance[address(soul)][_recipient] = walletTokenBalance[address(soul)][_recipient] + _amount;
13,346
17
// ========== PUBLIC FUNCTIONS ========== / Final balance received and penalty balance paid by user upon calling exit
function getWithdrawableBalance( address user ) public view returns ( uint256 unlockedAmount, uint256 penaltyAmount
function getWithdrawableBalance( address user ) public view returns ( uint256 unlockedAmount, uint256 penaltyAmount
1,813
133
// 0 _heroLevel produces warriors of COMMON rarity
uint256 rarityChance = _heroLevel == 0 ? RARITY_CHANCE_RANGE : _random(0, RARITY_CHANCE_RANGE, hash) / (_heroLevel * _getBonus(_heroIdentity)); // 0 - 10 000 000 uint256 rarity = _computeRarity(rarityChance, params[UNIQUE_INDEX_13],params[LEGENDARY_INDEX_14], params[MYTHIC_INDEX_15], params[RARE_INDEX_16], params[UNCOMMON_INDEX_17]); uint256 classMech;
uint256 rarityChance = _heroLevel == 0 ? RARITY_CHANCE_RANGE : _random(0, RARITY_CHANCE_RANGE, hash) / (_heroLevel * _getBonus(_heroIdentity)); // 0 - 10 000 000 uint256 rarity = _computeRarity(rarityChance, params[UNIQUE_INDEX_13],params[LEGENDARY_INDEX_14], params[MYTHIC_INDEX_15], params[RARE_INDEX_16], params[UNCOMMON_INDEX_17]); uint256 classMech;
40,784
65
// Return all city data_tokenId uint256 of token/
function getCityData (uint256 _tokenId) external view returns (address _owner, uint256 _price, uint256 _nextPrice, uint256 _payout, address _cOwner, uint256 _cPrice, uint256 _cPayout)
function getCityData (uint256 _tokenId) external view returns (address _owner, uint256 _price, uint256 _nextPrice, uint256 _payout, address _cOwner, uint256 _cPrice, uint256 _cPayout)
9,430
1
// uint public vestingEnd;
address public feeTo; address public owner;
address public feeTo; address public owner;
19,824
17
// UUPS initializer, initializes a vesting contracttoken_ address of the ERC20 token contract, non-zero, immutable treasury_ address of the wallet funding vesting contract, mutable /
function postConstruct(address token_, address treasury_) public virtual initializer { require(token_ != address(0x0)); // note we don't verify treasury is not zero and allow it to be set up later _token = token_; _treasury = treasury_; __Ownable_init(); __ReentrancyGuard_init(); }
function postConstruct(address token_, address treasury_) public virtual initializer { require(token_ != address(0x0)); // note we don't verify treasury is not zero and allow it to be set up later _token = token_; _treasury = treasury_; __Ownable_init(); __ReentrancyGuard_init(); }
39,905
38
// require(product.brandAccount != address(0));
Brand storage brand = brands[product.brandAccount];
Brand storage brand = brands[product.brandAccount];
11,084
104
// transfer to floor/liqudation insurance reserves
deltaToken.transfer(reserveVaultAddress, deltaToken.balanceOf(address(this))); // queried again in case of rounding problems
deltaToken.transfer(reserveVaultAddress, deltaToken.balanceOf(address(this))); // queried again in case of rounding problems
79,202
41
// Return the DOMAIN_SEPARATOR It's named internal to allow making it public from the contract that uses it by creating a simple view function with the desired public name, such as DOMAIN_SEPARATOR or domainSeparator. solhint-disable-next-line func-name-mixedcase
function _domainSeparator() internal view returns (bytes32) { uint256 chainId; assembly {chainId := chainid()} return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId); }
function _domainSeparator() internal view returns (bytes32) { uint256 chainId; assembly {chainId := chainid()} return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId); }
13,875
188
// Token name
string private _name;
string private _name;
23,028
14
// The price of the token is obtained through the price feed contract.tokenID The ID of the token that will take the price. return The token price of a uniform unit./
function getTokenPrice(uint256 tokenID) external view override returns (uint256)
function getTokenPrice(uint256 tokenID) external view override returns (uint256)
23,370
93
// snapshot adjusted contract balance
lastBalance = lastBalance.sub(_value);
lastBalance = lastBalance.sub(_value);
46,450
329
// executes the redirection of the interest from one address to another. immediately after redirection, the destination address will start to accrue interest._from the address from which transfer the aTokens_to the destination address/
) internal { address currentRedirectionAddress = interestRedirectionAddresses[_from]; require(_to != currentRedirectionAddress, "Interest is already redirected to the user"); //accumulates the accrued interest to the principal (uint256 previousPrincipalBalance, uint256 fromBalance, uint256 balanceIncrease, uint256 fromIndex) = cumulateBalanceInternal(_from); require(fromBalance > 0, "Interest stream can only be redirected if there is a valid balance"); //if the user is already redirecting the interest to someone, before changing //the redirection address we substract the redirected balance of the previous //recipient if(currentRedirectionAddress != address(0)){ updateRedirectedBalanceOfRedirectionAddressInternal(_from,0, previousPrincipalBalance); } //if the user is redirecting the interest back to himself, //we simply set to 0 the interest redirection address if(_to == _from) { interestRedirectionAddresses[_from] = address(0); emit InterestStreamRedirected( _from, address(0), fromBalance, balanceIncrease, fromIndex ); return; } //first set the redirection address to the new recipient interestRedirectionAddresses[_from] = _to; //adds the user balance to the redirected balance of the destination updateRedirectedBalanceOfRedirectionAddressInternal(_from,fromBalance,0); emit InterestStreamRedirected( _from, _to, fromBalance, balanceIncrease, fromIndex ); }
) internal { address currentRedirectionAddress = interestRedirectionAddresses[_from]; require(_to != currentRedirectionAddress, "Interest is already redirected to the user"); //accumulates the accrued interest to the principal (uint256 previousPrincipalBalance, uint256 fromBalance, uint256 balanceIncrease, uint256 fromIndex) = cumulateBalanceInternal(_from); require(fromBalance > 0, "Interest stream can only be redirected if there is a valid balance"); //if the user is already redirecting the interest to someone, before changing //the redirection address we substract the redirected balance of the previous //recipient if(currentRedirectionAddress != address(0)){ updateRedirectedBalanceOfRedirectionAddressInternal(_from,0, previousPrincipalBalance); } //if the user is redirecting the interest back to himself, //we simply set to 0 the interest redirection address if(_to == _from) { interestRedirectionAddresses[_from] = address(0); emit InterestStreamRedirected( _from, address(0), fromBalance, balanceIncrease, fromIndex ); return; } //first set the redirection address to the new recipient interestRedirectionAddresses[_from] = _to; //adds the user balance to the redirected balance of the destination updateRedirectedBalanceOfRedirectionAddressInternal(_from,fromBalance,0); emit InterestStreamRedirected( _from, _to, fromBalance, balanceIncrease, fromIndex ); }
15,247
9
// If `approve(from, to, amount)` fails, try to `approve(from, to, 0)` before retry.
function forceApprove( IERC20 token, address spender, uint256 value
function forceApprove( IERC20 token, address spender, uint256 value
15,430
12
// update last bet
updateBetVault(_pID); plyr_[_pID].bet = amount_.add(plyr_[_pID].bet); plyr_[_pID].token = plyr_[_pID].token.sub(amount_); plyr_[_pID].lrnd_lott = lottrnd; Rndlotty[lottrnd].rndToken = Rndlotty[lottrnd].rndToken.add(amount_); emit BetTransfer(plyr_[_pID].addr, amount_ , lottrnd);
updateBetVault(_pID); plyr_[_pID].bet = amount_.add(plyr_[_pID].bet); plyr_[_pID].token = plyr_[_pID].token.sub(amount_); plyr_[_pID].lrnd_lott = lottrnd; Rndlotty[lottrnd].rndToken = Rndlotty[lottrnd].rndToken.add(amount_); emit BetTransfer(plyr_[_pID].addr, amount_ , lottrnd);
4,185
0
// This is the subset of `IDydx.ActionType` that are supported by the bridge.
enum BridgeActionType { Deposit, // Deposit tokens into dydx account. Withdraw // Withdraw tokens from dydx account. }
enum BridgeActionType { Deposit, // Deposit tokens into dydx account. Withdraw // Withdraw tokens from dydx account. }
36,817
45
// Provides a safe ERC20.name version which returns '???' as fallback string./token The address of the ERC-20 token contract./ return (string) Token name.
function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME)); return success ? returnDataToString(data) : "???"; }
function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME)); return success ? returnDataToString(data) : "???"; }
41,791
21
// Mint longOptionTokens using the underlyingTokens received from UniswapV2 flash swap to this contract. Send underlyingTokens from this contract to the optionToken contract, then call mintOptions.
(uint256 mintedOptions, uint256 mintedRedeems) = mintOptionsWithUnderlyingBalance( IOption(optionAddress), flashLoanQuantity );
(uint256 mintedOptions, uint256 mintedRedeems) = mintOptionsWithUnderlyingBalance( IOption(optionAddress), flashLoanQuantity );
34,035
0
// Declare storage for a whitelisted addresses
mapping(address => mapping(address => mapping(bytes32 => bool))) whitelistedAddresses;
mapping(address => mapping(address => mapping(bytes32 => bool))) whitelistedAddresses;
10,033
177
// Record global and per-user data to checkpoint/_tokenId NFT token ID. No user checkpoint if 0/old_locked Pevious locked amount / end lock time for the user/new_locked New locked amount / end lock time for the user
function _checkpoint( uint _tokenId, LockedBalance memory old_locked, LockedBalance memory new_locked
function _checkpoint( uint _tokenId, LockedBalance memory old_locked, LockedBalance memory new_locked
48,104
29
// DSProxyFactory This factory deploys new proxy instances through build() Deployed proxy addresses are logged
contract DSProxyFactory { event Created(address indexed sender, address indexed owner, address proxy, address cache); mapping(address=>bool) public isProxy; DSProxyCache public cache; constructor() public { cache = new DSProxyCache(); } // deploys a new proxy instance // sets owner of proxy to caller function build() public returns (address payable proxy) { proxy = build(msg.sender); } // deploys a new proxy instance // sets custom owner of proxy function build(address owner) public returns (address payable proxy) { proxy = address(new DSProxy(address(cache))); emit Created(msg.sender, owner, address(proxy), address(cache)); DSProxy(proxy).setOwner(owner); isProxy[proxy] = true; } }
contract DSProxyFactory { event Created(address indexed sender, address indexed owner, address proxy, address cache); mapping(address=>bool) public isProxy; DSProxyCache public cache; constructor() public { cache = new DSProxyCache(); } // deploys a new proxy instance // sets owner of proxy to caller function build() public returns (address payable proxy) { proxy = build(msg.sender); } // deploys a new proxy instance // sets custom owner of proxy function build(address owner) public returns (address payable proxy) { proxy = address(new DSProxy(address(cache))); emit Created(msg.sender, owner, address(proxy), address(cache)); DSProxy(proxy).setOwner(owner); isProxy[proxy] = true; } }
18,048
4
// Factory for the deployment of EIP1167 minimal proxies /
abstract contract MinimalProxyFactory is Factory { bytes private constant _minimalProxyInitCodePrefix = hex'3d602d80600a3d3981f3_363d3d373d3d3d363d73'; bytes private constant _minimalProxyInitCodeSuffix = hex'5af43d82803e903d91602b57fd5bf3'; /** * @notice deploy an EIP1167 minimal proxy using "CREATE" opcode * @param target implementation contract to proxy * @return minimalProxy address of deployed proxy */ function _deployMinimalProxy (address target) internal returns (address minimalProxy) { return _deploy(_generateMinimalProxyInitCode(target)); } /** * @notice deploy an EIP1167 minimal proxy using "CREATE2" opcode * @dev reverts if deployment is not successful (likely because salt has already been used) * @param target implementation contract to proxy * @param salt input for deterministic address calculation * @return minimalProxy address of deployed proxy */ function _deployMinimalProxy (address target, bytes32 salt) internal returns (address minimalProxy) { return _deploy(_generateMinimalProxyInitCode(target), salt); } /** * @notice calculate the deployment address for a given target and salt * @param target implementation contract to proxy * @param salt input for deterministic address calculation * @return deployment address */ function _calculateMinimalProxyDeploymentAddress (address target, bytes32 salt) internal view returns (address) { return _calculateDeploymentAddress(keccak256(_generateMinimalProxyInitCode(target)), salt); } /** * @notice concatenate elements to form EIP1167 minimal proxy initialization code * @param target implementation contract to proxy * @return bytes memory initialization code */ function _generateMinimalProxyInitCode (address target) internal pure returns (bytes memory) { return abi.encodePacked(_minimalProxyInitCodePrefix, target, _minimalProxyInitCodeSuffix); } }
abstract contract MinimalProxyFactory is Factory { bytes private constant _minimalProxyInitCodePrefix = hex'3d602d80600a3d3981f3_363d3d373d3d3d363d73'; bytes private constant _minimalProxyInitCodeSuffix = hex'5af43d82803e903d91602b57fd5bf3'; /** * @notice deploy an EIP1167 minimal proxy using "CREATE" opcode * @param target implementation contract to proxy * @return minimalProxy address of deployed proxy */ function _deployMinimalProxy (address target) internal returns (address minimalProxy) { return _deploy(_generateMinimalProxyInitCode(target)); } /** * @notice deploy an EIP1167 minimal proxy using "CREATE2" opcode * @dev reverts if deployment is not successful (likely because salt has already been used) * @param target implementation contract to proxy * @param salt input for deterministic address calculation * @return minimalProxy address of deployed proxy */ function _deployMinimalProxy (address target, bytes32 salt) internal returns (address minimalProxy) { return _deploy(_generateMinimalProxyInitCode(target), salt); } /** * @notice calculate the deployment address for a given target and salt * @param target implementation contract to proxy * @param salt input for deterministic address calculation * @return deployment address */ function _calculateMinimalProxyDeploymentAddress (address target, bytes32 salt) internal view returns (address) { return _calculateDeploymentAddress(keccak256(_generateMinimalProxyInitCode(target)), salt); } /** * @notice concatenate elements to form EIP1167 minimal proxy initialization code * @param target implementation contract to proxy * @return bytes memory initialization code */ function _generateMinimalProxyInitCode (address target) internal pure returns (bytes memory) { return abi.encodePacked(_minimalProxyInitCodePrefix, target, _minimalProxyInitCodeSuffix); } }
22,742
27
// The Founders reward has xx% of their funds locked during the bonus period which then drip out linearly per block over 3 years.
if (block.number <= FINISH_BONUS_AT_BLOCK) { govToken.lock(address(founderaddr), GovTokenForFounders.mul(95).div(100)); }
if (block.number <= FINISH_BONUS_AT_BLOCK) { govToken.lock(address(founderaddr), GovTokenForFounders.mul(95).div(100)); }
17,127
60
// Retrieve user's locked balance.account user's account. /
function lockedBalanceOf(address /*account*/) public view returns (uint256) { delegateToViewAndReturn(); }
function lockedBalanceOf(address /*account*/) public view returns (uint256) { delegateToViewAndReturn(); }
38,256
18
// Percentage factor that represents the liquidity reserves that can't be borrowed.
uint128 public reserveFactor;
uint128 public reserveFactor;
24,361
37
// Append userAddress and relayer address at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData;
(bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData;
54,467
122
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
set._values[toDeleteIndex] = lastvalue;
3,449
46
// lib/dss-interfaces/src/dss/DaiAbstract.sol/ pragma solidity >=0.5.12; / https:github.com/makerdao/dss/blob/master/src/dai.sol
interface DaiAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function name() external view returns (string memory); function symbol() external view returns (string memory); function version() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address) external view returns (uint256); function allowance(address, address) external view returns (uint256); function nonces(address) external view returns (uint256); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external view returns (bytes32); function transfer(address, uint256) external; function transferFrom(address, address, uint256) external returns (bool); function mint(address, uint256) external; function burn(address, uint256) external; function approve(address, uint256) external returns (bool); function push(address, uint256) external; function pull(address, uint256) external; function move(address, address, uint256) external; function permit(address, address, uint256, uint256, bool, uint8, bytes32, bytes32) external; }
interface DaiAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function name() external view returns (string memory); function symbol() external view returns (string memory); function version() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address) external view returns (uint256); function allowance(address, address) external view returns (uint256); function nonces(address) external view returns (uint256); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external view returns (bytes32); function transfer(address, uint256) external; function transferFrom(address, address, uint256) external returns (bool); function mint(address, uint256) external; function burn(address, uint256) external; function approve(address, uint256) external returns (bool); function push(address, uint256) external; function pull(address, uint256) external; function move(address, address, uint256) external; function permit(address, address, uint256, uint256, bool, uint8, bytes32, bytes32) external; }
35,136
29
// Emits one {CallExecuted} event per transaction in the batch. Requirements: - the caller must have the 'executor' role. /
function executeBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == datas.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt); _beforeCall(predecessor); for (uint256 i = 0; i < targets.length; ++i) { _call(id, i, targets[i], values[i], datas[i]); }
function executeBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == datas.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt); _beforeCall(predecessor); for (uint256 i = 0; i < targets.length; ++i) { _call(id, i, targets[i], values[i], datas[i]); }
15,289
61
// Multiply the curve's generator point by a scalar. /
function multipleGeneratorByScalar(uint scalar) internal pure returns (uint, uint)
function multipleGeneratorByScalar(uint scalar) internal pure returns (uint, uint)
46,897
3
// The GOOPs token seeder
IGOOPsSeeder public seeder;
IGOOPsSeeder public seeder;
10,012
42
// Timed sale actions for public sale
uint64 publicSaleStart; uint64 publicSaleEnd;
uint64 publicSaleStart; uint64 publicSaleEnd;
37,977
109
// Adminable dYdXEIP-1967 Proxy Admin contract. /
contract Adminable { /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will revert. */ modifier onlyAdmin() { require( msg.sender == getAdmin(), "Adminable: caller is not admin" ); _; } /** * @return The EIP-1967 proxy admin */ function getAdmin() public view returns (address) { return address(uint160(uint256(Storage.load(ADMIN_SLOT)))); } }
contract Adminable { /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will revert. */ modifier onlyAdmin() { require( msg.sender == getAdmin(), "Adminable: caller is not admin" ); _; } /** * @return The EIP-1967 proxy admin */ function getAdmin() public view returns (address) { return address(uint160(uint256(Storage.load(ADMIN_SLOT)))); } }
44,074
46
// Optional functions from the ERC20 standard. /
contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } }
contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } }
2,504
58
// Manager - 2
setFeeDistributionAndStatusThreshold(2, [20, 12, 8, 4, 2], thresholds[2]);
setFeeDistributionAndStatusThreshold(2, [20, 12, 8, 4, 2], thresholds[2]);
44,508
3
// mint to the list
for (i = 0; i < amounts.length; i++) { _safeMint(recipients[i], amounts[i]); }
for (i = 0; i < amounts.length; i++) { _safeMint(recipients[i], amounts[i]); }
53,349
152
// Inverse of fee i.e., a fee divisor of 100 == 1% Three fee types Mint fee 0 or <= 2% Burn fee 0 or <= 1% Claim fee 0 <= 4% /
function setFeeDivisors( uint256 mintFeeDivisor, uint256 burnFeeDivisor, uint256 claimFeeDivisor
function setFeeDivisors( uint256 mintFeeDivisor, uint256 burnFeeDivisor, uint256 claimFeeDivisor
33,908
7
// Mints new token of specified type. quantity uint256 Number of tokens to be minted toAddress address Of token recipient/
function mint(uint256 quantity, address toAddress) public payable { require(saleLive, "PugsPuggyFactory: Sale is not live"); require(canMint(quantity), "PugsPuggyFactory: Unable to mint token"); require(msg.value >= (quantity * TOKEN_PRICE), "PugsPuggyFactory: Insufficient funds"); PugsPuggy pugsPuggy = PugsPuggy(nftAddress); for (uint256 i=0; i<quantity; i++) { pugsPuggy.mintTo(toAddress); } }
function mint(uint256 quantity, address toAddress) public payable { require(saleLive, "PugsPuggyFactory: Sale is not live"); require(canMint(quantity), "PugsPuggyFactory: Unable to mint token"); require(msg.value >= (quantity * TOKEN_PRICE), "PugsPuggyFactory: Insufficient funds"); PugsPuggy pugsPuggy = PugsPuggy(nftAddress); for (uint256 i=0; i<quantity; i++) { pugsPuggy.mintTo(toAddress); } }
7,920
114
// By storing the original value once again, a refund is triggered (see https:eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
_status = _NOT_ENTERED;
933
2
// Returns variable debt token address of asset asset The address of the underlying asset of the reservereturn varaiableDebtToken address of the asset /
function getVDebtToken(address asset) public view returns (address) { DataTypes.ReserveData memory reserveData = lendingPool.getReserveData(asset); return reserveData.variableDebtTokenAddress; }
function getVDebtToken(address asset) public view returns (address) { DataTypes.ReserveData memory reserveData = lendingPool.getReserveData(asset); return reserveData.variableDebtTokenAddress; }
31,127
6
// See {IVote} interface.
function Create_Ballot(bytes32 key, address Voters_Register_Address, bytes4 Check_Voter_Selector, uint Vote_Duration, uint Vote_Validation_Duration, uint Propositions_Number, uint Max_Winning_Propositions_Number) external override { require(Ballots[key].Creation_Timestamp == 0, "Already Existing Ballot"); if(Voters_Register_Address==address(0) || Check_Voter_Selector==bytes4(0) || Vote_Duration==0 || Max_Winning_Propositions_Number==0 ){ revert("Bad Argument Values"); }
function Create_Ballot(bytes32 key, address Voters_Register_Address, bytes4 Check_Voter_Selector, uint Vote_Duration, uint Vote_Validation_Duration, uint Propositions_Number, uint Max_Winning_Propositions_Number) external override { require(Ballots[key].Creation_Timestamp == 0, "Already Existing Ballot"); if(Voters_Register_Address==address(0) || Check_Voter_Selector==bytes4(0) || Vote_Duration==0 || Max_Winning_Propositions_Number==0 ){ revert("Bad Argument Values"); }
33,334
15
// module:user-config Delay, in number of block, between the proposal is created and the vote starts. This can be increassed toleave time for users to buy voting power, of delegate it, before the voting of a proposal starts. /
function votingDelay() public view virtual returns (uint256);
function votingDelay() public view virtual returns (uint256);
6,699
111
// First token out is the same as borrowTokenOut
token0Out[0] = borrowToken0; address token0 = IUniswapV2Pair(pairs[0]).token0(); address token1 = IUniswapV2Pair(pairs[0]).token1(); if(msg.sender != owner()) { require(token0 != CORE && token1 != CORE, "FA Controller: CORE strategies can be only added by an admin"); }
token0Out[0] = borrowToken0; address token0 = IUniswapV2Pair(pairs[0]).token0(); address token1 = IUniswapV2Pair(pairs[0]).token1(); if(msg.sender != owner()) { require(token0 != CORE && token1 != CORE, "FA Controller: CORE strategies can be only added by an admin"); }
35,939
3
// stakes tokens according to the vesting schedule this function will be invoked from receiveApproval SOV.approveAndCall -> this.receiveApproval -> this.stakeTokensWithApproval _sender the sender of SOV.approveAndCall _amount the amount of tokens to stake/
function stakeTokensWithApproval(address _sender, uint256 _amount) public onlyThisContract { _stakeTokens(_sender, _amount); }
function stakeTokensWithApproval(address _sender, uint256 _amount) public onlyThisContract { _stakeTokens(_sender, _amount); }
51,377
262
// // Set the deposit paused flag to true to prevent rebasing. /
function pauseRebase() external onlyGovernorOrStrategist { rebasePaused = true; emit RebasePaused(); }
function pauseRebase() external onlyGovernorOrStrategist { rebasePaused = true; emit RebasePaused(); }
25,988