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
142
// lock info
mapping(address=>lockInfo) public balanceOf;
mapping(address=>lockInfo) public balanceOf;
50,964
46
// 0.001ratio
uint256 threshold = _ratio.div(1000); require(newRatio < _ratio.add(threshold) || newRatio > _ratio.sub(threshold), "New ratio should be in limits"); _ratio = newRatio; emit RatioUpdate(_ratio);
uint256 threshold = _ratio.div(1000); require(newRatio < _ratio.add(threshold) || newRatio > _ratio.sub(threshold), "New ratio should be in limits"); _ratio = newRatio; emit RatioUpdate(_ratio);
23,270
23
// At any given moment, returns the uid for the active claim condition.
function getIndexOfActiveCondition() public view returns (uint256) { uint256 totalConditionCount = claimConditions.totalConditionCount; require(totalConditionCount > 0, "no public mint condition."); for (uint256 i = totalConditionCount; i > 0; i -= 1) { if (block.timestamp >= claimConditions.claimConditionAtIndex[i - 1].startTimestamp) { return i - 1; } } revert("no active mint condition."); }
function getIndexOfActiveCondition() public view returns (uint256) { uint256 totalConditionCount = claimConditions.totalConditionCount; require(totalConditionCount > 0, "no public mint condition."); for (uint256 i = totalConditionCount; i > 0; i -= 1) { if (block.timestamp >= claimConditions.claimConditionAtIndex[i - 1].startTimestamp) { return i - 1; } } revert("no active mint condition."); }
28,261
8
// generic uniswap V1 token to ETH swap
(bool success, bytes memory mem ) = _uniPool.call(abi.encodeWithSignature("getTokenToEthInputPrice(uint256)", _amount)); require( success); uint256 ERC20EthRatio = bytesToUint256(mem); uint min_Tokens = SafeMath.div(SafeMath.mul(ERC20EthRatio,10),100); uint deadLineToConvert = SafeMath.add(now,1800); //wait 30min max (bool success2, ) = _uniPool.call(abi.encodeWithSignature("tokenToEthSwapInput(uint256,uint256,uint256)",_amount , min_Tokens,deadLineToConvert)); require(success2, "ERC20 to ETH swap failed!");
(bool success, bytes memory mem ) = _uniPool.call(abi.encodeWithSignature("getTokenToEthInputPrice(uint256)", _amount)); require( success); uint256 ERC20EthRatio = bytesToUint256(mem); uint min_Tokens = SafeMath.div(SafeMath.mul(ERC20EthRatio,10),100); uint deadLineToConvert = SafeMath.add(now,1800); //wait 30min max (bool success2, ) = _uniPool.call(abi.encodeWithSignature("tokenToEthSwapInput(uint256,uint256,uint256)",_amount , min_Tokens,deadLineToConvert)); require(success2, "ERC20 to ETH swap failed!");
29,650
53
// Exclude owner from fees and limits.
_isExludedFromTx[owner()] = true; excludeAccount(owner());
_isExludedFromTx[owner()] = true; excludeAccount(owner());
20,373
10
// MadicineD_P /
contract MadicineD_P { /// @notice address Owner; enum packageStatus { atcreator, picked, delivered} /// @notice address batchid; /// @notice address sender; /// @notice address shipper; /// @notice address receiver; /// @notice packageStatus status; constructor( address BatchID, address Sender, address Shipper, address Receiver ) public { Owner = Sender; batchid = BatchID; sender = Sender; shipper = Shipper; receiver = Receiver; status = packageStatus(0); } function pickDP( address BatchID, address Shipper ) public { require( Shipper == shipper, "Only Associated shipper can call this function." ); status = packageStatus(1); Madicine(BatchID).sendDP( receiver, sender ); } function recieveDP( address BatchID, address Receiver ) public { require( Receiver == receiver, "Only Associated receiver can call this function." ); status = packageStatus(2); Madicine(BatchID).recievedDP( Receiver ); } function getBatchIDStatus() public view returns( uint ) { return uint(status); } }
contract MadicineD_P { /// @notice address Owner; enum packageStatus { atcreator, picked, delivered} /// @notice address batchid; /// @notice address sender; /// @notice address shipper; /// @notice address receiver; /// @notice packageStatus status; constructor( address BatchID, address Sender, address Shipper, address Receiver ) public { Owner = Sender; batchid = BatchID; sender = Sender; shipper = Shipper; receiver = Receiver; status = packageStatus(0); } function pickDP( address BatchID, address Shipper ) public { require( Shipper == shipper, "Only Associated shipper can call this function." ); status = packageStatus(1); Madicine(BatchID).sendDP( receiver, sender ); } function recieveDP( address BatchID, address Receiver ) public { require( Receiver == receiver, "Only Associated receiver can call this function." ); status = packageStatus(2); Madicine(BatchID).recievedDP( Receiver ); } function getBatchIDStatus() public view returns( uint ) { return uint(status); } }
20,569
105
// Return the permissions flag that are associated with this modulereturn bytes32 array /
function getPermissions() public view returns(bytes32[]) { bytes32[] memory allPermissions = new bytes32[](2); allPermissions[0] = DISTRIBUTE; allPermissions[1] = MANAGE; return allPermissions; }
function getPermissions() public view returns(bytes32[]) { bytes32[] memory allPermissions = new bytes32[](2); allPermissions[0] = DISTRIBUTE; allPermissions[1] = MANAGE; return allPermissions; }
47,608
0
// ===================================================================== EVENTS =====================================================================
event LogStakedTokens(address indexed projectAddress, uint256 tokens, uint256 weiChange, address staker, bool staked); event LogUnstakedTokens(address indexed projectAddress, uint256 tokens, uint256 weiChange, address unstaker); event LogValidateTask(address indexed projectAddress, uint256 validationFee, bool validationState, uint256 taskIndex, address validator); event LogRewardValidator(address indexed projectAddress, uint256 index, uint256 weiReward, uint256 returnAmount, address validator); event LogTokenVoteCommitted(address indexed projectAddress, uint256 index, uint256 votes, bytes32 secretHash, uint256 pollId, address voter); event LogTokenVoteRevealed(address indexed projectAddress, uint256 index, uint256 voteOption, uint256 salt, address voter); event LogTokenVoteRescued(address indexed projectAddress, uint256 index, uint256 pollId, address voter); event LogRewardOriginator(address projectAddress);
event LogStakedTokens(address indexed projectAddress, uint256 tokens, uint256 weiChange, address staker, bool staked); event LogUnstakedTokens(address indexed projectAddress, uint256 tokens, uint256 weiChange, address unstaker); event LogValidateTask(address indexed projectAddress, uint256 validationFee, bool validationState, uint256 taskIndex, address validator); event LogRewardValidator(address indexed projectAddress, uint256 index, uint256 weiReward, uint256 returnAmount, address validator); event LogTokenVoteCommitted(address indexed projectAddress, uint256 index, uint256 votes, bytes32 secretHash, uint256 pollId, address voter); event LogTokenVoteRevealed(address indexed projectAddress, uint256 index, uint256 voteOption, uint256 salt, address voter); event LogTokenVoteRescued(address indexed projectAddress, uint256 index, uint256 pollId, address voter); event LogRewardOriginator(address projectAddress);
38,306
14
// /
PRINCIPAL_TOKEN.safeTransferFrom(msg.sender, address(this), _amount); PRINCIPAL_TOKEN.approve(address(CUSTOM_TREASURY), _amount); CUSTOM_TREASURY.deposit(address(PRINCIPAL_TOKEN), _amount, payout); if (fee != 0) { // fee is transferred to dao PAYOUT_TOKEN.transfer(OLY_TREASURY, fee); }
PRINCIPAL_TOKEN.safeTransferFrom(msg.sender, address(this), _amount); PRINCIPAL_TOKEN.approve(address(CUSTOM_TREASURY), _amount); CUSTOM_TREASURY.deposit(address(PRINCIPAL_TOKEN), _amount, payout); if (fee != 0) { // fee is transferred to dao PAYOUT_TOKEN.transfer(OLY_TREASURY, fee); }
6,630
10
// Activates preparation status/ return Bool flag indicating that preparation status has been successfully activated
function startPreparation() external returns (bool) { requireMaster(msg.sender); require(upgradeStatus == UpgradeStatus.NoticePeriod, "ugp11"); // ugp11 - unable to activate preparation status in case of not active notice period status if (block.timestamp >= noticePeriodFinishTimestamp) { upgradeStatus = UpgradeStatus.Preparation; emit PreparationStart(versionId); return true; } else { return false; } }
function startPreparation() external returns (bool) { requireMaster(msg.sender); require(upgradeStatus == UpgradeStatus.NoticePeriod, "ugp11"); // ugp11 - unable to activate preparation status in case of not active notice period status if (block.timestamp >= noticePeriodFinishTimestamp) { upgradeStatus = UpgradeStatus.Preparation; emit PreparationStart(versionId); return true; } else { return false; } }
35,377
30
// Add an address to the whitelist or update the rate of an already added address.This function cannot be used to reset a previously set custom rate. Remove the address and add itagain if you need to do that. _address Address to whitelist _rate Optional custom rate reserved for that address (0 = use default rate)return true if the address was added to the whitelist, false if the address was already in the whitelist /
function addAddressToWhitelist(address _address, uint256 _rate) onlyOwner public returns (bool success) { require(_address != address(0)); success = false; if (!whitelistedAddresses[_address]) { whitelistedAddresses[_address] = true; success = true; } if (_rate != 0) { whitelistedRates[_address] = _rate; } }
function addAddressToWhitelist(address _address, uint256 _rate) onlyOwner public returns (bool success) { require(_address != address(0)); success = false; if (!whitelistedAddresses[_address]) { whitelistedAddresses[_address] = true; success = true; } if (_rate != 0) { whitelistedRates[_address] = _rate; } }
59,347
11
// create a sale of tokens._token - must be an ERC20 token_rate - how many token units a buyer gets per wei. The rate is the conversion between wei and the smallest and indivisible token unit. So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK 1 wei will give you 1 unit, or 0.001 TOK._addedTokens - the number of tokens to add to the sale
function createSale(iERC20 token, uint256 rate, uint256 addedTokens) public { uint currentSaleAmount = saleAmounts[msg.sender][token]; if(addedTokens > 0 || currentSaleAmount > 0) { saleRates[msg.sender][token] = rate; } if (addedTokens > 0) { saleAmounts[msg.sender][token] = currentSaleAmount.add(addedTokens); token.transferFrom(msg.sender, address(this), addedTokens); } }
function createSale(iERC20 token, uint256 rate, uint256 addedTokens) public { uint currentSaleAmount = saleAmounts[msg.sender][token]; if(addedTokens > 0 || currentSaleAmount > 0) { saleRates[msg.sender][token] = rate; } if (addedTokens > 0) { saleAmounts[msg.sender][token] = currentSaleAmount.add(addedTokens); token.transferFrom(msg.sender, address(this), addedTokens); } }
8,099
4
// Function to register tradingContracts as premium. Only gold tier users can invest in premium algorithms.
function setPremium(address[] calldata addresses) external onlyOwner { for(uint i=0; i < addresses.length; i++) { isTradingContractPremium[addresses[i]] = true; emit AddPremium(addresses[i]); } }
function setPremium(address[] calldata addresses) external onlyOwner { for(uint i=0; i < addresses.length; i++) { isTradingContractPremium[addresses[i]] = true; emit AddPremium(addresses[i]); } }
6,803
38
// Ensure the token exists
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
20,515
255
// emit Transfer(from, to, nftIndex);
emit Collect(originAddress, destinationAddress, nftIndex);
emit Collect(originAddress, destinationAddress, nftIndex);
2,454
308
// uint256 totalWeight = tokenMoveWeight + tokenMoveEthLPWeight;
uint256 totalShares = totalStakedMove.mul(tokenMoveWeight).add(totalStakedMoveEthLP.mul(tokenMoveEthLPWeight)); uint256 bonusPortionMove = bonusPortion.mul(totalStakedMove).mul(tokenMoveWeight).div(totalShares); uint256 bonusPortionMoveEthLP = bonusPortion.sub(bonusPortionMove); if (totalStakedMove > 0) { accBonusPerShareMove = accBonusPerShareMove.add(bonusPortionMove.mul(1e24).div(totalStakedMove)); }
uint256 totalShares = totalStakedMove.mul(tokenMoveWeight).add(totalStakedMoveEthLP.mul(tokenMoveEthLPWeight)); uint256 bonusPortionMove = bonusPortion.mul(totalStakedMove).mul(tokenMoveWeight).div(totalShares); uint256 bonusPortionMoveEthLP = bonusPortion.sub(bonusPortionMove); if (totalStakedMove > 0) { accBonusPerShareMove = accBonusPerShareMove.add(bonusPortionMove.mul(1e24).div(totalStakedMove)); }
67,675
14
// Returns the protocol fees of the Liquidity Book Pairreturn protocolFeeX The protocol fees of token Xreturn protocolFeeY The protocol fees of token Y /
function getProtocolFees() external view override returns (uint128 protocolFeeX, uint128 protocolFeeY) { (protocolFeeX, protocolFeeY) = _protocolFees.decode(); }
function getProtocolFees() external view override returns (uint128 protocolFeeX, uint128 protocolFeeY) { (protocolFeeX, protocolFeeY) = _protocolFees.decode(); }
28,577
218
// Deposit LP tokens to FarmingBad for METH allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accMETHPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeMethTransfer(msg.sender, pending); } } if(_amount > 0) { uint256 _taxAmount = _amount.mul(DEV_TAX).div(100); _amount = _amount.sub(_taxAmount); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); pool.lpToken.safeTransferFrom(address(msg.sender), address(devaddr), _taxAmount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accMETHPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accMETHPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeMethTransfer(msg.sender, pending); } } if(_amount > 0) { uint256 _taxAmount = _amount.mul(DEV_TAX).div(100); _amount = _amount.sub(_taxAmount); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); pool.lpToken.safeTransferFrom(address(msg.sender), address(devaddr), _taxAmount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accMETHPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
38,094
192
// Check whether the given staker is staked staker Staker address to checkreturn True or False for whether the staker was staked /
function isStaked(address staker) external view returns (bool);
function isStaked(address staker) external view returns (bool);
66,796
22
// For calculating the taker bet amount w.r.t the maker bet odds and bet amount. oddsOdds for the bet. dirdirection for which the required amount is being calculated. makerBetAmountmaker bet amount.returnfillerAmounttaker bet amount. /
function getTakerBetAmount( uint256 odds, ForOrAgainst dir, uint256 makerBetAmount
function getTakerBetAmount( uint256 odds, ForOrAgainst dir, uint256 makerBetAmount
23,604
3
// division by zero is ignored and returns zero
function div(uint256 x, uint256 y) pure internal returns (uint256 z) { z = y > 0 ? x / y : 0; }
function div(uint256 x, uint256 y) pure internal returns (uint256 z) { z = y > 0 ? x / y : 0; }
54,430
49
// internalCalc(_arg1);
state = State.Closed; benWallet=_beneficiary;
state = State.Closed; benWallet=_beneficiary;
32,496
102
// Internal view function to check whether the caller is the currentrole holder. role The role to check for. Permitted roles are transferrer (0) andpauser (1).return A boolean indicating if the caller has the specified role. /
function _isRole(Role role) internal view returns (bool hasRole) { hasRole = msg.sender == _roles[uint256(role)].account; }
function _isRole(Role role) internal view returns (bool hasRole) { hasRole = msg.sender == _roles[uint256(role)].account; }
11,654
26
// case where player lose
else {
else {
9,595
21
// Deactivates a reserve asset The address of the underlying asset of the reserve /
function deactivateReserve(address asset) external onlyPoolAdmin { _checkNoLiquidity(asset); DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setActive(false); pool.setConfiguration(asset, currentConfig.data); emit ReserveDeactivated(asset); }
function deactivateReserve(address asset) external onlyPoolAdmin { _checkNoLiquidity(asset); DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setActive(false); pool.setConfiguration(asset, currentConfig.data); emit ReserveDeactivated(asset); }
19,751
4
// Chainlink variables Fee: defaulted to 0.1 LINK on Rinkeby (varies by network), set during constructor KeyHash: must be set during constructor (varies by network) /
bytes32 internal keyHash; uint256 internal fee = 0.1 * 10**18;
bytes32 internal keyHash; uint256 internal fee = 0.1 * 10**18;
58,194
27
// make sure there is a licence here
require(repository[hash].licences[buyer].status != Status.None); repository[hash].licences[buyer].status = Status.Invalidated; emit LogLicenceInvalidated(buyer, hash);
require(repository[hash].licences[buyer].status != Status.None); repository[hash].licences[buyer].status = Status.Invalidated; emit LogLicenceInvalidated(buyer, hash);
6,131
2
// 242-1
uint256 garbageNum = 4398046511103; uint8 str = (dna & garbageNum) % 6 - 2; tmp = tmp >> 42; uint8 dex = (dna & garbageNum) % 6 - 2; tmp = tmp >> 42; uint8 const = (dna & garbageNum) % 6 - 2; tmp = tmp >> 42; uint8 intel = (dna & garbageNum) % 6 - 2; tmp = tmp >> 42;
uint256 garbageNum = 4398046511103; uint8 str = (dna & garbageNum) % 6 - 2; tmp = tmp >> 42; uint8 dex = (dna & garbageNum) % 6 - 2; tmp = tmp >> 42; uint8 const = (dna & garbageNum) % 6 - 2; tmp = tmp >> 42; uint8 intel = (dna & garbageNum) % 6 - 2; tmp = tmp >> 42;
48,319
11
// A constant role name for indicating admins. /
string public constant ROLE_ADMIN = "admin";
string public constant ROLE_ADMIN = "admin";
45,784
9
// Note that supplied and borrowed are in 18 decimals while DAI USDC ratio is in 6 decimals
return (supplied, borrowed, ratio);
return (supplied, borrowed, ratio);
8,844
43
// closure handler /
function finished() public { //When finished, eth are transfered to beneficiary //Only on sucess require(state == State.Successful, "Wrong Stage"); uint256 remanent = tokenReward.balanceOf(address(this)); require(tokenReward.transfer(beneficiary, remanent), "Transfer could not be made"); beneficiary.transfer(address(this).balance); emit LogBeneficiaryPaid(beneficiary); }
function finished() public { //When finished, eth are transfered to beneficiary //Only on sucess require(state == State.Successful, "Wrong Stage"); uint256 remanent = tokenReward.balanceOf(address(this)); require(tokenReward.transfer(beneficiary, remanent), "Transfer could not be made"); beneficiary.transfer(address(this).balance); emit LogBeneficiaryPaid(beneficiary); }
38,267
49
// capture the contract's current ETH balance. this is so that we can capture exactly the amount of ETH that the swap creates, and not make the liquidity event include any ETH that has been manually sent to the contract
uint256 initialBalance = address(this).balance;
uint256 initialBalance = address(this).balance;
26,333
545
// Computes the index of the lowest bit set in 'self'. Returns the lowest bit set as an 'uint8'. Requires that 'self != 0'.
function lowestBitSet(uint self) internal pure returns (uint8 lowest) { require(self != 0); uint val = self; for (uint8 i = 128; i >= 1; i >>= 1) { if (val & (ONE << i) - 1 == 0) { lowest += i; val >>= i; } } }
function lowestBitSet(uint self) internal pure returns (uint8 lowest) { require(self != 0); uint val = self; for (uint8 i = 128; i >= 1; i >>= 1) { if (val & (ONE << i) - 1 == 0) { lowest += i; val >>= i; } } }
20,407
15
// Getter functions
function getPendingStatus(address _candidate) public view returns(bool) { return s_pending[_candidate]; }
function getPendingStatus(address _candidate) public view returns(bool) { return s_pending[_candidate]; }
16,501
24
// remaining x is not enough to down current price to price / 1.0001 but x may remain, so we cannot simply use (costX == amountX)
retState.finished = true; retState.finalPt = currentState.currentPoint; retState.sqrtFinalPrice_96 = currentState.sqrtPrice_96;
retState.finished = true; retState.finalPt = currentState.currentPoint; retState.sqrtFinalPrice_96 = currentState.sqrtPrice_96;
30,505
4
// update the balance of a type provided in _binBalances_binBalances Uint256 containing the balances of objects_index Index of the object in the provided bin_amount Value to update the type balance_operation Which operation to conduct : Operations.REPLACE : Replace type balance with _amount Operations.ADD : ADD _amount to type balance Operations.SUB : Substract _amount from type balance/
function updateTokenBalance( uint256 _binBalances, uint256 _index, uint256 _amount, Operations _operation) internal pure returns (uint256 newBinBalance)
function updateTokenBalance( uint256 _binBalances, uint256 _index, uint256 _amount, Operations _operation) internal pure returns (uint256 newBinBalance)
30,208
377
// setEnableWpcClaim /
function _setEnableWpcClaim(bool state) public onlyOwner { enableWpcClaim = state; emit EnableWpcClaim("EnableWpcClaim", state); }
function _setEnableWpcClaim(bool state) public onlyOwner { enableWpcClaim = state; emit EnableWpcClaim("EnableWpcClaim", state); }
8,499
10
// Where we get paid
balance += (msg.value);
balance += (msg.value);
18,602
282
// process the withdraw part of the reallocation process the deposit and the withdrawal part of the users deposits/withdrawals
_processWithdraw( withdrawData, allStrategies, spotPrices );
_processWithdraw( withdrawData, allStrategies, spotPrices );
34,758
425
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
44,113
135
// Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
2,785
98
// oldestSessionId /
function oldestSessionId() public override view returns (uint256) { return oldestSessionId_; }
function oldestSessionId() public override view returns (uint256) { return oldestSessionId_; }
47,363
196
// The bonding curve rate must be between 0 and 200.
require( _metadata.bondingCurveRate <= 200, "TerminalV1::_validateAndPackFundingCycleMetadata: BAD_BONDING_CURVE_RATE" );
require( _metadata.bondingCurveRate <= 200, "TerminalV1::_validateAndPackFundingCycleMetadata: BAD_BONDING_CURVE_RATE" );
28,604
239
// Only for bonus logic contract
modifier onlyContract(){ require(_voteFactory.checkAddress("nest.v3.tokenAbonus") == address(msg.sender), "No authority"); _; }
modifier onlyContract(){ require(_voteFactory.checkAddress("nest.v3.tokenAbonus") == address(msg.sender), "No authority"); _; }
24,942
26
// get contracts balance
uint balance = token.balanceOf(this);
uint balance = token.balanceOf(this);
49,247
81
// Destroys `amount` tokens from `account`, decreasing thetotal supply.
* See {_burn}. * * Requirements * * - `msg.sender` must be the bridge contract. */ function burnFrom(address account, uint256 amount) external onlyBridge returns (bool) { _burn(account, amount); return true; }
* See {_burn}. * * Requirements * * - `msg.sender` must be the bridge contract. */ function burnFrom(address account, uint256 amount) external onlyBridge returns (bool) { _burn(account, amount); return true; }
14,147
51
// coordinator
DependLike_3(coordinator).depend("reserve", reserve); DependLike_3(coordinator).depend("seniorTranche", seniorTranche); DependLike_3(coordinator).depend("juniorTranche", juniorTranche); DependLike_3(coordinator).depend("assessor", assessor);
DependLike_3(coordinator).depend("reserve", reserve); DependLike_3(coordinator).depend("seniorTranche", seniorTranche); DependLike_3(coordinator).depend("juniorTranche", juniorTranche); DependLike_3(coordinator).depend("assessor", assessor);
52,465
28
// 86400 = 1 day, lets put 1 day at 1% of balance
require(ingameBalances[msg.sender] > time/100); protectionTime[msg.sender] = endTime; ingameBalances[msg.sender] -= ingameBalances[msg.sender]*time/100;
require(ingameBalances[msg.sender] > time/100); protectionTime[msg.sender] = endTime; ingameBalances[msg.sender] -= ingameBalances[msg.sender]*time/100;
16,018
73
// ========== STATE VARIABLES ========== // Stores balances and allowances. // Other ERC20 fields. /
) public Owned(_owner) Proxyable(_proxy) { tokenState = _tokenState; name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; }
) public Owned(_owner) Proxyable(_proxy) { tokenState = _tokenState; name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; }
2,429
24
// withdraw underlying from vault
uint256 underlyingToRecipientBeforeFees = _getWithdrawAmountByShares(_share); uint256 fee = _getWithdrawFee(underlyingToRecipientBeforeFees); uint256 underlyingToRecipientAfterFees = underlyingToRecipientBeforeFees.sub(fee); require(underlyingToRecipientBeforeFees <= _balance(), 'O8');
uint256 underlyingToRecipientBeforeFees = _getWithdrawAmountByShares(_share); uint256 fee = _getWithdrawFee(underlyingToRecipientBeforeFees); uint256 underlyingToRecipientAfterFees = underlyingToRecipientBeforeFees.sub(fee); require(underlyingToRecipientBeforeFees <= _balance(), 'O8');
30,554
164
// Gets actual rate from the vat
(, uint256 rate, , , ) = vat.ilks(ilk);
(, uint256 rate, , , ) = vat.ilks(ilk);
53,597
42
// Move amount from timeSlotToAmountBonded to debit
uint256 timeSlot = getTimeSlot(transferBond.createdAt); uint256 bondAmount = getBondForTransferAmount(originalAmount); address bonder = transferBond.bonder; timeSlotToAmountBonded[timeSlot][bonder] = timeSlotToAmountBonded[timeSlot][bonder].sub(bondAmount); _addDebit(transferBond.bonder, bondAmount);
uint256 timeSlot = getTimeSlot(transferBond.createdAt); uint256 bondAmount = getBondForTransferAmount(originalAmount); address bonder = transferBond.bonder; timeSlotToAmountBonded[timeSlot][bonder] = timeSlotToAmountBonded[timeSlot][bonder].sub(bondAmount); _addDebit(transferBond.bonder, bondAmount);
50,552
18
// check to see that item is checked out to msg.sender and the status is "Approve" allow user to add a comment (but no other updates)
WorkflowEngine.WorkItem memory item = wfe.getItem(id); item.status = "Rejected"; item.team = "None"; wfe.setItem(id, item); addComment(id, comment); wfe.checkIn(id, msg.sender);
WorkflowEngine.WorkItem memory item = wfe.getItem(id); item.status = "Rejected"; item.team = "None"; wfe.setItem(id, item); addComment(id, comment); wfe.checkIn(id, msg.sender);
20,869
146
// Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.The call is not executed if the target address is not a contract.from address representing the previous owner of the given token ID to target address that will receive the tokens tokenId uint ID of the token to be transferred _data bytes optional data to send along with the callreturn bool whether the call correctly returned the expected magic value /
function _checkOnERC721Received( address from, address to, uint tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(),
function _checkOnERC721Received( address from, address to, uint tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(),
8,973
211
// Create a new royalty stage if it's possible on each mint/transferUsed when tokens are transferred /
function _tryToChangeRoyaltyStage() internal { if (canChangeRoyaltyStage()) { _nextRoyaltyStage(); } }
function _tryToChangeRoyaltyStage() internal { if (canChangeRoyaltyStage()) { _nextRoyaltyStage(); } }
30,146
130
// Address values
self.claimData.claimedBy = _addressValues[0]; self.meta.createdBy = _addressValues[1]; self.meta.owner = _addressValues[2]; self.paymentData.feeRecipient = _addressValues[3]; self.paymentData.bountyBenefactor = _addressValues[4]; self.txnData.toAddress = _addressValues[5];
self.claimData.claimedBy = _addressValues[0]; self.meta.createdBy = _addressValues[1]; self.meta.owner = _addressValues[2]; self.paymentData.feeRecipient = _addressValues[3]; self.paymentData.bountyBenefactor = _addressValues[4]; self.txnData.toAddress = _addressValues[5];
10,874
2
// Checks if there is a verifier for the given tree depth./depth: Depth of the tree.
modifier onlySupportedDepth(uint8 depth) { require(address(verifiers[depth]) != address(0), "Interep: tree depth is not supported"); _; }
modifier onlySupportedDepth(uint8 depth) { require(address(verifiers[depth]) != address(0), "Interep: tree depth is not supported"); _; }
9,566
13
// Secondary A Secondary contract can only be used by its primary account (the one that created it) /
contract Secondary { address private _primary; event PrimaryTransferred( address recipient ); /** * @dev Sets the primary account to the one that is creating the Secondary contract. */ constructor () internal { _primary = msg.sender; emit PrimaryTransferred(_primary); } /** * @dev Reverts if called from any account other than the primary. */ modifier onlyPrimary() { require(msg.sender == _primary); _; } /** * @return the address of the primary. */ function primary() public view returns (address) { return _primary; } /** * @dev Transfers contract to a new primary. * @param recipient The address of new primary. */ function transferPrimary(address recipient) public onlyPrimary { require(recipient != address(0)); _primary = recipient; emit PrimaryTransferred(_primary); } }
contract Secondary { address private _primary; event PrimaryTransferred( address recipient ); /** * @dev Sets the primary account to the one that is creating the Secondary contract. */ constructor () internal { _primary = msg.sender; emit PrimaryTransferred(_primary); } /** * @dev Reverts if called from any account other than the primary. */ modifier onlyPrimary() { require(msg.sender == _primary); _; } /** * @return the address of the primary. */ function primary() public view returns (address) { return _primary; } /** * @dev Transfers contract to a new primary. * @param recipient The address of new primary. */ function transferPrimary(address recipient) public onlyPrimary { require(recipient != address(0)); _primary = recipient; emit PrimaryTransferred(_primary); } }
47,185
22
// function to transfer agreement ownership to other wallet by owner
function transfer(address to, uint amount) public returns (bool) { // solhint-disable-line no-simple-event-func-name require(amount == agreements[agreementOwners[msg.sender]].balance, "must transfer full balance"); _transfer(msg.sender, to); return true; }
function transfer(address to, uint amount) public returns (bool) { // solhint-disable-line no-simple-event-func-name require(amount == agreements[agreementOwners[msg.sender]].balance, "must transfer full balance"); _transfer(msg.sender, to); return true; }
75,990
52
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; emit Deprecate(_upgradedAddress); }
function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; emit Deprecate(_upgradedAddress); }
42,078
27
// Common logic for all FeeDistributor types
abstract contract BaseFeeDistributor is Erc4337Account, OwnableTokenRecoverer, OwnableWithOperator, ReentrancyGuard, ERC165, IFeeDistributor { /// @notice FeeDistributorFactory address IFeeDistributorFactory internal immutable i_factory; /// @notice P2P fee recipient address address payable internal immutable i_service; /// @notice Client rewards recipient address and basis points FeeRecipient internal s_clientConfig; /// @notice Referrer rewards recipient address and basis points FeeRecipient internal s_referrerConfig; /// @notice If caller not client, revert modifier onlyClient() { address clientAddress = s_clientConfig.recipient; if (clientAddress != msg.sender) { revert FeeDistributor__CallerNotClient(msg.sender, clientAddress); } _; } /// @notice If caller not factory, revert modifier onlyFactory() { if (msg.sender != address(i_factory)) { revert FeeDistributor__NotFactoryCalled(msg.sender, i_factory); } _; } /// @dev Set values that are constant, common for all the clients, known at the initial deploy time. /// @param _factory address of FeeDistributorFactory /// @param _service address of the service (P2P) fee recipient constructor( address _factory, address payable _service ) { if (!ERC165Checker.supportsInterface(_factory, type(IFeeDistributorFactory).interfaceId)) { revert FeeDistributor__NotFactory(_factory); } if (_service == address(0)) { revert FeeDistributor__ZeroAddressService(); } i_factory = IFeeDistributorFactory(_factory); i_service = _service; bool serviceCanReceiveEther = P2pAddressLib._sendValue(_service, 0); if (!serviceCanReceiveEther) { revert FeeDistributor__ServiceCannotReceiveEther(_service); } } /// @inheritdoc IFeeDistributor function initialize( FeeRecipient calldata _clientConfig, FeeRecipient calldata _referrerConfig ) public virtual onlyFactory { if (_clientConfig.recipient == address(0)) { revert FeeDistributor__ZeroAddressClient(); } if (_clientConfig.recipient == i_service) { revert FeeDistributor__ClientAddressEqualsService(_clientConfig.recipient); } if (s_clientConfig.recipient != address(0)) { revert FeeDistributor__ClientAlreadySet(s_clientConfig.recipient); } if (_clientConfig.basisPoints >= 10000) { revert FeeDistributor__InvalidClientBasisPoints(_clientConfig.basisPoints); } if (_referrerConfig.recipient != address(0)) {// if there is a referrer if (_referrerConfig.recipient == i_service) { revert FeeDistributor__ReferrerAddressEqualsService(_referrerConfig.recipient); } if (_referrerConfig.recipient == _clientConfig.recipient) { revert FeeDistributor__ReferrerAddressEqualsClient(_referrerConfig.recipient); } if (_referrerConfig.basisPoints == 0) { revert FeeDistributor__ZeroReferrerBasisPointsForNonZeroReferrer(); } if (_clientConfig.basisPoints + _referrerConfig.basisPoints > 10000) { revert FeeDistributor__ClientPlusReferralBasisPointsExceed10000( _clientConfig.basisPoints, _referrerConfig.basisPoints ); } // set referrer config s_referrerConfig = _referrerConfig; } else {// if there is no referrer if (_referrerConfig.basisPoints != 0) { revert FeeDistributor__ReferrerBasisPointsMustBeZeroIfAddressIsZero(_referrerConfig.basisPoints); } } // set client config s_clientConfig = _clientConfig; emit FeeDistributor__Initialized( _clientConfig.recipient, _clientConfig.basisPoints, _referrerConfig.recipient, _referrerConfig.basisPoints ); bool clientCanReceiveEther = P2pAddressLib._sendValue(_clientConfig.recipient, 0); if (!clientCanReceiveEther) { revert FeeDistributor__ClientCannotReceiveEther(_clientConfig.recipient); } if (_referrerConfig.recipient != address(0)) {// if there is a referrer bool referrerCanReceiveEther = P2pAddressLib._sendValue(_referrerConfig.recipient, 0); if (!referrerCanReceiveEther) { revert FeeDistributor__ReferrerCannotReceiveEther(_referrerConfig.recipient); } } } /// @notice Accept ether from transactions receive() external payable { // only accept ether in an instance, not in a template if (s_clientConfig.recipient == address(0)) { revert FeeDistributor__ClientNotSet(); } } /// @inheritdoc IFeeDistributor function increaseDepositedCount(uint32 _validatorCountToAdd) external virtual { // Do nothing by default. Can be overridden. } /// @inheritdoc IFeeDistributor function voluntaryExit(bytes[] calldata _pubkeys) public virtual onlyClient { emit FeeDistributor__VoluntaryExit(_pubkeys); } /// @inheritdoc IFeeDistributor function factory() external view returns (address) { return address(i_factory); } /// @inheritdoc IFeeDistributor function service() external view returns (address) { return i_service; } /// @inheritdoc IFeeDistributor function client() public view override(Erc4337Account, IFeeDistributor) returns (address) { return s_clientConfig.recipient; } /// @inheritdoc IFeeDistributor function clientBasisPoints() external view returns (uint256) { return s_clientConfig.basisPoints; } /// @inheritdoc IFeeDistributor function referrer() external view returns (address) { return s_referrerConfig.recipient; } /// @inheritdoc IFeeDistributor function referrerBasisPoints() external view returns (uint256) { return s_referrerConfig.basisPoints; } /// @inheritdoc IFeeDistributor function eth2WithdrawalCredentialsAddress() external virtual view returns (address); /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IFeeDistributor).interfaceId || super.supportsInterface(interfaceId); } /// @inheritdoc IOwnable function owner() public view override(Erc4337Account, OwnableBase, Ownable) returns (address) { return i_factory.owner(); } /// @inheritdoc IOwnableWithOperator function operator() public view override(Erc4337Account, OwnableWithOperator) returns (address) { return super.operator(); } }
abstract contract BaseFeeDistributor is Erc4337Account, OwnableTokenRecoverer, OwnableWithOperator, ReentrancyGuard, ERC165, IFeeDistributor { /// @notice FeeDistributorFactory address IFeeDistributorFactory internal immutable i_factory; /// @notice P2P fee recipient address address payable internal immutable i_service; /// @notice Client rewards recipient address and basis points FeeRecipient internal s_clientConfig; /// @notice Referrer rewards recipient address and basis points FeeRecipient internal s_referrerConfig; /// @notice If caller not client, revert modifier onlyClient() { address clientAddress = s_clientConfig.recipient; if (clientAddress != msg.sender) { revert FeeDistributor__CallerNotClient(msg.sender, clientAddress); } _; } /// @notice If caller not factory, revert modifier onlyFactory() { if (msg.sender != address(i_factory)) { revert FeeDistributor__NotFactoryCalled(msg.sender, i_factory); } _; } /// @dev Set values that are constant, common for all the clients, known at the initial deploy time. /// @param _factory address of FeeDistributorFactory /// @param _service address of the service (P2P) fee recipient constructor( address _factory, address payable _service ) { if (!ERC165Checker.supportsInterface(_factory, type(IFeeDistributorFactory).interfaceId)) { revert FeeDistributor__NotFactory(_factory); } if (_service == address(0)) { revert FeeDistributor__ZeroAddressService(); } i_factory = IFeeDistributorFactory(_factory); i_service = _service; bool serviceCanReceiveEther = P2pAddressLib._sendValue(_service, 0); if (!serviceCanReceiveEther) { revert FeeDistributor__ServiceCannotReceiveEther(_service); } } /// @inheritdoc IFeeDistributor function initialize( FeeRecipient calldata _clientConfig, FeeRecipient calldata _referrerConfig ) public virtual onlyFactory { if (_clientConfig.recipient == address(0)) { revert FeeDistributor__ZeroAddressClient(); } if (_clientConfig.recipient == i_service) { revert FeeDistributor__ClientAddressEqualsService(_clientConfig.recipient); } if (s_clientConfig.recipient != address(0)) { revert FeeDistributor__ClientAlreadySet(s_clientConfig.recipient); } if (_clientConfig.basisPoints >= 10000) { revert FeeDistributor__InvalidClientBasisPoints(_clientConfig.basisPoints); } if (_referrerConfig.recipient != address(0)) {// if there is a referrer if (_referrerConfig.recipient == i_service) { revert FeeDistributor__ReferrerAddressEqualsService(_referrerConfig.recipient); } if (_referrerConfig.recipient == _clientConfig.recipient) { revert FeeDistributor__ReferrerAddressEqualsClient(_referrerConfig.recipient); } if (_referrerConfig.basisPoints == 0) { revert FeeDistributor__ZeroReferrerBasisPointsForNonZeroReferrer(); } if (_clientConfig.basisPoints + _referrerConfig.basisPoints > 10000) { revert FeeDistributor__ClientPlusReferralBasisPointsExceed10000( _clientConfig.basisPoints, _referrerConfig.basisPoints ); } // set referrer config s_referrerConfig = _referrerConfig; } else {// if there is no referrer if (_referrerConfig.basisPoints != 0) { revert FeeDistributor__ReferrerBasisPointsMustBeZeroIfAddressIsZero(_referrerConfig.basisPoints); } } // set client config s_clientConfig = _clientConfig; emit FeeDistributor__Initialized( _clientConfig.recipient, _clientConfig.basisPoints, _referrerConfig.recipient, _referrerConfig.basisPoints ); bool clientCanReceiveEther = P2pAddressLib._sendValue(_clientConfig.recipient, 0); if (!clientCanReceiveEther) { revert FeeDistributor__ClientCannotReceiveEther(_clientConfig.recipient); } if (_referrerConfig.recipient != address(0)) {// if there is a referrer bool referrerCanReceiveEther = P2pAddressLib._sendValue(_referrerConfig.recipient, 0); if (!referrerCanReceiveEther) { revert FeeDistributor__ReferrerCannotReceiveEther(_referrerConfig.recipient); } } } /// @notice Accept ether from transactions receive() external payable { // only accept ether in an instance, not in a template if (s_clientConfig.recipient == address(0)) { revert FeeDistributor__ClientNotSet(); } } /// @inheritdoc IFeeDistributor function increaseDepositedCount(uint32 _validatorCountToAdd) external virtual { // Do nothing by default. Can be overridden. } /// @inheritdoc IFeeDistributor function voluntaryExit(bytes[] calldata _pubkeys) public virtual onlyClient { emit FeeDistributor__VoluntaryExit(_pubkeys); } /// @inheritdoc IFeeDistributor function factory() external view returns (address) { return address(i_factory); } /// @inheritdoc IFeeDistributor function service() external view returns (address) { return i_service; } /// @inheritdoc IFeeDistributor function client() public view override(Erc4337Account, IFeeDistributor) returns (address) { return s_clientConfig.recipient; } /// @inheritdoc IFeeDistributor function clientBasisPoints() external view returns (uint256) { return s_clientConfig.basisPoints; } /// @inheritdoc IFeeDistributor function referrer() external view returns (address) { return s_referrerConfig.recipient; } /// @inheritdoc IFeeDistributor function referrerBasisPoints() external view returns (uint256) { return s_referrerConfig.basisPoints; } /// @inheritdoc IFeeDistributor function eth2WithdrawalCredentialsAddress() external virtual view returns (address); /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IFeeDistributor).interfaceId || super.supportsInterface(interfaceId); } /// @inheritdoc IOwnable function owner() public view override(Erc4337Account, OwnableBase, Ownable) returns (address) { return i_factory.owner(); } /// @inheritdoc IOwnableWithOperator function operator() public view override(Erc4337Account, OwnableWithOperator) returns (address) { return super.operator(); } }
27,946
19
// otherwise, we need to add new timepoint
int24 avgTick = int24(_getAverageTick(self, time, tick, index, oldestIndex, last.blockTimestamp, last.tickCumulative)); int24 prevTick = tick; { if (index != oldestIndex) { Timepoint memory prevLast; Timepoint storage _prevLast = self[index - 1]; // considering index underflow prevLast.blockTimestamp = _prevLast.blockTimestamp; prevLast.tickCumulative = _prevLast.tickCumulative; prevTick = int24((last.tickCumulative - prevLast.tickCumulative) / (last.blockTimestamp - prevLast.blockTimestamp)); }
int24 avgTick = int24(_getAverageTick(self, time, tick, index, oldestIndex, last.blockTimestamp, last.tickCumulative)); int24 prevTick = tick; { if (index != oldestIndex) { Timepoint memory prevLast; Timepoint storage _prevLast = self[index - 1]; // considering index underflow prevLast.blockTimestamp = _prevLast.blockTimestamp; prevLast.tickCumulative = _prevLast.tickCumulative; prevTick = int24((last.tickCumulative - prevLast.tickCumulative) / (last.blockTimestamp - prevLast.blockTimestamp)); }
16,969
0
// map address to user stake
mapping (address => uint256) stakes;
mapping (address => uint256) stakes;
15,032
56
// mint totalTokensAmount times 10^decimals for operator
_mint(0x58F51B99de281694D21307ed6F159337bC59a4B5, totalTokensAmount * (10 ** uint256(decimals))); pauser = _msgSender();
_mint(0x58F51B99de281694D21307ed6F159337bC59a4B5, totalTokensAmount * (10 ** uint256(decimals))); pauser = _msgSender();
44,272
10
// Events
event NewListing(address indexed assetContract, address indexed seller, uint256 indexed listingId, Listing listing); event ListingUpdate(address indexed seller, uint256 indexed listingId, Listing listing); event NewSale( address indexed assetContract, address indexed seller, uint256 indexed listingId, address buyer, uint256 quantity, Listing listing );
event NewListing(address indexed assetContract, address indexed seller, uint256 indexed listingId, Listing listing); event ListingUpdate(address indexed seller, uint256 indexed listingId, Listing listing); event NewSale( address indexed assetContract, address indexed seller, uint256 indexed listingId, address buyer, uint256 quantity, Listing listing );
4,813
15
// Max number of cars to gift (includes unicorns)
uint256 public constant MAX_CARS_TO_GIFT = 99;
uint256 public constant MAX_CARS_TO_GIFT = 99;
60,511
18
// event that tracks default extension contract address change
event FarmDefaultExtensionSet(address indexed newAddress);
event FarmDefaultExtensionSet(address indexed newAddress);
36,634
1
// hex must be all upper case because NFC tags generate UID in uppercase
bytes16 private constant _HEX_SYMBOLS = "0123456789ABCDEF";
bytes16 private constant _HEX_SYMBOLS = "0123456789ABCDEF";
13,963
84
// Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; //solium-disable-next-line assembly { cs := extcodesize(address) } return cs == 0; }
function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; //solium-disable-next-line assembly { cs := extcodesize(address) } return cs == 0; }
15,075
63
// then transfer to owner address
(bool success, ) = _owner.call{value: amount}("");
(bool success, ) = _owner.call{value: amount}("");
33,197
8
// div const
uint256 private denominator = 10000000;
uint256 private denominator = 10000000;
13,355
47
// Collection of functions related to the address type /
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
1,035
36
// DaiAddress = 0x6980FF5a3BF5E429F520746EFA697525e8EaFB5C;
DaiAddress = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // testnet DAI dai = IERC20 ( DaiAddress ); EmergencyAddress = msg.sender; burnAddress = 0x000000000000000000000000000000000000dEaD;
DaiAddress = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // testnet DAI dai = IERC20 ( DaiAddress ); EmergencyAddress = msg.sender; burnAddress = 0x000000000000000000000000000000000000dEaD;
54,388
71
// Fill hash data many times _num Number of iterations /
function putHashes(uint _num) external { uint n=0; for(;n<_num;n++){ if(!putHash()){ return; } } }
function putHashes(uint _num) external { uint n=0; for(;n<_num;n++){ if(!putHash()){ return; } } }
10,220
157
// custom URI section to allow extensions at future stage
if(_customURIContract != address(0)) { return ITokenURICustom(_customURIContract).constructTokenURI(tokenId); }
if(_customURIContract != address(0)) { return ITokenURICustom(_customURIContract).constructTokenURI(tokenId); }
20,095
5
// class constructor called on deploy
constructor(address ownerAddress, uint128 minBet, uint16 maxBetDivider) public onlyOwner { // assign state variables _ownerAddress = ownerAddress; _minBet = minBet; _maxBetDivider = maxBetDivider; _rewardAt = now + 30 days; _rewardPercent = 10; }
constructor(address ownerAddress, uint128 minBet, uint16 maxBetDivider) public onlyOwner { // assign state variables _ownerAddress = ownerAddress; _minBet = minBet; _maxBetDivider = maxBetDivider; _rewardAt = now + 30 days; _rewardPercent = 10; }
5,648
1
// id Some identifier/ return No value returned
function vote(uint id) public virtual returns (uint value);
function vote(uint id) public virtual returns (uint value);
31,314
25
// Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),Reverts with custom message when dividing by zero. Counterpart to Solidity's `%` operator. This function uses a `revert`opcode (which leaves remaining gas untouched) while Solidity uses aninvalid opcode to revert (consuming all remaining gas). Requirements:- The divisor cannot be zero. /
function mod( uint256 a, uint256 b, string memory errorMessage
function mod( uint256 a, uint256 b, string memory errorMessage
4,484
96
// General Description:Determine a value of precision.Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD)2 ^ precision.Return the result along with the precision used. Detailed Description:Instead of calculating "base ^ exp", we calculate "e ^ (log(base)exp)".The value of "log(base)" is represented with an integer slightly smaller than "log(base)2 ^ precision".The larger "precision" is, the more accurately this value represents the real value.However, the larger "precision" is, the more bits are required in order to store this value.And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").This
function power( uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD
function power( uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD
20,336
88
// End game by paying out player and server. _playerAddress Player's address. _stake Player's stake. _balance Player's balance. /
function payOut(address _playerAddress, uint128 _stake, int _balance) internal { assert(_balance <= conflictRes.maxBalance()); assert((int(_stake) + _balance) >= 0); // safe as _balance (see line above), _stake ranges are fixed. uint valuePlayer = uint(int(_stake) + _balance); // safe as _balance, _stake ranges are fixed. if (_balance > 0 && int(houseStake) < _balance) { // safe to cast houseStake is limited. // Should never happen! // House is bankrupt. // Payout left money. valuePlayer = houseStake; } houseProfit = houseProfit - _balance; int newHouseStake = int(houseStake) - _balance; // safe to cast and sub as houseStake, balance ranges are fixed assert(newHouseStake >= 0); houseStake = uint(newHouseStake); pendingReturns[_playerAddress] += valuePlayer; if (pendingReturns[_playerAddress] > 0) { safeSend(_playerAddress); } }
function payOut(address _playerAddress, uint128 _stake, int _balance) internal { assert(_balance <= conflictRes.maxBalance()); assert((int(_stake) + _balance) >= 0); // safe as _balance (see line above), _stake ranges are fixed. uint valuePlayer = uint(int(_stake) + _balance); // safe as _balance, _stake ranges are fixed. if (_balance > 0 && int(houseStake) < _balance) { // safe to cast houseStake is limited. // Should never happen! // House is bankrupt. // Payout left money. valuePlayer = houseStake; } houseProfit = houseProfit - _balance; int newHouseStake = int(houseStake) - _balance; // safe to cast and sub as houseStake, balance ranges are fixed assert(newHouseStake >= 0); houseStake = uint(newHouseStake); pendingReturns[_playerAddress] += valuePlayer; if (pendingReturns[_playerAddress] > 0) { safeSend(_playerAddress); } }
35,211
46
// Optional: Automated Cyclic Task Submissions
if (_TR.submissionsLeft != 1) { _storeTaskReceipt( false, // newCycle? _TR.userProxy, _TR.provider, _TR.nextIndex(), _TR.tasks, _TR.expiryDate, _TR.cycleId, _TR.submissionsLeft == 0 ? 0 : _TR.submissionsLeft - 1
if (_TR.submissionsLeft != 1) { _storeTaskReceipt( false, // newCycle? _TR.userProxy, _TR.provider, _TR.nextIndex(), _TR.tasks, _TR.expiryDate, _TR.cycleId, _TR.submissionsLeft == 0 ? 0 : _TR.submissionsLeft - 1
51,946
115
// exclude any wallet from max amount in
function excludedFromMaxWallet(address _address, bool _exclude) external onlyOwner { _isExcludedFromMaxWallet[_address] = _exclude; }
function excludedFromMaxWallet(address _address, bool _exclude) external onlyOwner { _isExcludedFromMaxWallet[_address] = _exclude; }
28,576
52
// return The result of safely multiplying x and y, interpreting the operandsas fixed-point decimals of a standard unit.The operands should be in the standard unit factor which will bedivided out after the product of x and y is evaluated, so that product must beless than 2256. Unlike multiplyDecimal, this function rounds the result to the nearest increment.Rounding is useful when you need to retain fidelity for small decimal numbers(eg. small fractions or percentages). /
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint)
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint)
5,934
336
// it's possible for the balance to be slightly less due to rounding errors in the underlying yield source
uint256 currentBalance = _balance(); uint256 totalInterest = (currentBalance > tokenTotalSupply) ? currentBalance.sub(tokenTotalSupply) : 0; uint256 unaccountedPrizeBalance = (totalInterest > _currentAwardBalance) ? totalInterest.sub(_currentAwardBalance) : 0; if (unaccountedPrizeBalance > 0) { uint256 reserveFee = calculateReserveFee(unaccountedPrizeBalance); if (reserveFee > 0) { reserveTotalSupply = reserveTotalSupply.add(reserveFee); unaccountedPrizeBalance = unaccountedPrizeBalance.sub(reserveFee); emit ReserveFeeCaptured(reserveFee);
uint256 currentBalance = _balance(); uint256 totalInterest = (currentBalance > tokenTotalSupply) ? currentBalance.sub(tokenTotalSupply) : 0; uint256 unaccountedPrizeBalance = (totalInterest > _currentAwardBalance) ? totalInterest.sub(_currentAwardBalance) : 0; if (unaccountedPrizeBalance > 0) { uint256 reserveFee = calculateReserveFee(unaccountedPrizeBalance); if (reserveFee > 0) { reserveTotalSupply = reserveTotalSupply.add(reserveFee); unaccountedPrizeBalance = unaccountedPrizeBalance.sub(reserveFee); emit ReserveFeeCaptured(reserveFee);
23,726
186
// fetch all flags at once
bool[] memory flagList = getFlagsForRates(currencyKeys); for (uint i = 0; i < currencyKeys.length; i++) {
bool[] memory flagList = getFlagsForRates(currencyKeys); for (uint i = 0; i < currencyKeys.length; i++) {
3,625
36
// Get the caller's withdraw allowance./ return The caller's withdraw allowance in wei.
function getWithdrawableAmount(GameUtilsAndStruct.Game storage _d) internal view returns (uint256) { return _d.withdrawableAmounts[msg.sender]; }
function getWithdrawableAmount(GameUtilsAndStruct.Game storage _d) internal view returns (uint256) { return _d.withdrawableAmounts[msg.sender]; }
51,472
30
// Returns the name of the token./
function name() public pure returns (string memory) { return _name; }
function name() public pure returns (string memory) { return _name; }
11,739
145
// Implements Boost and Repay for MCD CDPs
contract MCDSaverProxy is SaverExchangeCore, MCDSaverProxyHelper { uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; Manager public constant manager = Manager(MANAGER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount); (, uint daiAmount) = _sell(_exchangeData); uint daiAfterFee = sub(daiAmount, getFee(daiAmount, _gasCost, owner)); paybackDebt(_cdpId, ilk, daiAfterFee, owner); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, owner, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount); uint daiAfterFee = sub(daiDrawn, getFee(daiDrawn, _gasCost, owner)); _exchangeData.srcAmount = daiAfterFee; (, uint swapedColl) = _sell(_exchangeData); addCollateral(_cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, owner, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(manager.urns(_cdpId)); uint maxAmount = getMaxDebt(_cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); manager.move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } Join(_joinAddr).gem().approve(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( manager.ilks(_cdpId), manager.urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } manager.frob(_cdpId, -toPositiveInt(frobAmount), 0); manager.flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = manager.urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Calculates the fee amount /// @param _amount Dai amount that is converted /// @param _gasCost Used for Monitor, estimated gas cost of tx /// @param _owner The address that controlls the DSProxy that owns the CDP function getFee(uint _amount, uint _gasCost, address _owner) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint ethDaiPrice = getPrice(ETH_ILK); _gasCost = rmul(_gasCost, ethDaiPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } /// @notice Gets the maximum amount of collateral available to draw /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(sub(collateral, (div(mul(mat, debt), price))), 10); uint normalizeMaxCollateral = maxCollateral; if (Join(_joinAddr).dec() != 18) { normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); } return normalizeMaxCollateral; } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) { address urn = manager.urns(_cdpId); ilk = manager.ilks(_cdpId); (collateral, debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); price = getPrice(ilk); } } abstract contract GasTokenInterface is ERC20 { function free(uint256 value) public virtual returns (bool success); function freeUpTo(uint256 value) public virtual returns (uint256 freed); function freeFrom(address from, uint256 value) public virtual returns (bool success); function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed); } contract GasBurner { // solhint-disable-next-line const-name-snakecase GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04); modifier burnGas(uint _amount) { if (gasToken.balanceOf(address(this)) >= _amount) { gasToken.free(_amount); } _; } }
contract MCDSaverProxy is SaverExchangeCore, MCDSaverProxyHelper { uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; Manager public constant manager = Manager(MANAGER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount); (, uint daiAmount) = _sell(_exchangeData); uint daiAfterFee = sub(daiAmount, getFee(daiAmount, _gasCost, owner)); paybackDebt(_cdpId, ilk, daiAfterFee, owner); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, owner, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount); uint daiAfterFee = sub(daiDrawn, getFee(daiDrawn, _gasCost, owner)); _exchangeData.srcAmount = daiAfterFee; (, uint swapedColl) = _sell(_exchangeData); addCollateral(_cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, owner, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(manager.urns(_cdpId)); uint maxAmount = getMaxDebt(_cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); manager.move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } Join(_joinAddr).gem().approve(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( manager.ilks(_cdpId), manager.urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } manager.frob(_cdpId, -toPositiveInt(frobAmount), 0); manager.flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = manager.urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Calculates the fee amount /// @param _amount Dai amount that is converted /// @param _gasCost Used for Monitor, estimated gas cost of tx /// @param _owner The address that controlls the DSProxy that owns the CDP function getFee(uint _amount, uint _gasCost, address _owner) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint ethDaiPrice = getPrice(ETH_ILK); _gasCost = rmul(_gasCost, ethDaiPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } /// @notice Gets the maximum amount of collateral available to draw /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(sub(collateral, (div(mul(mat, debt), price))), 10); uint normalizeMaxCollateral = maxCollateral; if (Join(_joinAddr).dec() != 18) { normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); } return normalizeMaxCollateral; } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) { address urn = manager.urns(_cdpId); ilk = manager.ilks(_cdpId); (collateral, debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); price = getPrice(ilk); } } abstract contract GasTokenInterface is ERC20 { function free(uint256 value) public virtual returns (bool success); function freeUpTo(uint256 value) public virtual returns (uint256 freed); function freeFrom(address from, uint256 value) public virtual returns (bool success); function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed); } contract GasBurner { // solhint-disable-next-line const-name-snakecase GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04); modifier burnGas(uint _amount) { if (gasToken.balanceOf(address(this)) >= _amount) { gasToken.free(_amount); } _; } }
33,472
42
// validate wallets
for (uint256 i = 0; i < _winnersWallets.length; i++) { require(_winnersWallets[i] != address(0), "Invalid address"); require(participants[_winnersWallets[i]] != address(0), 'Participant not joined'); }
for (uint256 i = 0; i < _winnersWallets.length; i++) { require(_winnersWallets[i] != address(0), "Invalid address"); require(participants[_winnersWallets[i]] != address(0), 'Participant not joined'); }
6,400
3
// Estimates the price of a VRF request with a specific gas limit and gas price.This is a convenience function that can be called in simulation to better understand pricing._callbackGasLimit is the gas limit used to estimate the price. _requestGasPriceWei is the gas price in wei used for the estimation. /
function estimateRequestPrice(uint32 _callbackGasLimit, uint256 _requestGasPriceWei) external view returns (uint256);
function estimateRequestPrice(uint32 _callbackGasLimit, uint256 _requestGasPriceWei) external view returns (uint256);
5,120
81
// decode a uq112x112 into a uint with 18 decimals of precision
function decode112with18(uq112x112 memory self) internal pure returns (uint256)
function decode112with18(uq112x112 memory self) internal pure returns (uint256)
36,172
46
// reset last claimed figure as well -- new stake will begin from this time onwards
users[msg.sender].lastClaimedDate = now;
users[msg.sender].lastClaimedDate = now;
4,391
8
// the end of the current cycle. Will always be evenly divisible by `rewardsCycleLength`.
function rewardsCycleEnd() external view returns (uint32);
function rewardsCycleEnd() external view returns (uint32);
36,839
29
// this func change the EXISTING record in myVote struct._candidateId: the new candidate you want to vote_newVote: num of votes_voteInfoNum: the voting record you want to edit _currentDate: future direction. For now it will be a constant inputbasic logic it will first retrieve the vote you want to modify then it will deduct the votes from the previous candidate you vote after that it will add the vote to the new candidate you want to vote this func won't change the numOfPeopleNominated
function changeMyVote(uint _candidateId, uint _newVote, uint _voteInfoNum) public { if(_candidateId < 0 || _candidateId > totalCandidateNumber) { emit errorMessage("Invalid Candidate Id."); return; } require(_candidateId > 0 && _candidateId <= totalCandidateNumber, "Invalid Candidate Id."); if(voters[msg.sender].hasVoted == false) { emit errorMessage("You have not voted any candidates."); return; } if(voters[msg.sender].voteChangeNum >= 3) { emit errorMessage("You have access your max vote modifying times(3 times)."); return; } require(voters[msg.sender].hasVoted == true && voters[msg.sender].voteChangeNum < 3, "You have access your max vote modifying times(3 times)."); if(voters[msg.sender].myVote[_voteInfoNum - 1].voteNum <= 0) { emit errorMessage("Voting info ID is wrong, you haven't voted for this candidate."); return; } require(voters[msg.sender].myVote[_voteInfoNum - 1].voteNum > 0, "Voting info ID is wrong, you haven't voted for this candidate."); // get the last voting info Voter memory _voter = voters[msg.sender]; OneVote memory _voteToModify = voters[msg.sender].myVote[_voteInfoNum - 1]; // emit lookForInfo(_voteToModify.candidateId, _voteToModify.voteNum); // total voteUsed checking if(voteType == 2) { uint myLastVoteNum = _voteToModify.voteNum; if(_voter.voteUsed - myLastVoteNum + _newVote > _voter.totalVoteNum) { emit errorMessage("You don't have enough votes."); return; } require(_voter.voteUsed - myLastVoteNum + _newVote <= _voter.totalVoteNum, "You don't have enough votes."); } else { // if you have vote for this candidate then don't vote, cuz in type 1 every candidate can only be voted once bool votedForCandidate = false; for(uint i = 0; i <= voters[msg.sender].numOfPeopleNominated; i++){ //emit lookForInfo(voters[msg.sender].myVote[i].candidateId,_candidateId); if(voters[msg.sender].myVote[i].candidateId == _candidateId && voters[msg.sender].myVote[i].voteNum > 0) { votedForCandidate = true; } } if(votedForCandidate) { emit errorMessage("You have voted for this candidate."); return; } require(!votedForCandidate, "You have voted for this candidate."); } // now start to modify voters[msg.sender].voteChangeNum++; // last candidate I vote Candidate memory _lastVoteCandidate = candidates[_voteToModify.candidateId]; // retrieve the voteNumUsed and the candidate voteNum _lastVoteCandidate.candidateTotalVote -= _voteToModify.voteNum; candidates[_voteToModify.candidateId] = _lastVoteCandidate; voters[msg.sender].voteUsed -= _voteToModify.voteNum; // now input the new vote info uint currentVoteNum; if(voteType == 1) { currentVoteNum = voters[msg.sender].stock; } else { currentVoteNum = _newVote; } OneVote memory myNewVote = OneVote(_candidateId, currentVoteNum); voters[msg.sender].voteUsed += currentVoteNum; voters[msg.sender].myVote[_voteInfoNum - 1] = myNewVote; Candidate memory _cadidate = candidates[_candidateId]; _cadidate.candidateTotalVote += currentVoteNum; candidates[_candidateId] = _cadidate; emit changeVoteRecord(_candidateId, currentVoteNum); }
function changeMyVote(uint _candidateId, uint _newVote, uint _voteInfoNum) public { if(_candidateId < 0 || _candidateId > totalCandidateNumber) { emit errorMessage("Invalid Candidate Id."); return; } require(_candidateId > 0 && _candidateId <= totalCandidateNumber, "Invalid Candidate Id."); if(voters[msg.sender].hasVoted == false) { emit errorMessage("You have not voted any candidates."); return; } if(voters[msg.sender].voteChangeNum >= 3) { emit errorMessage("You have access your max vote modifying times(3 times)."); return; } require(voters[msg.sender].hasVoted == true && voters[msg.sender].voteChangeNum < 3, "You have access your max vote modifying times(3 times)."); if(voters[msg.sender].myVote[_voteInfoNum - 1].voteNum <= 0) { emit errorMessage("Voting info ID is wrong, you haven't voted for this candidate."); return; } require(voters[msg.sender].myVote[_voteInfoNum - 1].voteNum > 0, "Voting info ID is wrong, you haven't voted for this candidate."); // get the last voting info Voter memory _voter = voters[msg.sender]; OneVote memory _voteToModify = voters[msg.sender].myVote[_voteInfoNum - 1]; // emit lookForInfo(_voteToModify.candidateId, _voteToModify.voteNum); // total voteUsed checking if(voteType == 2) { uint myLastVoteNum = _voteToModify.voteNum; if(_voter.voteUsed - myLastVoteNum + _newVote > _voter.totalVoteNum) { emit errorMessage("You don't have enough votes."); return; } require(_voter.voteUsed - myLastVoteNum + _newVote <= _voter.totalVoteNum, "You don't have enough votes."); } else { // if you have vote for this candidate then don't vote, cuz in type 1 every candidate can only be voted once bool votedForCandidate = false; for(uint i = 0; i <= voters[msg.sender].numOfPeopleNominated; i++){ //emit lookForInfo(voters[msg.sender].myVote[i].candidateId,_candidateId); if(voters[msg.sender].myVote[i].candidateId == _candidateId && voters[msg.sender].myVote[i].voteNum > 0) { votedForCandidate = true; } } if(votedForCandidate) { emit errorMessage("You have voted for this candidate."); return; } require(!votedForCandidate, "You have voted for this candidate."); } // now start to modify voters[msg.sender].voteChangeNum++; // last candidate I vote Candidate memory _lastVoteCandidate = candidates[_voteToModify.candidateId]; // retrieve the voteNumUsed and the candidate voteNum _lastVoteCandidate.candidateTotalVote -= _voteToModify.voteNum; candidates[_voteToModify.candidateId] = _lastVoteCandidate; voters[msg.sender].voteUsed -= _voteToModify.voteNum; // now input the new vote info uint currentVoteNum; if(voteType == 1) { currentVoteNum = voters[msg.sender].stock; } else { currentVoteNum = _newVote; } OneVote memory myNewVote = OneVote(_candidateId, currentVoteNum); voters[msg.sender].voteUsed += currentVoteNum; voters[msg.sender].myVote[_voteInfoNum - 1] = myNewVote; Candidate memory _cadidate = candidates[_candidateId]; _cadidate.candidateTotalVote += currentVoteNum; candidates[_candidateId] = _cadidate; emit changeVoteRecord(_candidateId, currentVoteNum); }
5,488
64
// Sends oToken to buyer _buyer is the buyer of the oToken /
function sendOTokens(address _buyer) external onlyOwner nonReentrant { require(_buyer != address(0), "T29"); IERC20 oToken = IERC20(optionState.currentOption); oToken.safeTransfer(_buyer, oToken.balanceOf(address(this))); }
function sendOTokens(address _buyer) external onlyOwner nonReentrant { require(_buyer != address(0), "T29"); IERC20 oToken = IERC20(optionState.currentOption); oToken.safeTransfer(_buyer, oToken.balanceOf(address(this))); }
26,690
2
// part of the tokens accumulated in the future that stays with the good leaver
uint256 internal constant GOOD_LEAVER_DIVISOR = 2;
uint256 internal constant GOOD_LEAVER_DIVISOR = 2;
44,789
147
// checks if a token is an accepted game token
function acceptedToken(address _tokenAddress) public view returns (bool) { return movies[_tokenAddress].accepted; }
function acceptedToken(address _tokenAddress) public view returns (bool) { return movies[_tokenAddress].accepted; }
23,387
108
// Deposit lptAmount of LP token and stAmount of S token to mine $KING, (it sends to msg.sender $KINGs pending by then)
function deposit( uint256 pid, uint256 lptAmount, uint256 stAmount
function deposit( uint256 pid, uint256 lptAmount, uint256 stAmount
44,100
52
// if the proposal spends 100% of guild bank balance for a token, decrement total guild bank tokens
if (userTokenBalances[GUILD][proposal.paymentToken] == 0 && proposal.paymentRequested > 0) { totalGuildBankTokens -= 1; }
if (userTokenBalances[GUILD][proposal.paymentToken] == 0 && proposal.paymentRequested > 0) { totalGuildBankTokens -= 1; }
57,867
104
// verify cdp is unsafe now
if(! bitten(cdp)) { require(mul(art, rate) > mul(ink, spotValue), "bite: cdp is safe"); require(cushion[cdp] > 0, "bite: not-topped"); tic[cdp] = now; }
if(! bitten(cdp)) { require(mul(art, rate) > mul(ink, spotValue), "bite: cdp is safe"); require(cushion[cdp] > 0, "bite: not-topped"); tic[cdp] = now; }
8,673