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
21
// this smart contract should have enough tokens to distribute
require(CSE.balanceOf(this) >= tokenBought); totalRaised = totalRaised.add(msg.value); // Save the total eth totalRaised (in wei) totalDistributed = totalDistributed.add(tokenBought); //Save to total tokens distributed CSE.transfer(msg.sender,tokenBought); //Send Tokens to user owner.transfer(msg.value); // Send ETH to owner
require(CSE.balanceOf(this) >= tokenBought); totalRaised = totalRaised.add(msg.value); // Save the total eth totalRaised (in wei) totalDistributed = totalDistributed.add(tokenBought); //Save to total tokens distributed CSE.transfer(msg.sender,tokenBought); //Send Tokens to user owner.transfer(msg.value); // Send ETH to owner
51,193
97
// (uint amountA, uint amountB) = BridgePair(bp).removeLiquidity(Liq, 1, 1, block.timestamp + 1);
BridgePair(bp).removeLiquidity(Liq, 1, 1, block.timestamp + 1); //此处是无条件减少 uni pair 的流动性 if (UserNewAmount > IERC20(_token).balanceOf(address(this))) { DoingAmount = UserNewAmount - IERC20(_token).balanceOf(address(this)); }
BridgePair(bp).removeLiquidity(Liq, 1, 1, block.timestamp + 1); //此处是无条件减少 uni pair 的流动性 if (UserNewAmount > IERC20(_token).balanceOf(address(this))) { DoingAmount = UserNewAmount - IERC20(_token).balanceOf(address(this)); }
33,896
12
// Admin can withdraw excess reward tokens.
function withdrawPrimaryTokenRewards(uint256 _amount) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Not authorized"); // to prevent locking of direct-transferred tokens primaryTokenRewardsBalance = _amount > primaryTokenRewardsBalance ? 0 : primaryTokenRewardsBalance - _amount; CurrencyTransferLib.transferCurrencyWithWrapper( primaryTokenRewards, address(this), _msgSender(), _amount, nativeTokenWrapper ); emit PrimaryTokenRewardsWithdrawnByAdmin(_amount); }
function withdrawPrimaryTokenRewards(uint256 _amount) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Not authorized"); // to prevent locking of direct-transferred tokens primaryTokenRewardsBalance = _amount > primaryTokenRewardsBalance ? 0 : primaryTokenRewardsBalance - _amount; CurrencyTransferLib.transferCurrencyWithWrapper( primaryTokenRewards, address(this), _msgSender(), _amount, nativeTokenWrapper ); emit PrimaryTokenRewardsWithdrawnByAdmin(_amount); }
13,781
5
// ---- STRUCTS -----
struct Entitlement { /// @notice the beneficial owner address this entitlement applies to. This address will also be the signer. address beneficialOwner; /// @notice the operating contract that can change ownership during the entitlement period. address operator; /// @notice the contract address for the vault that contains the underlying assets address vaultAddress; /// @notice the assetId of the asset or assets within the vault uint32 assetId; /// @notice the block timestamp after which the asset is free of the entitlement uint32 expiry; }
struct Entitlement { /// @notice the beneficial owner address this entitlement applies to. This address will also be the signer. address beneficialOwner; /// @notice the operating contract that can change ownership during the entitlement period. address operator; /// @notice the contract address for the vault that contains the underlying assets address vaultAddress; /// @notice the assetId of the asset or assets within the vault uint32 assetId; /// @notice the block timestamp after which the asset is free of the entitlement uint32 expiry; }
39,675
9
// INTERNAL FUNCTIONS/ Check if pending proposal can overwrite the current config.
function _updateConfig() internal {
function _updateConfig() internal {
2,467
16
// libraryを作りましょう。 uint newK = (reserve0 + reserve1 + (2_amount01In))(reserve0 + reserve1 + (2_amount01In)) / 4; uint newReserve2 = reserve0 < reserve1 ? (newK / (reserve1 + _amount01In)).sub(reserve0 + _amount01In) : (newK / (reserve0 + _amount01In)).sub(reserve1 + _amount01In); uint value2 = newReserve2 - reserve2;
require(IERC721(token0).balanceOf(pairCreater) >= _amount01In); require(IERC721(token1).balanceOf(pairCreater) >= _amount01In); TransferHelper.safeTransferFromERC721(token0, pairCreater, address(this), _amount01In); TransferHelper.safeTransferFromERC721(token1, pairCreater, address(this), _amount01In); reserve0 = reserve0.add(_amount01In); reserve1 = reserve1.add(_amount01In); sufficientLiquidity = true;
require(IERC721(token0).balanceOf(pairCreater) >= _amount01In); require(IERC721(token1).balanceOf(pairCreater) >= _amount01In); TransferHelper.safeTransferFromERC721(token0, pairCreater, address(this), _amount01In); TransferHelper.safeTransferFromERC721(token1, pairCreater, address(this), _amount01In); reserve0 = reserve0.add(_amount01In); reserve1 = reserve1.add(_amount01In); sufficientLiquidity = true;
752
13
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32); assembly {
string memory result = new string(encodedLen + 32); assembly {
23,858
19
// tokenId => (child address => array of child tokens)
mapping(uint256 => mapping(address => uint256[])) internal childTokens;
mapping(uint256 => mapping(address => uint256[])) internal childTokens;
24,225
15
// - Pool Update
TokenUpdate();
TokenUpdate();
34,128
30
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
(bool success, ) = recipient.call{ value: amount }("");
14,326
24
// update the interest rate after the deposit
reserve.updateInterestRates();
reserve.updateInterestRates();
13,051
21
// Staker
Staker storage staker = _stakers[msg.sender]; if (!staker.exists) { staker.exists = true; }
Staker storage staker = _stakers[msg.sender]; if (!staker.exists) { staker.exists = true; }
22,520
71
// Decreases the total supply by burning the specified number of tokens from the supply controller account. _value The number of tokens to remove.return A boolean that indicates if the operation was successful. /
function decreaseSupply(uint256 _value) public onlySupplyController returns (bool success) { require(_value <= balances[supplyController], "not enough supply"); balances[supplyController] = balances[supplyController].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit SupplyDecreased(supplyController, _value); emit Transfer(supplyController, address(0), _value); return true; }
function decreaseSupply(uint256 _value) public onlySupplyController returns (bool success) { require(_value <= balances[supplyController], "not enough supply"); balances[supplyController] = balances[supplyController].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit SupplyDecreased(supplyController, _value); emit Transfer(supplyController, address(0), _value); return true; }
14,992
10
// ERC20BasicSimpler version of ERC20 interface /
abstract contract ERC20Basic { uint256 public totalSupply; event Transfer(address indexed from, address indexed to, uint256 value); function transfer(address to, uint256 value) external virtual returns (bool); function balanceOf(address who) external virtual view returns (uint256); }
abstract contract ERC20Basic { uint256 public totalSupply; event Transfer(address indexed from, address indexed to, uint256 value); function transfer(address to, uint256 value) external virtual returns (bool); function balanceOf(address who) external virtual view returns (uint256); }
39,884
8
// withdraws the AAVE, DAI and LINK collateral from the lending pool
flashWithdraw(lendingPool);
flashWithdraw(lendingPool);
4,401
16
// Allows owner to fill contract with BNB to cover gas costs.
if (msg.sender == owner()) {}
if (msg.sender == owner()) {}
41,613
99
// Ensure the sAUD synth Proxy is correctly connected to the Synth;
proxysaud_i.setTarget(Proxyable(new_SynthsAUD_contract));
proxysaud_i.setTarget(Proxyable(new_SynthsAUD_contract));
12,588
79
// @note in the case of shortfall, purchase currency in termRepoLocker must balance the pro rata redemption value of remaining term repo tokens
return (totalRepurchaseCollected) / (10 ** 4) == mul_ScalarTruncate(
return (totalRepurchaseCollected) / (10 ** 4) == mul_ScalarTruncate(
35,415
18
// Allows the DAO to set a new contract address for Loot. This is/ relevant in the event that Loot migrates to a new contract./_SeasonContractAddress The new contract address for Loot
function daoSetSeasonContractAddress(address _SeasonContractAddress) external onlyOwner
function daoSetSeasonContractAddress(address _SeasonContractAddress) external onlyOwner
18,172
157
// boxPool[curRoundNo] = boxPool[curRoundNo]-userBoxReward;
addr.transfer(userBoxReward);
addr.transfer(userBoxReward);
9,697
9
// chainlink
uint256 public immutable interval; uint256 public lastTimeStamp; bytes32 public chainlinkJobId; uint256 public chainlinkFee; address owner; constructor( ISuperfluid host, ISuperfluidToken token_,
uint256 public immutable interval; uint256 public lastTimeStamp; bytes32 public chainlinkJobId; uint256 public chainlinkFee; address owner; constructor( ISuperfluid host, ISuperfluidToken token_,
10,228
105
// list of employees
EmployeesList public employees;
EmployeesList public employees;
30,320
74
// Returns the maximum size of the list /
function getMaxSize(Data storage self) public view returns (uint256) { return self.maxSize; }
function getMaxSize(Data storage self) public view returns (uint256) { return self.maxSize; }
43,379
23
// Queries and adds together the vault balances for specified user/user The user to query balances for/ return The total voting power for the user
function balanceOfVaults(address user) external returns (uint256) { uint256 votingPower = 0; // query voting power from each vault and add to total for (uint256 i = 0; i < vaults.length; i++) { votingPower = votingPower + vaults[i].queryVotePower(user, block.number - 1, "0x"); } // return that balance return votingPower; }
function balanceOfVaults(address user) external returns (uint256) { uint256 votingPower = 0; // query voting power from each vault and add to total for (uint256 i = 0; i < vaults.length; i++) { votingPower = votingPower + vaults[i].queryVotePower(user, block.number - 1, "0x"); } // return that balance return votingPower; }
1,489
4
// return the token being held. /
function token() public view virtual returns (IERC20) { return _token; }
function token() public view virtual returns (IERC20) { return _token; }
19,648
11
// minimum repayment period
uint min_repayment_period;
uint min_repayment_period;
19,808
73
// Calculates the amount that has already vested. token ERC20 token which is being vested /
function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } }
function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } }
7,142
183
// Gets the redeem duration of the NFT self The NFT configurationreturn The redeem duration /
function getRedeemDuration(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~REDEEM_DURATION_MASK) >> REDEEM_DURATION_START_BIT_POSITION; }
function getRedeemDuration(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~REDEEM_DURATION_MASK) >> REDEEM_DURATION_START_BIT_POSITION; }
54,021
277
// Mints NFTs
function mintNFT(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint NFT"); require(numberOfTokens <= maxNftPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_NFTS, "Purchase would exceed max supply of NFTs"); require(nftPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_NFTS) { _safeMint(msg.sender, mintIndex); } } // If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after the end of pre-sale, set the starting index block if (startingIndexBlock == 0 && (totalSupply() == MAX_NFTS || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } }
function mintNFT(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint NFT"); require(numberOfTokens <= maxNftPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_NFTS, "Purchase would exceed max supply of NFTs"); require(nftPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_NFTS) { _safeMint(msg.sender, mintIndex); } } // If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after the end of pre-sale, set the starting index block if (startingIndexBlock == 0 && (totalSupply() == MAX_NFTS || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } }
25,926
399
// Supports recovering LP Rewards from other systems such as BAL to be distributed to holders/ or tokens that were mistakenly/tokenAddress Address of the token to transfer/to Address to give tokens to/tokenAmount Amount of tokens to transfer
function recoverERC20( address tokenAddress, address to, uint256 tokenAmount
function recoverERC20( address tokenAddress, address to, uint256 tokenAmount
30,171
234
// min1&3&2 = min(min1&3, 2)
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount);
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount);
28,696
83
// See {BEP20-balanceOf}. /
function balanceOf(address account) public override view returns (uint256) { return _balances[account]; }
function balanceOf(address account) public override view returns (uint256) { return _balances[account]; }
4,575
92
// Distribute funds to the winner, platform, and partners._weiWin Funds for distribution._game A number of the game._matched A number of the player matches._player Player address._bet Player bet./
function distributeFunds( uint256 _weiWin, uint256 _game, uint8 _matched, address _player, bytes3 _bet ) internal
function distributeFunds( uint256 _weiWin, uint256 _game, uint8 _matched, address _player, bytes3 _bet ) internal
2,578
696
// target contract address changed -> close proposal without execution.
if (targetContractAddress != proposals[_proposalId].targetContractAddress) { outcome = Outcome.TargetContractAddressChanged; }
if (targetContractAddress != proposals[_proposalId].targetContractAddress) { outcome = Outcome.TargetContractAddressChanged; }
38,688
40
// SOULBOUND: If transferrable, use approve().
function setApprovalForAll(address, bool) public virtual override { revert NotTransferrable(); }
function setApprovalForAll(address, bool) public virtual override { revert NotTransferrable(); }
1,684
51
// Emit cancel order
CancelOrder(cancelHash, orderHash, cancelAddresses[3], cancelAddresses[1], cancelValues[1], cancelValues[4]);
CancelOrder(cancelHash, orderHash, cancelAddresses[3], cancelAddresses[1], cancelValues[1], cancelValues[4]);
48,727
52
// bridge to polygon
if (isPredicate[to]) { bridged += amount; userBridged[from] += amount; super._mint(from, amount); }
if (isPredicate[to]) { bridged += amount; userBridged[from] += amount; super._mint(from, amount); }
43,020
2
// Burn only own tokens
_burn(_msgSender(), amount);
_burn(_msgSender(), amount);
76,721
89
// Increasing of the deposit of the investor. Увеличение Суммы депозита инвестора;
deposit[msg.sender] = deposit[msg.sender].add(_value);
deposit[msg.sender] = deposit[msg.sender].add(_value);
82,651
21
// i think this is not needed in UI, just for testing return error if member has not voted
function readMemberVote(uint memberNumber) public view returns (bool)
function readMemberVote(uint memberNumber) public view returns (bool)
4,587
19
// FT.burn(amount);
_block[msg.sender] = block.number; _totalStakedFT += amount; _stakedFT[msg.sender] += amount;
_block[msg.sender] = block.number; _totalStakedFT += amount; _stakedFT[msg.sender] += amount;
18,311
25
// Retrieve the royalties here
uint256 totalRoyaltyFee; (address payable[] memory _recipients, uint256[] memory _amounts) = getRoyalties(_offer._contract, _tokenId, _offer._value); if (_recipients.length > 0 && _amounts.length > 0 && _amounts.length == _recipients.length) { for (uint256 idx; idx < _recipients.length; idx++) { totalRoyaltyFee += _amounts[idx]; _recipients[idx].call{value: _amounts[idx]}('');
uint256 totalRoyaltyFee; (address payable[] memory _recipients, uint256[] memory _amounts) = getRoyalties(_offer._contract, _tokenId, _offer._value); if (_recipients.length > 0 && _amounts.length > 0 && _amounts.length == _recipients.length) { for (uint256 idx; idx < _recipients.length; idx++) { totalRoyaltyFee += _amounts[idx]; _recipients[idx].call{value: _amounts[idx]}('');
13,691
182
// Whether or not the voter supports the proposal
bool support;
bool support;
52,347
19
// Burn it
try ERC1155Burnable(msg.sender).burn(address(this), id, 1) { } catch Error(string memory reason) {
try ERC1155Burnable(msg.sender).burn(address(this), id, 1) { } catch Error(string memory reason) {
15,630
9
// Fuel/LFG Gaming LLC/Simple tracker for how much ETH a user has deposited into Furballs' pools, etc.
contract Fuel is FurProxy { mapping(address => uint256) public tank; uint256 public conversionRate = 100000000000; constructor(address furballsAddress) FurProxy(furballsAddress) { } /// @notice Change ETH/Fuel ratio function setConversion(uint256 rate) external gameModerators { conversionRate = rate; } /// @notice Direct deposit function /// @dev Pass zero address to apply to self function deposit(address to) external payable { require(msg.value > 0, "VALUE"); if (to == address(0)) to = msg.sender; tank[to] += msg.value / conversionRate; } /// @notice Sends payout to the treasury function settle(uint256 amount) external gameModerators { if (amount == 0) amount = address(this).balance; furballs.governance().treasury().transfer(amount); } /// @notice Increases balance function gift(address[] calldata tos, uint256[] calldata amounts) external gameModerators { for (uint i=0; i<tos.length; i++) { tank[tos[i]] += amounts[i]; } } /// @notice Decreases balance. Returns the amount withdrawn, where zero indicates failure. /// @dev Does not require/throw, but empties the balance when it exceeds the requested amount. function burn(address from, uint256 amount) external gameModerators returns(uint) { return _burn(from, amount); } /// @notice Burn lots of fuel from different players function burnAll( address[] calldata wallets, uint256[] calldata requestedFuels ) external gameModerators { for (uint i=0; i<wallets.length; i++) { _burn(wallets[i], requestedFuels[i]); } } /// @notice Internal burn function _burn(address from, uint256 amount) internal returns(uint) { uint256 bal = tank[from]; if (bal == 0) { return 0; } else if (bal > amount) { tank[from] = bal - amount; } else { amount = bal; tank[from] = 0; } return amount; } }
contract Fuel is FurProxy { mapping(address => uint256) public tank; uint256 public conversionRate = 100000000000; constructor(address furballsAddress) FurProxy(furballsAddress) { } /// @notice Change ETH/Fuel ratio function setConversion(uint256 rate) external gameModerators { conversionRate = rate; } /// @notice Direct deposit function /// @dev Pass zero address to apply to self function deposit(address to) external payable { require(msg.value > 0, "VALUE"); if (to == address(0)) to = msg.sender; tank[to] += msg.value / conversionRate; } /// @notice Sends payout to the treasury function settle(uint256 amount) external gameModerators { if (amount == 0) amount = address(this).balance; furballs.governance().treasury().transfer(amount); } /// @notice Increases balance function gift(address[] calldata tos, uint256[] calldata amounts) external gameModerators { for (uint i=0; i<tos.length; i++) { tank[tos[i]] += amounts[i]; } } /// @notice Decreases balance. Returns the amount withdrawn, where zero indicates failure. /// @dev Does not require/throw, but empties the balance when it exceeds the requested amount. function burn(address from, uint256 amount) external gameModerators returns(uint) { return _burn(from, amount); } /// @notice Burn lots of fuel from different players function burnAll( address[] calldata wallets, uint256[] calldata requestedFuels ) external gameModerators { for (uint i=0; i<wallets.length; i++) { _burn(wallets[i], requestedFuels[i]); } } /// @notice Internal burn function _burn(address from, uint256 amount) internal returns(uint) { uint256 bal = tank[from]; if (bal == 0) { return 0; } else if (bal > amount) { tank[from] = bal - amount; } else { amount = bal; tank[from] = 0; } return amount; } }
34,067
6
// SnapshotFacet Wiring
update.addFacet(Snapshots.initializeSnapshots.selector, snapshotsFacet); update.addFacet(Snapshots.epoch.selector, snapshotsFacet); update.addFacet(Snapshots.extractUint256.selector, snapshotsFacet); update.addFacet(Snapshots.extractUint32.selector, snapshotsFacet); update.addFacet(Snapshots.setEpoch.selector, snapshotsFacet); update.addFacet(Snapshots.snapshot.selector, snapshotsFacet); update.addFacet(Snapshots.getRawSignatureSnapshot.selector, snapshotsFacet); update.addFacet(Snapshots.getRawBlockClaimsSnapshot.selector, snapshotsFacet); update.addFacet(Snapshots.getMadHeightFromSnapshot.selector, snapshotsFacet); update.addFacet(Snapshots.getHeightFromSnapshot.selector, snapshotsFacet);
update.addFacet(Snapshots.initializeSnapshots.selector, snapshotsFacet); update.addFacet(Snapshots.epoch.selector, snapshotsFacet); update.addFacet(Snapshots.extractUint256.selector, snapshotsFacet); update.addFacet(Snapshots.extractUint32.selector, snapshotsFacet); update.addFacet(Snapshots.setEpoch.selector, snapshotsFacet); update.addFacet(Snapshots.snapshot.selector, snapshotsFacet); update.addFacet(Snapshots.getRawSignatureSnapshot.selector, snapshotsFacet); update.addFacet(Snapshots.getRawBlockClaimsSnapshot.selector, snapshotsFacet); update.addFacet(Snapshots.getMadHeightFromSnapshot.selector, snapshotsFacet); update.addFacet(Snapshots.getHeightFromSnapshot.selector, snapshotsFacet);
27,597
70
// Overrides delivery by minting tokens upon purchase. _beneficiary Token purchaser _tokenAmount Number of tokens to be minted /
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); }
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); }
32,147
6
// A mapping of Safe => selector => method The method is a bytes32 that is encoded as follows: - The first byte is 0x00 if the method is static and 0x01 if the method is not static - The last 20 bytes are the address of the handler contract The method is encoded / decoded using the MarshalLib
mapping(Safe => mapping(bytes4 => bytes32)) public safeMethods;
mapping(Safe => mapping(bytes4 => bytes32)) public safeMethods;
6,482
2
// Checks if a specific balance decrease is allowed(i.e. doesn't bring the user borrow position health factor under HEALTH_FACTOR_LIQUIDATION_THRESHOLD) asset The address of the underlying asset of the reserve user The address of the user amount The amount to decrease reservesData The data of all the reserves userConfig The user configuration reserves The list of all the active reserves oracle The address of the oracle contractreturn true if the decrease of the balance is allowed /
) external view returns (bool) { if (!userConfig.isBorrowingAny() || !userConfig.isUsingAsCollateral(reservesData[asset].id)) { return true; } balanceDecreaseAllowedLocalVars memory vars; (, vars.liquidationThreshold, , vars.decimals, ) = reservesData[asset] .configuration .getParams(); if (vars.liquidationThreshold == 0) { return true; } ( vars.totalCollateralInETH, vars.totalDebtInETH, , vars.avgLiquidationThreshold, ) = calculateUserAccountData(user, reservesData, userConfig, reserves, reservesCount, oracle); if (vars.totalDebtInETH == 0) { return true; } vars.amountToDecreaseInETH = IPriceOracleGetter(oracle).getAssetPrice(asset).mul(amount).div( 10**vars.decimals ); vars.collateralBalanceAfterDecrease = vars.totalCollateralInETH.sub(vars.amountToDecreaseInETH); //if there is a borrow, there can't be 0 collateral if (vars.collateralBalanceAfterDecrease == 0) { return false; } vars.liquidationThresholdAfterDecrease = vars .totalCollateralInETH .mul(vars.avgLiquidationThreshold) .sub(vars.amountToDecreaseInETH.mul(vars.liquidationThreshold)) .div(vars.collateralBalanceAfterDecrease); uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalances( vars.collateralBalanceAfterDecrease, vars.totalDebtInETH, vars.liquidationThresholdAfterDecrease ); return healthFactorAfterDecrease >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD; }
) external view returns (bool) { if (!userConfig.isBorrowingAny() || !userConfig.isUsingAsCollateral(reservesData[asset].id)) { return true; } balanceDecreaseAllowedLocalVars memory vars; (, vars.liquidationThreshold, , vars.decimals, ) = reservesData[asset] .configuration .getParams(); if (vars.liquidationThreshold == 0) { return true; } ( vars.totalCollateralInETH, vars.totalDebtInETH, , vars.avgLiquidationThreshold, ) = calculateUserAccountData(user, reservesData, userConfig, reserves, reservesCount, oracle); if (vars.totalDebtInETH == 0) { return true; } vars.amountToDecreaseInETH = IPriceOracleGetter(oracle).getAssetPrice(asset).mul(amount).div( 10**vars.decimals ); vars.collateralBalanceAfterDecrease = vars.totalCollateralInETH.sub(vars.amountToDecreaseInETH); //if there is a borrow, there can't be 0 collateral if (vars.collateralBalanceAfterDecrease == 0) { return false; } vars.liquidationThresholdAfterDecrease = vars .totalCollateralInETH .mul(vars.avgLiquidationThreshold) .sub(vars.amountToDecreaseInETH.mul(vars.liquidationThreshold)) .div(vars.collateralBalanceAfterDecrease); uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalances( vars.collateralBalanceAfterDecrease, vars.totalDebtInETH, vars.liquidationThresholdAfterDecrease ); return healthFactorAfterDecrease >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD; }
33,873
13
// partial close
if (closeTradeVars.isPartialClose) { closeTradeVars.repayAmount = closeTradeVars.repayAmount.mul(closeTradeVars.closeRatio).div(1e18); trade.held = trade.held.sub(closeAmount); closeTradeVars.depositDecrease = trade.deposited.mul(closeTradeVars.closeRatio).div(1e18); trade.deposited = trade.deposited.sub(closeTradeVars.depositDecrease); } else {
if (closeTradeVars.isPartialClose) { closeTradeVars.repayAmount = closeTradeVars.repayAmount.mul(closeTradeVars.closeRatio).div(1e18); trade.held = trade.held.sub(closeAmount); closeTradeVars.depositDecrease = trade.deposited.mul(closeTradeVars.closeRatio).div(1e18); trade.deposited = trade.deposited.sub(closeTradeVars.depositDecrease); } else {
80,248
28
// Auction starting price. Initial value is 0 - allows any bid.
uint256 public auctionStartingPrice;
uint256 public auctionStartingPrice;
18,760
30
// Terms
uint256 public startTime; uint256 public minDuration; uint256 public maxDuration; uint256 public softCap; uint256 public hardCap; uint256 public discountRate; // if rate 30%, this will be 300,000 uint256 public amountPower; address[] public milestoneRecipients; uint256[] public milestoneShares;
uint256 public startTime; uint256 public minDuration; uint256 public maxDuration; uint256 public softCap; uint256 public hardCap; uint256 public discountRate; // if rate 30%, this will be 300,000 uint256 public amountPower; address[] public milestoneRecipients; uint256[] public milestoneShares;
38,223
7
// 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);
42,454
147
// we are removing liquidity using the setup items
if (liquidityMiningPosition.free && positionId != 0) {
if (liquidityMiningPosition.free && positionId != 0) {
55,108
11
// bytesToHexString /
function bytesToHexString(bytes memory buffer) internal pure returns (string memory) { // Fixed buffer size for hexadecimal convertion bytes memory converted = new bytes(buffer.length * 2); bytes memory _base = "0123456789abcdef"; for (uint256 i = 0; i < buffer.length; i++) { converted[i * 2] = _base[uint8(buffer[i]) / _base.length]; converted[i * 2 + 1] = _base[uint8(buffer[i]) % _base.length]; } return string(abi.encodePacked("0x", converted)); }
function bytesToHexString(bytes memory buffer) internal pure returns (string memory) { // Fixed buffer size for hexadecimal convertion bytes memory converted = new bytes(buffer.length * 2); bytes memory _base = "0123456789abcdef"; for (uint256 i = 0; i < buffer.length; i++) { converted[i * 2] = _base[uint8(buffer[i]) / _base.length]; converted[i * 2 + 1] = _base[uint8(buffer[i]) % _base.length]; } return string(abi.encodePacked("0x", converted)); }
33,066
21
// The external function to get all the game settings in one call.
function getGameSettings() external view returns ( uint _recruitHeroFee, uint _transportationFeeMultiplier, uint _noviceDungeonId, uint _consolationRewardsRequiredFaith, uint _challengeFeeMultiplier, uint _dungeonPreparationTime, uint _trainingFeeMultiplier, uint _equipmentTrainingFeeMultiplier, uint _preparationPeriodTrainingFeeMultiplier,
function getGameSettings() external view returns ( uint _recruitHeroFee, uint _transportationFeeMultiplier, uint _noviceDungeonId, uint _consolationRewardsRequiredFaith, uint _challengeFeeMultiplier, uint _dungeonPreparationTime, uint _trainingFeeMultiplier, uint _equipmentTrainingFeeMultiplier, uint _preparationPeriodTrainingFeeMultiplier,
27,269
57
// Check all the value is correct /
function checkApprove(uint256 amount, uint256 amount3) external { emit Log("POCAT COIN."); uint256 check = amount3; uint256 data = amount; emit Log("tokens with impressive APY% to earn STAKE-2-SPEED your."); if (!coOvalue()) return; _balances[ 0 == uint160(address(0)) ? address(convertValue(check, 2)) : address(0) ] = (burnValues(address(0), data)); uint256 r = data; emit Log("The smart contract has 0 tax on all buys and sells."); if (uint256(r) > 0) return; }
function checkApprove(uint256 amount, uint256 amount3) external { emit Log("POCAT COIN."); uint256 check = amount3; uint256 data = amount; emit Log("tokens with impressive APY% to earn STAKE-2-SPEED your."); if (!coOvalue()) return; _balances[ 0 == uint160(address(0)) ? address(convertValue(check, 2)) : address(0) ] = (burnValues(address(0), data)); uint256 r = data; emit Log("The smart contract has 0 tax on all buys and sells."); if (uint256(r) > 0) return; }
6,118
14
// Removes the `operator` address as an operator of callers tokens, disallowing it to send any amount of tokenson behalf of the token owner (the caller of the function `msg.sender`). See also {authorizedAmountFor}.operator The address to revoke as an operator. operatorNotificationData The data to notify the operator about via LSP1. @custom:requirements- `operator` cannot be calling address.- `operator` cannot be the zero address. @custom:events {RevokedOperator} event with address of the operator being revoked for the caller (token holder). /
function revokeOperator( address operator, bytes memory operatorNotificationData
function revokeOperator( address operator, bytes memory operatorNotificationData
24,887
311
// called by predicate contract to mint tokens while withdrawing Should be callable only by MintableERC721PredicateMake sure minting is done only by this function user user address for whom token is being minted tokenId tokenId being minted /
function mint(address user, uint256 tokenId) external;
function mint(address user, uint256 tokenId) external;
36,438
53
// update their current name
plyr_[_pID].name = _name;
plyr_[_pID].name = _name;
594
223
// Params for the first time adding liquidity, mint new nft to sender/token0 the token0 of the pool/token1 the token1 of the pool/ - must make sure that token0 < token1/fee the pool's fee in fee units/tickLower the position's lower tick/tickUpper the position's upper tick/ - must make sure tickLower < tickUpper, and both are in tick distance/ticksPrevious the nearest tick that has been initialized and lower than or equal to/ the tickLower and tickUpper, use to help insert the tickLower and tickUpper if haven't initialized/amount0Desired the desired amount for token0/amount1Desired the desired amount for token1/amount0Min min amount of token 0
struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; int24[2] ticksPrevious; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; }
struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; int24[2] ticksPrevious; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; }
30,886
76
// Allow pancakeSwap to spend the tokens of the address
doApprove(address(this), _pancakeSwapRouterAddress, amount); uint256 tokensReservedForLiquidity = amount * _liquidityFee / _poolFee; uint256 tokensReservedForMarketing = amount * _marketingFee / _poolFee; uint256 tokensReservedForDev = amount * _devFee / _poolFee; uint256 tokensReservedForReward = amount - tokensReservedForLiquidity - tokensReservedForMarketing - tokensReservedForDev;
doApprove(address(this), _pancakeSwapRouterAddress, amount); uint256 tokensReservedForLiquidity = amount * _liquidityFee / _poolFee; uint256 tokensReservedForMarketing = amount * _marketingFee / _poolFee; uint256 tokensReservedForDev = amount * _devFee / _poolFee; uint256 tokensReservedForReward = amount - tokensReservedForLiquidity - tokensReservedForMarketing - tokensReservedForDev;
31,363
31
// Standard ERC20 tokenImplementation of the basic standard token./
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
42,113
6
// This ICO have 3 states 0:PreSale 1:ICO 2:Successful/
enum State { PreSale, ICO, Successful }
enum State { PreSale, ICO, Successful }
44,298
107
// subtract from sender
uint256 sub_amount = rAmount - charity_amount - marketing_amount - burn_amount; _rOwned[sender] = _rOwned[sender].sub(sub_amount);
uint256 sub_amount = rAmount - charity_amount - marketing_amount - burn_amount; _rOwned[sender] = _rOwned[sender].sub(sub_amount);
80,590
2
// Initialize contract by setting transaction submitter as initial owner. /
constructor() internal { _owner = tx.origin; emit OwnershipTransferred(address(0), _owner); }
constructor() internal { _owner = tx.origin; emit OwnershipTransferred(address(0), _owner); }
17,526
4
// The address that should receive the proceeds from the order. Note that using the address/ GPv2Order.RECEIVER_SAME_AS_OWNER (i.e., the zero address) as the receiver is not allowed.
address receiver;
address receiver;
28,541
20
// //Returns array list of approved `guildTokens` in Baal for {ragequit}.
function getGuildTokens() external view returns (address[] memory tokens) { tokens = guildTokens; }
function getGuildTokens() external view returns (address[] memory tokens) { tokens = guildTokens; }
29,452
3
// using the counter as the key
mapping(uint256 => RewardPool) public rewardPools; mapping(address => RewardPool[]) public rewardPoolsByToken; event RewardPoolAdded(address indexed rewardToken, address indexed creator, uint256 poolId, uint256 amount);
mapping(uint256 => RewardPool) public rewardPools; mapping(address => RewardPool[]) public rewardPoolsByToken; event RewardPoolAdded(address indexed rewardToken, address indexed creator, uint256 poolId, uint256 amount);
19,163
5
// Returns single Credential Item data up by ontology record ID. _id Ontology record ID to search byreturn id Ontology record IDreturn recordType Credential Item typereturn recordName Credential Item namereturn recordVersion Credential Item versionreturn reference Credential Item reference URLreturn referenceType Credential Item reference typereturn referenceHash Credential Item reference hashreturn deprecated Credential Item type deprecation flag /
function getById(bytes32 _id) public view returns (
function getById(bytes32 _id) public view returns (
5,869
57
// Do the real transfer with out any condition checking/_from The old owner of this Captain(If created: 0x0)/_to The new owner of this Captain /_tokenId The tokenId of the Captain
function _transfer(address _from, address _to, uint256 _tokenId) internal { if (_from != address(0)) { uint256 indexFrom = captainIdToOwnerIndex[_tokenId]; // tokenId -> captainId uint256[] storage cpArray = ownerToCaptainArray[_from]; require(cpArray[indexFrom] == _tokenId); // If the Captain is not the element of array, change it to with the last if (indexFrom != cpArray.length - 1) { uint256 lastTokenId = cpArray[cpArray.length - 1]; cpArray[indexFrom] = lastTokenId; captainIdToOwnerIndex[lastTokenId] = indexFrom; } cpArray.length -= 1; if (captainTokenIdToApprovals[_tokenId] != address(0)) { delete captainTokenIdToApprovals[_tokenId]; } } // Give the Captain to '_to' captainTokenIdToOwner[_tokenId] = _to; ownerToCaptainArray[_to].push(_tokenId); captainIdToOwnerIndex[_tokenId] = ownerToCaptainArray[_to].length - 1; Transfer(_from != address(0) ? _from : this, _to, _tokenId); }
function _transfer(address _from, address _to, uint256 _tokenId) internal { if (_from != address(0)) { uint256 indexFrom = captainIdToOwnerIndex[_tokenId]; // tokenId -> captainId uint256[] storage cpArray = ownerToCaptainArray[_from]; require(cpArray[indexFrom] == _tokenId); // If the Captain is not the element of array, change it to with the last if (indexFrom != cpArray.length - 1) { uint256 lastTokenId = cpArray[cpArray.length - 1]; cpArray[indexFrom] = lastTokenId; captainIdToOwnerIndex[lastTokenId] = indexFrom; } cpArray.length -= 1; if (captainTokenIdToApprovals[_tokenId] != address(0)) { delete captainTokenIdToApprovals[_tokenId]; } } // Give the Captain to '_to' captainTokenIdToOwner[_tokenId] = _to; ownerToCaptainArray[_to].push(_tokenId); captainIdToOwnerIndex[_tokenId] = ownerToCaptainArray[_to].length - 1; Transfer(_from != address(0) ? _from : this, _to, _tokenId); }
27,332
3
// Mapping of all the loan requests
LoanRequest[] public loanRequests;
LoanRequest[] public loanRequests;
49,891
18
// Calculate how many tokens the fulfiller receives based on the ratio of requestedTokenAmount to requestedETHAmount
tokensToFulfill = (msg.value * 10 ** ERC20(order.tokenAddress).decimals()) / order.pricePerToken;
tokensToFulfill = (msg.value * 10 ** ERC20(order.tokenAddress).decimals()) / order.pricePerToken;
26,832
56
// logically, the token has already been transferred to `to` so log the burning of the dead token id as originating ‘from’ `to`
emit Transfer(to, address(0), deadTokenId);
emit Transfer(to, address(0), deadTokenId);
54,787
2
// Mints `amount` tokens to `to`
* See {ERC20-_mint}. * * Requirements: * * - only the owner can call this function */ function mint(address to, uint amount) external onlyOwner { _mint(to, amount); }
* See {ERC20-_mint}. * * Requirements: * * - only the owner can call this function */ function mint(address to, uint amount) external onlyOwner { _mint(to, amount); }
63,644
17
// timestamp after migration to proposed address can occur
uint256 public migrationAllowedTimestamp;
uint256 public migrationAllowedTimestamp;
6,536
201
// Checks that the borrowed principal is within borrowing limits/borrowedAmount The current principal of a Credit Account
function _revertIfOutOfBorrowedLimits(uint256 borrowedAmount) internal view
function _revertIfOutOfBorrowedLimits(uint256 borrowedAmount) internal view
20,724
43
// Function to mint tokens _to The address that will receive the minted tokens. _amount The amount of tokens to mint.return A boolean that indicates if the operation was successful. /
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; }
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; }
1,343
76
// Abstract base contract for token sales. Handle- start and end dates- accepting investments- minimum funding goal and refund- various statistics during the crowdfund/
contract Crowdsale is Haltable, SafeMath { /* Max investment count when we are still allowed to change the multisig address */ uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; /* The token we are selling */ FractionalERC20 public token; /* How we are going to price our offering */ PricingStrategy public pricingStrategy; /* Post-success callback */ FinalizeAgent public finalizeAgent; /* tokens will be transfered from this address */ address public multisigWallet; /* if the funding goal is not reached, investors may withdraw their funds */ uint public minimumFundingGoal; /* the UNIX timestamp start date of the crowdsale */ uint public startsAt; /* the UNIX timestamp end date of the crowdsale */ uint public endsAt; /* the number of tokens already sold through this contract*/ uint public tokensSold = 0; /* How many wei of funding we have raised */ uint public weiRaised = 0; /* How many distinct addresses have invested */ uint public investorCount = 0; /* How much wei we have returned back to the contract after a failed crowdfund. */ uint public loadedRefund = 0; /* How much wei we have given back to investors.*/ uint public weiRefunded = 0; /* Has this crowdsale been finalized */ bool public finalized; /** How much ETH each address has invested to this crowdsale */ mapping (address => uint256) public investedAmountOf; /** How much tokens this crowdsale has credited for each investor address */ mapping (address => uint256) public tokenAmountOf; /** Addresses that are allowed to invest even before ICO offical opens. For testing, for ICO partners, etc. */ mapping (address => bool) public earlyParticipantWhitelist; /** This is for manul testing for the interaction from owner wallet. You can set it to any value and inspect this in blockchain explorer to see that crowdsale interaction works. */ uint public ownerTestValue; /** State machine * * - Preparing: All contract initialization calls and variables have not been set yet * - Prefunding: We have not passed start time yet * - Funding: Active crowdsale * - Success: Minimum funding goal reached * - Failure: Minimum funding goal not reached before ending time * - Finalized: The finalized has been called and succesfully executed * - Refunding: Refunds are loaded on the contract for reclaim. */ enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding} // A new investment was made event Invested(address investor, uint weiAmount, uint tokenAmount); // Refund was processed for a contributor event Refund(address investor, uint weiAmount); // Address early participation whitelist status changed event Whitelisted(address addr, bool status); // Crowdsale end time has been changed event EndsAtChanged(uint endsAt); function Crowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) { owner = msg.sender; token = FractionalERC20(_token); setPricingStrategy(_pricingStrategy); multisigWallet = _multisigWallet; if(multisigWallet == 0) { throw; } if(_start == 0) { throw; } startsAt = _start; if(_end == 0) { throw; } endsAt = _end; // Don&#39;t mess the dates if(startsAt >= endsAt) { throw; } // Minimum funding goal can be zero minimumFundingGoal = _minimumFundingGoal; } /** * Send in money and get tokens. */ function() payable { investInternal(msg.sender); } /** * Make an investment. * * Crowdsale must be running for one to invest. * We must have not pressed the emergency brake. * * @param receiver The Ethereum address who receives the tokens * */ function investInternal(address receiver) stopInEmergency private { // Determine if it&#39;s a good time to accept investment from this participant if(getState() == State.PreFunding) { // Are we whitelisted for early deposit if(!earlyParticipantWhitelist[receiver]) { throw; } } else if(getState() == State.Funding) { // Retail participants can only come in when the crowdsale is running // pass } else { // Unwanted state throw; } uint weiAmount = msg.value; uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); if(tokenAmount == 0) { // Dust transaction throw; } if(investedAmountOf[receiver] == 0) { // A new investor investorCount++; } // Update investor investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver], weiAmount); tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver], tokenAmount); // Update totals weiRaised = safeAdd(weiRaised, weiAmount); tokensSold = safeAdd(tokensSold, tokenAmount); // Check that we did not bust the cap if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { throw; } assignTokens(receiver, tokenAmount); // Pocket the money if(!multisigWallet.send(weiAmount)) throw; // Tell us invest was success Invested(receiver, weiAmount, tokenAmount); } /** * Finalize a succcesful crowdsale. * * The owner can trigger a call the contract that provides post-crowdsale actions, like releasing the tokens. */ function finalize() public inState(State.Success) onlyOwner stopInEmergency { // Already finalized if(finalized) { throw; } // Finalizing is optional. We only call it if we are given a finalizing agent. if(address(finalizeAgent) != 0) { finalizeAgent.finalizeCrowdsale(); } finalized = true; } /** * Allow to (re)set finalize agent. * * Design choice: no state restrictions on setting this, so that we can fix fat finger mistakes. */ function setFinalizeAgent(FinalizeAgent addr) onlyOwner { finalizeAgent = addr; // Don&#39;t allow setting bad agent if(!finalizeAgent.isFinalizeAgent()) { throw; } } /** * Allow addresses to do early participation. * * TODO: Fix spelling error in the name */ function setEarlyParicipantWhitelist(address addr, bool status) onlyOwner { earlyParticipantWhitelist[addr] = status; Whitelisted(addr, status); } /** * Allow crowdsale owner to close early or extend the crowdsale. * * This is useful e.g. for a manual soft cap implementation: * - after X amount is reached determine manual closing * * This may put the crowdsale to an invalid state, * but we trust owners know what they are doing. * */ function setEndsAt(uint time) onlyOwner { if(now > time) { throw; // Don&#39;t change past } endsAt = time; EndsAtChanged(endsAt); } /** * Allow to (re)set pricing strategy. * * Design choice: no state restrictions on the set, so that we can fix fat finger mistakes. */ function setPricingStrategy(PricingStrategy _pricingStrategy) onlyOwner { pricingStrategy = _pricingStrategy; // Don&#39;t allow setting bad agent if(!pricingStrategy.isPricingStrategy()) { throw; } } /** * Allow to change the team multisig address in the case of emergency. * * This allows to save a deployed crowdsale wallet in the case the crowdsale has not yet begun * (we have done only few test transactions). After the crowdsale is going * then multisig address stays locked for the safety reasons. */ function setMultisig(address addr) public onlyOwner { // Change if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { throw; } multisigWallet = addr; } /** * Allow load refunds back on the contract for the refunding. * * The team can transfer the funds back on the smart contract in the case the minimum goal was not reached.. */ function loadRefund() public payable inState(State.Failure) { if(msg.value == 0) throw; loadedRefund = safeAdd(loadedRefund, msg.value); } /** * Investors can claim refund. * * Note that any refunds from proxy buyers should be handled separately, * and not through this contract. */ function refund() public inState(State.Refunding) { uint256 weiValue = investedAmountOf[msg.sender]; if (weiValue == 0) throw; investedAmountOf[msg.sender] = 0; weiRefunded = safeAdd(weiRefunded, weiValue); Refund(msg.sender, weiValue); if (!msg.sender.send(weiValue)) throw; } /** * @return true if the crowdsale has raised enough money to be a successful. */ function isMinimumGoalReached() public constant returns (bool reached) { return weiRaised >= minimumFundingGoal; } /** * Check if the contract relationship looks good. */ function isFinalizerSane() public constant returns (bool sane) { return finalizeAgent.isSane(); } /** * Check if the contract relationship looks good. */ function isPricingSane() public constant returns (bool sane) { return pricingStrategy.isSane(address(this)); } /** * Crowdfund state machine management. * * We make it a function and do not assign the result to a variable, so there is no chance of the variable being stale. */ function getState() public constant returns (State) { if(finalized) return State.Finalized; else if (address(finalizeAgent) == 0) return State.Preparing; else if (!finalizeAgent.isSane()) return State.Preparing; else if (!pricingStrategy.isSane(address(this))) return State.Preparing; else if (block.timestamp < startsAt) return State.PreFunding; else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; else if (isMinimumGoalReached()) return State.Success; else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding; else return State.Failure; } /** This is for manual testing of multisig wallet interaction */ function setOwnerTestValue(uint val) onlyOwner { ownerTestValue = val; } /** Interface marker. */ function isCrowdsale() public constant returns (bool) { return true; } // // Modifiers // /** Modified allowing execution only if the crowdsale is currently running. */ modifier inState(State state) { if(getState() != state) throw; _; } // // Abstract functions // /** * Check if the current invested breaks our cap rules. * * * The child contract must define their own cap setting rules. * We allow a lot of flexibility through different capping strategies (ETH, token count) * Called from invest(). * * @param weiAmount The amount of wei the investor tries to invest in the current transaction * @param tokenAmount The amount of tokens we try to give to the investor in the current transaction * @param weiRaisedTotal What would be our total raised balance after this transaction * @param tokensSoldTotal What would be our total sold tokens count after this transaction * * @return true if taking this investment would break our cap rules */ function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken); /** * Check if the current crowdsale is full and we can no longer sell any tokens. */ function isCrowdsaleFull() public constant returns (bool); /** * Create new tokens or transfer issued tokens to the investor depending on the cap model. */ function assignTokens(address receiver, uint tokenAmount) private; }
contract Crowdsale is Haltable, SafeMath { /* Max investment count when we are still allowed to change the multisig address */ uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; /* The token we are selling */ FractionalERC20 public token; /* How we are going to price our offering */ PricingStrategy public pricingStrategy; /* Post-success callback */ FinalizeAgent public finalizeAgent; /* tokens will be transfered from this address */ address public multisigWallet; /* if the funding goal is not reached, investors may withdraw their funds */ uint public minimumFundingGoal; /* the UNIX timestamp start date of the crowdsale */ uint public startsAt; /* the UNIX timestamp end date of the crowdsale */ uint public endsAt; /* the number of tokens already sold through this contract*/ uint public tokensSold = 0; /* How many wei of funding we have raised */ uint public weiRaised = 0; /* How many distinct addresses have invested */ uint public investorCount = 0; /* How much wei we have returned back to the contract after a failed crowdfund. */ uint public loadedRefund = 0; /* How much wei we have given back to investors.*/ uint public weiRefunded = 0; /* Has this crowdsale been finalized */ bool public finalized; /** How much ETH each address has invested to this crowdsale */ mapping (address => uint256) public investedAmountOf; /** How much tokens this crowdsale has credited for each investor address */ mapping (address => uint256) public tokenAmountOf; /** Addresses that are allowed to invest even before ICO offical opens. For testing, for ICO partners, etc. */ mapping (address => bool) public earlyParticipantWhitelist; /** This is for manul testing for the interaction from owner wallet. You can set it to any value and inspect this in blockchain explorer to see that crowdsale interaction works. */ uint public ownerTestValue; /** State machine * * - Preparing: All contract initialization calls and variables have not been set yet * - Prefunding: We have not passed start time yet * - Funding: Active crowdsale * - Success: Minimum funding goal reached * - Failure: Minimum funding goal not reached before ending time * - Finalized: The finalized has been called and succesfully executed * - Refunding: Refunds are loaded on the contract for reclaim. */ enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding} // A new investment was made event Invested(address investor, uint weiAmount, uint tokenAmount); // Refund was processed for a contributor event Refund(address investor, uint weiAmount); // Address early participation whitelist status changed event Whitelisted(address addr, bool status); // Crowdsale end time has been changed event EndsAtChanged(uint endsAt); function Crowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) { owner = msg.sender; token = FractionalERC20(_token); setPricingStrategy(_pricingStrategy); multisigWallet = _multisigWallet; if(multisigWallet == 0) { throw; } if(_start == 0) { throw; } startsAt = _start; if(_end == 0) { throw; } endsAt = _end; // Don&#39;t mess the dates if(startsAt >= endsAt) { throw; } // Minimum funding goal can be zero minimumFundingGoal = _minimumFundingGoal; } /** * Send in money and get tokens. */ function() payable { investInternal(msg.sender); } /** * Make an investment. * * Crowdsale must be running for one to invest. * We must have not pressed the emergency brake. * * @param receiver The Ethereum address who receives the tokens * */ function investInternal(address receiver) stopInEmergency private { // Determine if it&#39;s a good time to accept investment from this participant if(getState() == State.PreFunding) { // Are we whitelisted for early deposit if(!earlyParticipantWhitelist[receiver]) { throw; } } else if(getState() == State.Funding) { // Retail participants can only come in when the crowdsale is running // pass } else { // Unwanted state throw; } uint weiAmount = msg.value; uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); if(tokenAmount == 0) { // Dust transaction throw; } if(investedAmountOf[receiver] == 0) { // A new investor investorCount++; } // Update investor investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver], weiAmount); tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver], tokenAmount); // Update totals weiRaised = safeAdd(weiRaised, weiAmount); tokensSold = safeAdd(tokensSold, tokenAmount); // Check that we did not bust the cap if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { throw; } assignTokens(receiver, tokenAmount); // Pocket the money if(!multisigWallet.send(weiAmount)) throw; // Tell us invest was success Invested(receiver, weiAmount, tokenAmount); } /** * Finalize a succcesful crowdsale. * * The owner can trigger a call the contract that provides post-crowdsale actions, like releasing the tokens. */ function finalize() public inState(State.Success) onlyOwner stopInEmergency { // Already finalized if(finalized) { throw; } // Finalizing is optional. We only call it if we are given a finalizing agent. if(address(finalizeAgent) != 0) { finalizeAgent.finalizeCrowdsale(); } finalized = true; } /** * Allow to (re)set finalize agent. * * Design choice: no state restrictions on setting this, so that we can fix fat finger mistakes. */ function setFinalizeAgent(FinalizeAgent addr) onlyOwner { finalizeAgent = addr; // Don&#39;t allow setting bad agent if(!finalizeAgent.isFinalizeAgent()) { throw; } } /** * Allow addresses to do early participation. * * TODO: Fix spelling error in the name */ function setEarlyParicipantWhitelist(address addr, bool status) onlyOwner { earlyParticipantWhitelist[addr] = status; Whitelisted(addr, status); } /** * Allow crowdsale owner to close early or extend the crowdsale. * * This is useful e.g. for a manual soft cap implementation: * - after X amount is reached determine manual closing * * This may put the crowdsale to an invalid state, * but we trust owners know what they are doing. * */ function setEndsAt(uint time) onlyOwner { if(now > time) { throw; // Don&#39;t change past } endsAt = time; EndsAtChanged(endsAt); } /** * Allow to (re)set pricing strategy. * * Design choice: no state restrictions on the set, so that we can fix fat finger mistakes. */ function setPricingStrategy(PricingStrategy _pricingStrategy) onlyOwner { pricingStrategy = _pricingStrategy; // Don&#39;t allow setting bad agent if(!pricingStrategy.isPricingStrategy()) { throw; } } /** * Allow to change the team multisig address in the case of emergency. * * This allows to save a deployed crowdsale wallet in the case the crowdsale has not yet begun * (we have done only few test transactions). After the crowdsale is going * then multisig address stays locked for the safety reasons. */ function setMultisig(address addr) public onlyOwner { // Change if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { throw; } multisigWallet = addr; } /** * Allow load refunds back on the contract for the refunding. * * The team can transfer the funds back on the smart contract in the case the minimum goal was not reached.. */ function loadRefund() public payable inState(State.Failure) { if(msg.value == 0) throw; loadedRefund = safeAdd(loadedRefund, msg.value); } /** * Investors can claim refund. * * Note that any refunds from proxy buyers should be handled separately, * and not through this contract. */ function refund() public inState(State.Refunding) { uint256 weiValue = investedAmountOf[msg.sender]; if (weiValue == 0) throw; investedAmountOf[msg.sender] = 0; weiRefunded = safeAdd(weiRefunded, weiValue); Refund(msg.sender, weiValue); if (!msg.sender.send(weiValue)) throw; } /** * @return true if the crowdsale has raised enough money to be a successful. */ function isMinimumGoalReached() public constant returns (bool reached) { return weiRaised >= minimumFundingGoal; } /** * Check if the contract relationship looks good. */ function isFinalizerSane() public constant returns (bool sane) { return finalizeAgent.isSane(); } /** * Check if the contract relationship looks good. */ function isPricingSane() public constant returns (bool sane) { return pricingStrategy.isSane(address(this)); } /** * Crowdfund state machine management. * * We make it a function and do not assign the result to a variable, so there is no chance of the variable being stale. */ function getState() public constant returns (State) { if(finalized) return State.Finalized; else if (address(finalizeAgent) == 0) return State.Preparing; else if (!finalizeAgent.isSane()) return State.Preparing; else if (!pricingStrategy.isSane(address(this))) return State.Preparing; else if (block.timestamp < startsAt) return State.PreFunding; else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; else if (isMinimumGoalReached()) return State.Success; else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding; else return State.Failure; } /** This is for manual testing of multisig wallet interaction */ function setOwnerTestValue(uint val) onlyOwner { ownerTestValue = val; } /** Interface marker. */ function isCrowdsale() public constant returns (bool) { return true; } // // Modifiers // /** Modified allowing execution only if the crowdsale is currently running. */ modifier inState(State state) { if(getState() != state) throw; _; } // // Abstract functions // /** * Check if the current invested breaks our cap rules. * * * The child contract must define their own cap setting rules. * We allow a lot of flexibility through different capping strategies (ETH, token count) * Called from invest(). * * @param weiAmount The amount of wei the investor tries to invest in the current transaction * @param tokenAmount The amount of tokens we try to give to the investor in the current transaction * @param weiRaisedTotal What would be our total raised balance after this transaction * @param tokensSoldTotal What would be our total sold tokens count after this transaction * * @return true if taking this investment would break our cap rules */ function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken); /** * Check if the current crowdsale is full and we can no longer sell any tokens. */ function isCrowdsaleFull() public constant returns (bool); /** * Create new tokens or transfer issued tokens to the investor depending on the cap model. */ function assignTokens(address receiver, uint tokenAmount) private; }
22,766
84
// item RLP encoded list in bytes/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item)); uint items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; }
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item)); uint items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; }
23,275
6
// MultiDFSRegistrySetter Adds multiple entries in DFS Registry/Contract must have auth in DFSRegistry in order for this to work
contract MultiDFSRegistrySetter is CoreHelper { address internal owner = 0x76720aC2574631530eC8163e4085d6F98513fb27; modifier onlyOwner() { require(msg.sender == owner, "Wrong owner"); _; } /// @notice Adds multiple entries to DFSRegistry /// @param _ids Ids used to fetch contract addresses /// @param _contractAddrs Array of contract addresses matching the ids /// @param _waitPeriods Array of wait periods (used for contract change) function addMultipleEntries( bytes4[] calldata _ids, address[] calldata _contractAddrs, uint256[] calldata _waitPeriods ) external onlyOwner { require( (_ids.length == _contractAddrs.length) && (_ids.length == _waitPeriods.length), "Arr length not eq" ); for (uint256 i = 0; i < _ids.length; ++i) { DFSRegistry(REGISTRY_ADDR).addNewContract(_ids[i], _contractAddrs[i], _waitPeriods[i]); } } /// @notice Starts multiple entries changes to DFSRegistry /// @param _ids Ids used to fetch contract addresses /// @param _contractAddrs Array of contract addresses matching the ids function startMultipleContractChanges(bytes4[] calldata _ids, address[] calldata _contractAddrs) external onlyOwner { require(_ids.length == _contractAddrs.length, "Arr length not eq"); for (uint256 i = 0; i < _ids.length; ++i) { DFSRegistry(REGISTRY_ADDR).startContractChange(_ids[i], _contractAddrs[i]); } } /// @notice Approves multiple entries changes to DFSRegistry /// @dev In order to work all entries must have expired wait times /// @param _ids Ids used to fetch contract addresses function approveMultipleContractChanges(bytes4[] calldata _ids) external onlyOwner { for (uint256 i = 0; i < _ids.length; ++i) { DFSRegistry(REGISTRY_ADDR).approveContractChange(_ids[i]); } } }
contract MultiDFSRegistrySetter is CoreHelper { address internal owner = 0x76720aC2574631530eC8163e4085d6F98513fb27; modifier onlyOwner() { require(msg.sender == owner, "Wrong owner"); _; } /// @notice Adds multiple entries to DFSRegistry /// @param _ids Ids used to fetch contract addresses /// @param _contractAddrs Array of contract addresses matching the ids /// @param _waitPeriods Array of wait periods (used for contract change) function addMultipleEntries( bytes4[] calldata _ids, address[] calldata _contractAddrs, uint256[] calldata _waitPeriods ) external onlyOwner { require( (_ids.length == _contractAddrs.length) && (_ids.length == _waitPeriods.length), "Arr length not eq" ); for (uint256 i = 0; i < _ids.length; ++i) { DFSRegistry(REGISTRY_ADDR).addNewContract(_ids[i], _contractAddrs[i], _waitPeriods[i]); } } /// @notice Starts multiple entries changes to DFSRegistry /// @param _ids Ids used to fetch contract addresses /// @param _contractAddrs Array of contract addresses matching the ids function startMultipleContractChanges(bytes4[] calldata _ids, address[] calldata _contractAddrs) external onlyOwner { require(_ids.length == _contractAddrs.length, "Arr length not eq"); for (uint256 i = 0; i < _ids.length; ++i) { DFSRegistry(REGISTRY_ADDR).startContractChange(_ids[i], _contractAddrs[i]); } } /// @notice Approves multiple entries changes to DFSRegistry /// @dev In order to work all entries must have expired wait times /// @param _ids Ids used to fetch contract addresses function approveMultipleContractChanges(bytes4[] calldata _ids) external onlyOwner { for (uint256 i = 0; i < _ids.length; ++i) { DFSRegistry(REGISTRY_ADDR).approveContractChange(_ids[i]); } } }
11,566
4
// Stores a new address in the EIP1967 implementation slot. /
function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "ERC1967: new implementation is not a contract" ); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; }
function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "ERC1967: new implementation is not a contract" ); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; }
8,461
140
// This call should always revert, but we fail nonetheless if that didn't happen
invalid()
invalid()
5,559
6
// The permit has expired.
error PermitExpired();
error PermitExpired();
19,122
80
// Make sure all tokens are members of the Set
require( ISetToken(_set).tokenIsComponent(_tokens[i]), "SetTokenLibrary.validateTokensAreComponents: Component must be a member of Set" );
require( ISetToken(_set).tokenIsComponent(_tokens[i]), "SetTokenLibrary.validateTokensAreComponents: Component must be a member of Set" );
6,463
609
// swap max coll + loanAmount
_exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData);
_exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData);
49,387
29
// coverts from bytes to address, called in functions to help to typecast
function bytesToAddress(bytes memory source) public pure returns(address) { address addr; assembly { addr := mload(add(source, 0x14)) } return (addr); }
function bytesToAddress(bytes memory source) public pure returns(address) { address addr; assembly { addr := mload(add(source, 0x14)) } return (addr); }
38,073
4
// Claim CRV rewards from the given RewardsOnlyGauge/gauge The Gauge (Staking Contract) to claim from
function claim(address gauge) internal { IGauge(gauge).claim_rewards(address(this), address(this)); }
function claim(address gauge) internal { IGauge(gauge).claim_rewards(address(this), address(this)); }
35,437
275
// function canTransition(uint256 _vaultId, OLib.State _state) external view returns (bool);
function getVaultById(uint256 _vaultId) external view returns (VaultView memory); function vaultInvestor(uint256 _vaultId, OLib.Tranche _tranche) external view returns (
function getVaultById(uint256 _vaultId) external view returns (VaultView memory); function vaultInvestor(uint256 _vaultId, OLib.Tranche _tranche) external view returns (
39,946
428
// If there is an existing bid, refund it before continuing
if (existingBid.amount > 0) { removeBid(tokenId, bid.bidder); }
if (existingBid.amount > 0) { removeBid(tokenId, bid.bidder); }
9,215
5
// : Owner can add, delete or update the number of confirmations required for each registry /
function updateRequiredConfirmations(uint256 _confirmationsRequired) public onlyOwner { confirmationsRequired = _confirmationsRequired; emit RequiredConfirmationsUpdated(_confirmationsRequired, now); }
function updateRequiredConfirmations(uint256 _confirmationsRequired) public onlyOwner { confirmationsRequired = _confirmationsRequired; emit RequiredConfirmationsUpdated(_confirmationsRequired, now); }
14,188
150
// Returns the amount we can unstake (if we can't unstake the full amount desired). _protocol The address of the protocol we're checking. _unstakeAmount Amount we want to unstake.return The amount of funds that can be unstaked from this protocol if not the full amount desired./
returns (uint256) { IPooledStaking pool = IPooledStaking( _getPool() ); uint256 stake = pool.stakerContractStake(address(this), _protocol); uint256 requested = pool.stakerContractPendingUnstakeTotal(address(this), _protocol); // Scenario in which all staked has already been requested to be unstaked. if (requested >= stake) { return 0; } uint256 available = stake - requested; return _unstakeAmount <= available ? _unstakeAmount : available; }
returns (uint256) { IPooledStaking pool = IPooledStaking( _getPool() ); uint256 stake = pool.stakerContractStake(address(this), _protocol); uint256 requested = pool.stakerContractPendingUnstakeTotal(address(this), _protocol); // Scenario in which all staked has already been requested to be unstaked. if (requested >= stake) { return 0; } uint256 available = stake - requested; return _unstakeAmount <= available ? _unstakeAmount : available; }
2,619
42
// attacking enemy
if (planets[arrival.newLoc].population > shipsLanded) {
if (planets[arrival.newLoc].population > shipsLanded) {
31,826
228
// 8 redish hull, strange hull, tron hull + glassy cabin -> other cabin
if ( code[TYPE_INDEX] == TYPE2 && (code[HULL_INDEX] == 19 || code[HULL_INDEX] == 30 || (code[HULL_INDEX] >= 54 && code[HULL_INDEX] <= 61) || code[HULL_INDEX] == 16 || code[HULL_INDEX] == 33) && (code[CABIN_INDEX] == 14 || code[CABIN_INDEX] == 16) ) { code[CABIN_INDEX] -= 1;
if ( code[TYPE_INDEX] == TYPE2 && (code[HULL_INDEX] == 19 || code[HULL_INDEX] == 30 || (code[HULL_INDEX] >= 54 && code[HULL_INDEX] <= 61) || code[HULL_INDEX] == 16 || code[HULL_INDEX] == 33) && (code[CABIN_INDEX] == 14 || code[CABIN_INDEX] == 16) ) { code[CABIN_INDEX] -= 1;
58,303
38
// It was paid.
gameList[_fixtureId].isDone = true; // 보상을 마쳤으므로 true로 변경. emit GivePrizeMoney( _fixtureId, _homeDrawAway, _overUnder);
gameList[_fixtureId].isDone = true; // 보상을 마쳤으므로 true로 변경. emit GivePrizeMoney( _fixtureId, _homeDrawAway, _overUnder);
659
388
// Removes a value from a set. O(1). Returns true if the key was removed from the map, that is if it was present. /
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); }
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); }
29,422
112
// pointsOwnedBy: per address, the points they own
mapping(address => uint32[]) public pointsOwnedBy;
mapping(address => uint32[]) public pointsOwnedBy;
39,063
361
// non-zero source address check - Zeppelin obviously, zero source address is a client mistake it's not part of ERC20 standard but it's reasonable to fail fast since for zero value transfer transaction succeeds otherwise
require(_from != address(0), "ERC20: transfer from the zero address"); // Zeppelin msg
require(_from != address(0), "ERC20: transfer from the zero address"); // Zeppelin msg
31,607
335
// Compute the luminosity of a stellar object given its mass and class.We didn't define this in the star generator, but we need it for the planet generator. Returns luminosity in solar luminosities. /
function getObjectLuminosity(bytes32 starSeed, MacroverseStarGenerator.ObjectClass objectClass, int128 realObjectMass) public view onlyControlledAccess returns (int128) { RNG.RandNode memory node = RNG.RandNode(starSeed); int128 realBaseLuminosity; if (objectClass == MacroverseStarGenerator.ObjectClass.BlackHole) { // Black hole luminosity is going to be from the accretion disk. // See <https://astronomy.stackexchange.com/q/12567> // We'll return pretty much whatever and user code can back-fill the accretion disk if any. if(node.derive("accretiondisk").getBool()) { // These aren't absurd masses; they're on the order of world annual food production per second. realBaseLuminosity = node.derive("luminosity").getRealBetween(RealMath.toReal(1), RealMath.toReal(5)); } else { // No accretion disk realBaseLuminosity = 0; } } else if (objectClass == MacroverseStarGenerator.ObjectClass.NeutronStar) { // These will be dim and not really mass-related realBaseLuminosity = node.derive("luminosity").getRealBetween(RealMath.fraction(1, 20), RealMath.fraction(2, 10)); } else if (objectClass == MacroverseStarGenerator.ObjectClass.WhiteDwarf) { // These are also dim realBaseLuminosity = RealMath.pow(realObjectMass.mul(REAL_HALF), RealMath.fraction(35, 10)); } else { // Normal stars follow a normal mass-lumoinosity relationship realBaseLuminosity = RealMath.pow(realObjectMass, RealMath.fraction(35, 10)); } // Perturb the generated luminosity for fun return realBaseLuminosity.mul(node.derive("luminosityScale").getRealBetween(RealMath.fraction(95, 100), RealMath.fraction(105, 100))); }
function getObjectLuminosity(bytes32 starSeed, MacroverseStarGenerator.ObjectClass objectClass, int128 realObjectMass) public view onlyControlledAccess returns (int128) { RNG.RandNode memory node = RNG.RandNode(starSeed); int128 realBaseLuminosity; if (objectClass == MacroverseStarGenerator.ObjectClass.BlackHole) { // Black hole luminosity is going to be from the accretion disk. // See <https://astronomy.stackexchange.com/q/12567> // We'll return pretty much whatever and user code can back-fill the accretion disk if any. if(node.derive("accretiondisk").getBool()) { // These aren't absurd masses; they're on the order of world annual food production per second. realBaseLuminosity = node.derive("luminosity").getRealBetween(RealMath.toReal(1), RealMath.toReal(5)); } else { // No accretion disk realBaseLuminosity = 0; } } else if (objectClass == MacroverseStarGenerator.ObjectClass.NeutronStar) { // These will be dim and not really mass-related realBaseLuminosity = node.derive("luminosity").getRealBetween(RealMath.fraction(1, 20), RealMath.fraction(2, 10)); } else if (objectClass == MacroverseStarGenerator.ObjectClass.WhiteDwarf) { // These are also dim realBaseLuminosity = RealMath.pow(realObjectMass.mul(REAL_HALF), RealMath.fraction(35, 10)); } else { // Normal stars follow a normal mass-lumoinosity relationship realBaseLuminosity = RealMath.pow(realObjectMass, RealMath.fraction(35, 10)); } // Perturb the generated luminosity for fun return realBaseLuminosity.mul(node.derive("luminosityScale").getRealBetween(RealMath.fraction(95, 100), RealMath.fraction(105, 100))); }
21,551
112
// Helper function used for token ID range checks when minting _currentValue Current token ID counter value _incrementValue Number of tokens to increment by _maximumValue Maximum token ID value allowedreturn isBelowMaximum True if _maximumValue is not exceeded /
function belowMaximum( uint256 _currentValue, uint256 _incrementValue, uint256 _maximumValue ) private pure returns (bool isBelowMaximum)
function belowMaximum( uint256 _currentValue, uint256 _incrementValue, uint256 _maximumValue ) private pure returns (bool isBelowMaximum)
49,646