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
2
// MailboxUros Radovanovic <ookie@protonmail.com>/
contract Mailbox { event Message(address owner, address recipient, bytes subject, bytes message); /** * @notice Send message to email `recipient`. * @param recipient The address of the account to send the message to. * @param subject The subject of the message * @param message The message in MIME type application/pkcs7-mime. */ function send(address recipient, bytes subject, bytes message) public { address owner = msg.sender; // Store the message in the transaction log. emit Message(owner, recipient, subject, message); } }
contract Mailbox { event Message(address owner, address recipient, bytes subject, bytes message); /** * @notice Send message to email `recipient`. * @param recipient The address of the account to send the message to. * @param subject The subject of the message * @param message The message in MIME type application/pkcs7-mime. */ function send(address recipient, bytes subject, bytes message) public { address owner = msg.sender; // Store the message in the transaction log. emit Message(owner, recipient, subject, message); } }
21,338
59
// unsuccess:
success := 0
success := 0
8,891
516
// Allows Node to set In_Maintenance status.Requirements:- Node must already be Active.- `msg.sender` must be owner of Node, validator, or SkaleManager. /
function setNodeInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); _setNodeInMaintenance(nodeIndex); }
function setNodeInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); _setNodeInMaintenance(nodeIndex); }
81,690
808
// This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other. `input` is the UTF-8 that should have the prefix prepended. `prefix` is the UTF-8 that should be prepended onto input. `prefixLength` is number of UTF-8 characters represented by `prefix`. Notes: 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be representedby the bytes32 output. 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result.
function _addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength
function _addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength
51,939
103
// reserve should be using eth instead of weth
return address(this).balance;
return address(this).balance;
74,721
68
// Counter overflow is incredibly unrealistic.
unchecked { balanceOf[to]++; }
unchecked { balanceOf[to]++; }
21,087
19
// When the market is deprecated the transfer function will fail because it will try call executeOutstandingEpochSettlementsUser, so we add an extra bool to _beforeTokenTransfer to check if the market is deprecated. This function sets that bool to true.
function deprecateToken() external override { require(msg.sender == market, "Only market can call transfer when market is deprecated"); marketIsDeprecated = true; }
function deprecateToken() external override { require(msg.sender == market, "Only market can call transfer when market is deprecated"); marketIsDeprecated = true; }
445
11
// use it for giveaway and mint for yourself
function gift(uint256 _mintAmount, address destination) public onlyOwner nonReentrant { require(_mintAmount > 0, "need to mint at least 1 NFT"); uint256 supply = totalSupply(); require(supply + _mintAmount <= maxSupply, "Soldout"); _safeMint(destination, _mintAmount); }
function gift(uint256 _mintAmount, address destination) public onlyOwner nonReentrant { require(_mintAmount > 0, "need to mint at least 1 NFT"); uint256 supply = totalSupply(); require(supply + _mintAmount <= maxSupply, "Soldout"); _safeMint(destination, _mintAmount); }
9,880
1
// Emitted every time a new smart vault is set /
event SmartVaultSet(address indexed smartVault);
event SmartVaultSet(address indexed smartVault);
32,071
310
// Emit the pve battle start event.
PVEStarted(msg.sender, warrior.dungeonIndex, _warriorId, warrior.cooldownEndBlock);
PVEStarted(msg.sender, warrior.dungeonIndex, _warriorId, warrior.cooldownEndBlock);
66,317
91
// Decrease allowance of `_spender` in behalf of `_from` at `_value` _from Owner account _spender Spender account _value Value to decreasereturn Operation status /
function decApprove(address _from, address _spender, uint _value) external onlyModule returns (bool) { allowed[_from][_spender] = allowed[_from][_spender].sub(_value); return true; }
function decApprove(address _from, address _spender, uint _value) external onlyModule returns (bool) { allowed[_from][_spender] = allowed[_from][_spender].sub(_value); return true; }
40,347
27
// This function should be called only by owner and creation time + deadlineMissed should be <= nowthis function return money to payeer because of deadline missed/
function returnMoney() public isDeadlineMissed onlyOwner { require(getCurrentState() == State.InProgress); if(address(this).balance > 0) { // return money to 'moneySource' moneySource.transfer(address(this).balance); } state = State.DeadlineMissed; emit WeiGenericTaskStateChanged(state); }
function returnMoney() public isDeadlineMissed onlyOwner { require(getCurrentState() == State.InProgress); if(address(this).balance > 0) { // return money to 'moneySource' moneySource.transfer(address(this).balance); } state = State.DeadlineMissed; emit WeiGenericTaskStateChanged(state); }
39,408
4
// NEW EVENTS - ADDED BY KASPER
event txMint(address indexed from, address indexed to, uint256 indexed nftIndex); event txPrimary(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); event txSecondary(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); event txCollect(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex);
event txMint(address indexed from, address indexed to, uint256 indexed nftIndex); event txPrimary(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); event txSecondary(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); event txCollect(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex);
18,940
41
// ERC223 Transfer to a contract or externally-owned account
function transfer( address to, uint value, bytes data ) public returns (bool success)
function transfer( address to, uint value, bytes data ) public returns (bool success)
6,074
27
// 25 are estimated of 25 seconds per block
uint delay = (_when - initialTime) / 25; uint factor = delay * increasePerBlock; uint multip = initialPrice * factor; uint result = initialPrice - multip / increasePerBlockDiv; require (result <= initialPrice); return result;
uint delay = (_when - initialTime) / 25; uint factor = delay * increasePerBlock; uint multip = initialPrice * factor; uint result = initialPrice - multip / increasePerBlockDiv; require (result <= initialPrice); return result;
75,329
15
// Updates and existing carbon project/Projects can be updated by data-managers
function updateProject( uint256 tokenId, string memory newStandard, string memory newMethodology, string memory newRegion, string memory newStorageMethod, string memory newMethod, string memory newEmissionType, string memory newCategory, string memory newUri,
function updateProject( uint256 tokenId, string memory newStandard, string memory newMethodology, string memory newRegion, string memory newStorageMethod, string memory newMethod, string memory newEmissionType, string memory newCategory, string memory newUri,
22,841
51
// buy BeerCoin directly using Ether /
function buy() payable public { // get the amount of token uint256 amount = msg.value * ICOPrice; // transfer _transfer(this, msg.sender, amount); }
function buy() payable public { // get the amount of token uint256 amount = msg.value * ICOPrice; // transfer _transfer(this, msg.sender, amount); }
43,126
269
// 2. Check the payment amount.
require(payment > 0, "Payment must be greater than 0");
require(payment > 0, "Payment must be greater than 0");
28,999
252
// Standard sale
bool public standardSaleActive; uint256 public pricePerPiece;
bool public standardSaleActive; uint256 public pricePerPiece;
79,217
3
// 加法 /
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; }
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; }
39,115
5
// get votes from the ERC20 token
votes = super._getVotes(account, blockNumber, _data);
votes = super._getVotes(account, blockNumber, _data);
11,346
60
// renounce ownership viw Ownable
Ownable.renounceOwnership();
Ownable.renounceOwnership();
4,172
42
// Standardize the price to use 36 decimals.
uint tokenPairWith36Decimals = tokenPairStandardizedPrice.mul(10 ** uint(tokenToDecimalsMap[tokenPair]));
uint tokenPairWith36Decimals = tokenPairStandardizedPrice.mul(10 ** uint(tokenToDecimalsMap[tokenPair]));
4,730
166
// variables around the ramp management of A, the amplification coefficientn(n - 1) see https:www.curve.fi/stableswap-paper.pdf for details
uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime;
uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime;
17,333
521
// check that there is enough room for new participants
require(pvpQueueSize < pvpQueue.length);
require(pvpQueueSize < pvpQueue.length);
41,010
118
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "Setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_;
err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "Setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_;
3,343
3
// Function to close the payment channel._nonce The nonce of the deposit. Used for avoiding replay attacks._amount The amount of tokens claimed to be due to the receiver._v Cryptographic param v derived from the signature._r Cryptographic param r derived from the signature._s Cryptographic param s derived from the signature./
function close( uint _nonce, uint _amount, uint8 _v, bytes32 _r, bytes32 _s) external
function close( uint _nonce, uint _amount, uint8 _v, bytes32 _r, bytes32 _s) external
37,684
138
// Emitted when account blacklist status changes /
event Blacklisted(address indexed account, bool isBlacklisted);
event Blacklisted(address indexed account, bool isBlacklisted);
23,057
17
// Implements staking and withdrawal logic.
contract StakingHbbftCoins is StakingHbbftBase { // ================================================ Events ======================================================== /// @dev Emitted by the `claimReward` function to signal the staker withdrew the specified /// amount of native coins from the specified pool for the specified staking epoch. /// @param fromPoolStakingAddress The pool from which the `staker` withdrew the amount. /// @param staker The address of the staker that withdrew the amount. /// @param stakingEpoch The serial number of the staking epoch for which the claim was made. /// @param nativeCoinsAmount The withdrawal amount of native coins. event ClaimedReward( address indexed fromPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 nativeCoinsAmount ); // =============================================== Setters ======================================================== /// @dev Withdraws a reward from the specified pool for the specified staking epochs /// to the staker address (msg.sender). /// @param _stakingEpochs The list of staking epochs in ascending order. /// If the list is empty, it is taken with `BlockRewardHbbft.epochsPoolGotRewardFor` getter. /// @param _poolStakingAddress The staking address of the pool from which the reward needs to be withdrawn. function claimReward( uint256[] memory _stakingEpochs, address _poolStakingAddress ) public gasPriceIsValid onlyInitialized { address payable staker = msg.sender; uint256 firstEpoch; uint256 lastEpoch; if (_poolStakingAddress != staker) { // this is a delegator firstEpoch = stakeFirstEpoch[_poolStakingAddress][staker]; require(firstEpoch != 0, "Claim: first epoch can't be 0"); lastEpoch = stakeLastEpoch[_poolStakingAddress][staker]; } IBlockRewardHbbftCoins blockRewardContract = IBlockRewardHbbftCoins(validatorSetContract.blockRewardContract()); address miningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress); uint256 rewardSum = 0; uint256 delegatorStake = 0; if (_stakingEpochs.length == 0) { _stakingEpochs = IBlockRewardHbbft(address(blockRewardContract)).epochsPoolGotRewardFor(miningAddress); } for (uint256 i = 0; i < _stakingEpochs.length; i++) { uint256 epoch = _stakingEpochs[i]; require(i == 0 || epoch > _stakingEpochs[i - 1], "Claim: need strictly increasing order"); require(epoch < stakingEpoch, "Claim: only before current epoch"); if (rewardWasTaken[_poolStakingAddress][staker][epoch]) continue; uint256 reward; if (_poolStakingAddress != staker) { // this is a delegator if (epoch < firstEpoch) { // If the delegator staked for the first time after // the `epoch`, skip this staking epoch continue; } if (lastEpoch <= epoch && lastEpoch != 0) { // If the delegator withdrew all their stake before the `epoch`, // don't check this and following epochs since it makes no sense break; } delegatorStake = _getDelegatorStake(epoch, firstEpoch, delegatorStake, _poolStakingAddress, staker); firstEpoch = epoch + 1; reward = blockRewardContract.getDelegatorReward(delegatorStake, epoch, miningAddress); } else { // this is a validator reward = blockRewardContract.getValidatorReward(epoch, miningAddress); } rewardSum = rewardSum.add(reward); rewardWasTaken[_poolStakingAddress][staker][epoch] = true; emit ClaimedReward(_poolStakingAddress, staker, epoch, reward); } blockRewardContract.transferReward(rewardSum, staker); } // =============================================== Getters ======================================================== /// @dev Returns reward amount in native coins for the specified pool, the specified staking epochs, /// and the specified staker address (delegator or validator). /// @param _stakingEpochs The list of staking epochs in ascending order. /// If the list is empty, it is taken with `BlockRewardHbbft.epochsPoolGotRewardFor` getter. /// @param _poolStakingAddress The staking address of the pool for which the amounts need to be returned. /// @param _staker The staker address (validator's staking address or delegator's address). function getRewardAmount( uint256[] memory _stakingEpochs, address _poolStakingAddress, address _staker ) public view returns(uint256) { uint256 firstEpoch; uint256 lastEpoch; if (_poolStakingAddress != _staker) { // this is a delegator firstEpoch = stakeFirstEpoch[_poolStakingAddress][_staker]; require(firstEpoch != 0, "Unable to get reward amount if no first epoch."); lastEpoch = stakeLastEpoch[_poolStakingAddress][_staker]; } IBlockRewardHbbftCoins blockRewardContract = IBlockRewardHbbftCoins(validatorSetContract.blockRewardContract()); address miningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress); uint256 delegatorStake; uint256 rewardSum; if (_stakingEpochs.length == 0) { _stakingEpochs = IBlockRewardHbbft(address(blockRewardContract)).epochsPoolGotRewardFor(miningAddress); } for (uint256 i = 0; i < _stakingEpochs.length; i++) { uint256 epoch = _stakingEpochs[i]; require(i == 0 || epoch > _stakingEpochs[i - 1], "internal Error: Staking Epochs required to be ordered."); require(epoch < stakingEpoch, "internal Error: epoch must not be lesser than current epoch."); if (rewardWasTaken[_poolStakingAddress][_staker][epoch]) continue; uint256 reward; if (_poolStakingAddress != _staker) { // this is a delegator if (epoch < firstEpoch) continue; if (lastEpoch <= epoch && lastEpoch != 0) break; delegatorStake = _getDelegatorStake(epoch, firstEpoch, delegatorStake, _poolStakingAddress, _staker); firstEpoch = epoch + 1; reward = blockRewardContract.getDelegatorReward(delegatorStake, epoch, miningAddress); } else { // this is a validator reward = blockRewardContract.getValidatorReward(epoch, miningAddress); } rewardSum += reward; } return rewardSum; } // ============================================== Internal ======================================================== /// @dev Sends coins from this contract to the specified address. /// @param _to The target address to send amount to. /// @param _amount The amount to send. function _sendWithdrawnStakeAmount(address payable _to, uint256 _amount) internal { if (!_to.send(_amount)) { // We use the `Sacrifice` trick to be sure the coins can be 100% sent to the receiver. // Otherwise, if the receiver is a contract which has a revert in its fallback function, // the sending will fail. (new Sacrifice2).value(_amount)(_to); } } }
contract StakingHbbftCoins is StakingHbbftBase { // ================================================ Events ======================================================== /// @dev Emitted by the `claimReward` function to signal the staker withdrew the specified /// amount of native coins from the specified pool for the specified staking epoch. /// @param fromPoolStakingAddress The pool from which the `staker` withdrew the amount. /// @param staker The address of the staker that withdrew the amount. /// @param stakingEpoch The serial number of the staking epoch for which the claim was made. /// @param nativeCoinsAmount The withdrawal amount of native coins. event ClaimedReward( address indexed fromPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 nativeCoinsAmount ); // =============================================== Setters ======================================================== /// @dev Withdraws a reward from the specified pool for the specified staking epochs /// to the staker address (msg.sender). /// @param _stakingEpochs The list of staking epochs in ascending order. /// If the list is empty, it is taken with `BlockRewardHbbft.epochsPoolGotRewardFor` getter. /// @param _poolStakingAddress The staking address of the pool from which the reward needs to be withdrawn. function claimReward( uint256[] memory _stakingEpochs, address _poolStakingAddress ) public gasPriceIsValid onlyInitialized { address payable staker = msg.sender; uint256 firstEpoch; uint256 lastEpoch; if (_poolStakingAddress != staker) { // this is a delegator firstEpoch = stakeFirstEpoch[_poolStakingAddress][staker]; require(firstEpoch != 0, "Claim: first epoch can't be 0"); lastEpoch = stakeLastEpoch[_poolStakingAddress][staker]; } IBlockRewardHbbftCoins blockRewardContract = IBlockRewardHbbftCoins(validatorSetContract.blockRewardContract()); address miningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress); uint256 rewardSum = 0; uint256 delegatorStake = 0; if (_stakingEpochs.length == 0) { _stakingEpochs = IBlockRewardHbbft(address(blockRewardContract)).epochsPoolGotRewardFor(miningAddress); } for (uint256 i = 0; i < _stakingEpochs.length; i++) { uint256 epoch = _stakingEpochs[i]; require(i == 0 || epoch > _stakingEpochs[i - 1], "Claim: need strictly increasing order"); require(epoch < stakingEpoch, "Claim: only before current epoch"); if (rewardWasTaken[_poolStakingAddress][staker][epoch]) continue; uint256 reward; if (_poolStakingAddress != staker) { // this is a delegator if (epoch < firstEpoch) { // If the delegator staked for the first time after // the `epoch`, skip this staking epoch continue; } if (lastEpoch <= epoch && lastEpoch != 0) { // If the delegator withdrew all their stake before the `epoch`, // don't check this and following epochs since it makes no sense break; } delegatorStake = _getDelegatorStake(epoch, firstEpoch, delegatorStake, _poolStakingAddress, staker); firstEpoch = epoch + 1; reward = blockRewardContract.getDelegatorReward(delegatorStake, epoch, miningAddress); } else { // this is a validator reward = blockRewardContract.getValidatorReward(epoch, miningAddress); } rewardSum = rewardSum.add(reward); rewardWasTaken[_poolStakingAddress][staker][epoch] = true; emit ClaimedReward(_poolStakingAddress, staker, epoch, reward); } blockRewardContract.transferReward(rewardSum, staker); } // =============================================== Getters ======================================================== /// @dev Returns reward amount in native coins for the specified pool, the specified staking epochs, /// and the specified staker address (delegator or validator). /// @param _stakingEpochs The list of staking epochs in ascending order. /// If the list is empty, it is taken with `BlockRewardHbbft.epochsPoolGotRewardFor` getter. /// @param _poolStakingAddress The staking address of the pool for which the amounts need to be returned. /// @param _staker The staker address (validator's staking address or delegator's address). function getRewardAmount( uint256[] memory _stakingEpochs, address _poolStakingAddress, address _staker ) public view returns(uint256) { uint256 firstEpoch; uint256 lastEpoch; if (_poolStakingAddress != _staker) { // this is a delegator firstEpoch = stakeFirstEpoch[_poolStakingAddress][_staker]; require(firstEpoch != 0, "Unable to get reward amount if no first epoch."); lastEpoch = stakeLastEpoch[_poolStakingAddress][_staker]; } IBlockRewardHbbftCoins blockRewardContract = IBlockRewardHbbftCoins(validatorSetContract.blockRewardContract()); address miningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress); uint256 delegatorStake; uint256 rewardSum; if (_stakingEpochs.length == 0) { _stakingEpochs = IBlockRewardHbbft(address(blockRewardContract)).epochsPoolGotRewardFor(miningAddress); } for (uint256 i = 0; i < _stakingEpochs.length; i++) { uint256 epoch = _stakingEpochs[i]; require(i == 0 || epoch > _stakingEpochs[i - 1], "internal Error: Staking Epochs required to be ordered."); require(epoch < stakingEpoch, "internal Error: epoch must not be lesser than current epoch."); if (rewardWasTaken[_poolStakingAddress][_staker][epoch]) continue; uint256 reward; if (_poolStakingAddress != _staker) { // this is a delegator if (epoch < firstEpoch) continue; if (lastEpoch <= epoch && lastEpoch != 0) break; delegatorStake = _getDelegatorStake(epoch, firstEpoch, delegatorStake, _poolStakingAddress, _staker); firstEpoch = epoch + 1; reward = blockRewardContract.getDelegatorReward(delegatorStake, epoch, miningAddress); } else { // this is a validator reward = blockRewardContract.getValidatorReward(epoch, miningAddress); } rewardSum += reward; } return rewardSum; } // ============================================== Internal ======================================================== /// @dev Sends coins from this contract to the specified address. /// @param _to The target address to send amount to. /// @param _amount The amount to send. function _sendWithdrawnStakeAmount(address payable _to, uint256 _amount) internal { if (!_to.send(_amount)) { // We use the `Sacrifice` trick to be sure the coins can be 100% sent to the receiver. // Otherwise, if the receiver is a contract which has a revert in its fallback function, // the sending will fail. (new Sacrifice2).value(_amount)(_to); } } }
18,281
3
// In-built transfer function to send all money from lottery contract to the player
winner.transfer(address(this).balance); players = new address[](0);
winner.transfer(address(this).balance); players = new address[](0);
27,147
284
// Update invaldiation nonce
state_invalidationMapping[_args.invalidationId] = _args .invalidationNonce;
state_invalidationMapping[_args.invalidationId] = _args .invalidationNonce;
7,862
139
// minimum amount of gas needed by this contract before it tries to deliver a message to the target contract.
uint256 public preExecuteMessageGasUsage; event Executed( MsgDataTypes.MsgType msgType, bytes32 msgId, MsgDataTypes.TxStatus status, address indexed receiver, uint64 srcChainId, bytes32 srcTxHash );
uint256 public preExecuteMessageGasUsage; event Executed( MsgDataTypes.MsgType msgType, bytes32 msgId, MsgDataTypes.TxStatus status, address indexed receiver, uint64 srcChainId, bytes32 srcTxHash );
48,372
147
// Calculate rewards by ((delegateStakeToSP / totalActiveFunds)totalRewards)
uint256 rewardsPriorToSPCut = ( delegateStakeToSP.mul(_totalRewards) ).div(_totalActiveFunds);
uint256 rewardsPriorToSPCut = ( delegateStakeToSP.mul(_totalRewards) ).div(_totalActiveFunds);
17,947
131
// update stats
totalPrizes += _game.prize(); totalOverthrows += _game.numOverthrows();
totalPrizes += _game.prize(); totalOverthrows += _game.numOverthrows();
38,568
11
// Called by owner to unpause, transitons the contract back to normal state/This function can be accessed by the user with role PAUSER_ROLE
function unpause() public onlyRole(PAUSER_ROLE) { _unpause(); }
function unpause() public onlyRole(PAUSER_ROLE) { _unpause(); }
23,039
17
// ====================================== give the people access to play
function openToThePublic() onlyOwner() public
function openToThePublic() onlyOwner() public
52,915
296
// Returns the current price for each token
function getCurrentPrice() public view returns (uint256) { require(hasSaleStarted == true, "Sale has not started"); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); uint256 currentSupply = totalSupply(); if (currentSupply >= 11100) { return 1500000000000000000; // 11100 - 11111 1.5 ETH } else if (currentSupply >= 10500) { return 800000000000000000; // 10500 - 11099 0.8 ETH } else if (currentSupply >= 6500) { return 500000000000000000; // 6500 - 10499 0.5 ETH } else if (currentSupply >= 2500) { return 300000000000000000; // 2500 - 6499 0.3 ETH } else if (currentSupply >= 1000) { return 150000000000000000; // 1000 - 2499 0.15 ETH } else { return 75000000000000000; // 0 - 999 0.075 ETH } }
function getCurrentPrice() public view returns (uint256) { require(hasSaleStarted == true, "Sale has not started"); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); uint256 currentSupply = totalSupply(); if (currentSupply >= 11100) { return 1500000000000000000; // 11100 - 11111 1.5 ETH } else if (currentSupply >= 10500) { return 800000000000000000; // 10500 - 11099 0.8 ETH } else if (currentSupply >= 6500) { return 500000000000000000; // 6500 - 10499 0.5 ETH } else if (currentSupply >= 2500) { return 300000000000000000; // 2500 - 6499 0.3 ETH } else if (currentSupply >= 1000) { return 150000000000000000; // 1000 - 2499 0.15 ETH } else { return 75000000000000000; // 0 - 999 0.075 ETH } }
10,713
339
// Update rewards per block
_updateRewardsPerBlock(endBlock); uint256 previousEndBlock = endBlock;
_updateRewardsPerBlock(endBlock); uint256 previousEndBlock = endBlock;
68,526
4
// returns a list of all pools' program data /
function programs() external view returns (ProgramData[] memory);
function programs() external view returns (ProgramData[] memory);
29,992
1
// Constructs the Testable contract. Called by child contracts.numbererAddress Contract that stores the current block in a testing environment. Must be set to 0x0 for production environments that use live time./
constructor(address numbererAddress) { numbererAddress_ = numbererAddress; }
constructor(address numbererAddress) { numbererAddress_ = numbererAddress; }
21,083
50
// Gets the approved address for a asset ID, or zero if no address set /
function getApproved(uint256 assetId) public view returns (address) { require(_exists(assetId), "BAC002: approved query for nonexistent asset"); return _assetApprovals[assetId]; }
function getApproved(uint256 assetId) public view returns (address) { require(_exists(assetId), "BAC002: approved query for nonexistent asset"); return _assetApprovals[assetId]; }
33,224
25
// Confirm that the signature matches that of the sender
require( verify(msg.sender, _publicKey, _signature), "Err: Invalid Signature" );
require( verify(msg.sender, _publicKey, _signature), "Err: Invalid Signature" );
15,119
24
// _params array of DstConfigParam
function setDstConfig(DstConfigParam[] calldata _params) external onlyRole(ADMIN_ROLE) { for (uint i = 0; i < _params.length; ++i) { DstConfigParam calldata param = _params[i]; dstConfig[param.dstEid] = DstConfig(param.gas, param.multiplierBps, param.floorMarginUSD); } emit SetDstConfig(_params); }
function setDstConfig(DstConfigParam[] calldata _params) external onlyRole(ADMIN_ROLE) { for (uint i = 0; i < _params.length; ++i) { DstConfigParam calldata param = _params[i]; dstConfig[param.dstEid] = DstConfig(param.gas, param.multiplierBps, param.floorMarginUSD); } emit SetDstConfig(_params); }
19,794
73
// Angels 0 and 1 have no max Lucifer and Michael have max numbers 250
maxTokenNumbers[2] = 250; maxTokenNumbers[3] = 250; maxTokenNumbers[4] = 45; maxTokenNumbers[5] = 50; for (i=6; i<15; i++) { maxTokenNumbers[i]= 45; }
maxTokenNumbers[2] = 250; maxTokenNumbers[3] = 250; maxTokenNumbers[4] = 45; maxTokenNumbers[5] = 50; for (i=6; i<15; i++) { maxTokenNumbers[i]= 45; }
33,166
37
// ------------------------------------------------------------------------ Don't accept ETH------------------------------------------------------------------------
function () public payable
function () public payable
49,763
177
// Push 3 to the end of the buffer - event will have 3 topics
mstore(add(0x20, add(ptr, mload(ptr))), 3)
mstore(add(0x20, add(ptr, mload(ptr))), 3)
74,537
5
// emergency rescue to allow unstaking without any checks but without $HONEY
bool public rescueEnabled = false;
bool public rescueEnabled = false;
41,103
15
// Buy Tokens by committing ETH to this contract address
receive () external payable { commitEth(msg.sender); }
receive () external payable { commitEth(msg.sender); }
43,828
201
// Provide a signal to the keeper that `tend()` should be called. The keeper will provide the estimated gas cost that they would pay to call `tend()`, and this function should use that estimate to make a determination if calling it is "worth it" for the keeper. This is not the only consideration into issuing this trigger, for example if the position would be negatively affected if `tend()` is not called shortly, then this can return `true` even if the keeper might be "at a loss" (keepers are always reimbursed by Yearn). `callCostInWei` must be priced in terms of `wei` (1e-18
function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; }
function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; }
890
556
// ERC897 - ERC DelegateProxy/
interface ERCProxy { function proxyType() external pure returns (uint256); function implementation() external view returns (address); }
interface ERCProxy { function proxyType() external pure returns (uint256); function implementation() external view returns (address); }
50,248
34
// Check to see whether the two stakers are in the same challenge stakerAddress1 Address of the first staker stakerAddress2 Address of the second stakerreturn Address of the challenge that the two stakers are in /
function inChallenge(address stakerAddress1, address stakerAddress2) internal view returns (uint64)
function inChallenge(address stakerAddress1, address stakerAddress2) internal view returns (uint64)
33,836
40
// for looping?
function getRequestsCount() public view returns (uint256) { return requests.length; }
function getRequestsCount() public view returns (uint256) { return requests.length; }
79,060
47
// after action hooks for child contracts
function _afterSetMaximumActiveBundles(uint256 numberOfBundles) internal virtual {} function _afterCreateBundle(uint256 bundleId, bytes memory filter, uint256 initialAmount) internal virtual {} function _afterFundBundle(uint256 bundleId, uint256 amount) internal virtual {} function _afterDefundBundle(uint256 bundleId, uint256 amount) internal virtual {} function _afterLockBundle(uint256 bundleId) internal virtual {} function _afterUnlockBundle(uint256 bundleId) internal virtual {} function _afterCloseBundle(uint256 bundleId) internal virtual {} function _afterBurnBundle(uint256 bundleId) internal virtual {} // abstract functions to implement by concrete child contracts function _lockCollateral(bytes32 processId, uint256 collateralAmount) internal virtual returns(bool success); function _processPremium(bytes32 processId, uint256 amount) internal virtual; function _processPayout(bytes32 processId, uint256 amount) internal virtual; function _releaseCollateral(bytes32 processId) internal virtual returns(uint256 collateralAmount); }
function _afterSetMaximumActiveBundles(uint256 numberOfBundles) internal virtual {} function _afterCreateBundle(uint256 bundleId, bytes memory filter, uint256 initialAmount) internal virtual {} function _afterFundBundle(uint256 bundleId, uint256 amount) internal virtual {} function _afterDefundBundle(uint256 bundleId, uint256 amount) internal virtual {} function _afterLockBundle(uint256 bundleId) internal virtual {} function _afterUnlockBundle(uint256 bundleId) internal virtual {} function _afterCloseBundle(uint256 bundleId) internal virtual {} function _afterBurnBundle(uint256 bundleId) internal virtual {} // abstract functions to implement by concrete child contracts function _lockCollateral(bytes32 processId, uint256 collateralAmount) internal virtual returns(bool success); function _processPremium(bytes32 processId, uint256 amount) internal virtual; function _processPayout(bytes32 processId, uint256 amount) internal virtual; function _releaseCollateral(bytes32 processId) internal virtual returns(uint256 collateralAmount); }
40,823
133
// send 4% tokens to developer wallet
_transferStandard(sender, devWallet, (amount * _developerFee).div(1000));
_transferStandard(sender, devWallet, (amount * _developerFee).div(1000));
24,053
89
// The target asset contract address.
address public targetAsset;
address public targetAsset;
24,756
3
// Give ownership to the claimer
ens.setOwner(node, _owner); emit ClaimSubdomain(_subnode, _owner, address(_resolver));
ens.setOwner(node, _owner); emit ClaimSubdomain(_subnode, _owner, address(_resolver));
52,578
145
// pre airdrop to any holders
function airdropToWallets(address[] memory airdropWallets, uint256[] memory amount) external onlyOwner() { require(airdropWallets.length == amount.length, "airdropToWallets:: Arrays must be the same length"); for(uint256 i = 0; i < airdropWallets.length; i++){ address wallet = airdropWallets[i]; uint256 airdropAmount = amount[i]; emit Transfer(msg.sender, wallet, airdropAmount); } }
function airdropToWallets(address[] memory airdropWallets, uint256[] memory amount) external onlyOwner() { require(airdropWallets.length == amount.length, "airdropToWallets:: Arrays must be the same length"); for(uint256 i = 0; i < airdropWallets.length; i++){ address wallet = airdropWallets[i]; uint256 airdropAmount = amount[i]; emit Transfer(msg.sender, wallet, airdropAmount); } }
14,300
15
// Returns the amount of tokens received in redeeming the composite plus token proportionally. _amount Amounf of composite plus to redeem.return Addresses and amounts of tokens returned as well as fee collected. /
function getRedeemAmount(uint256 _amount) external view override returns (address[] memory, uint256[] memory, uint256) { // Withdraw amount = Redeem amount * (1 - redeem fee) * liquidity ratio // Redeem fee is in 0.01% uint256 _fee = _amount.mul(redeemFee).div(MAX_PERCENT); uint256 _withdrawAmount = _amount.sub(_fee).mul(liquidityRatio()).div(WAD); address[] memory _redeemTokens = tokens; uint256[] memory _redeemAmounts = new uint256[](_redeemTokens.length); uint256 _totalSupply = totalSupply(); for (uint256 i = 0; i < _redeemTokens.length; i++) { uint256 _balance = IERC20Upgradeable(_redeemTokens[i]).balanceOf(address(this)); if (_balance == 0) continue; _redeemAmounts[i] = _balance.mul(_withdrawAmount).div(_totalSupply); } return (_redeemTokens, _redeemAmounts, _fee); }
function getRedeemAmount(uint256 _amount) external view override returns (address[] memory, uint256[] memory, uint256) { // Withdraw amount = Redeem amount * (1 - redeem fee) * liquidity ratio // Redeem fee is in 0.01% uint256 _fee = _amount.mul(redeemFee).div(MAX_PERCENT); uint256 _withdrawAmount = _amount.sub(_fee).mul(liquidityRatio()).div(WAD); address[] memory _redeemTokens = tokens; uint256[] memory _redeemAmounts = new uint256[](_redeemTokens.length); uint256 _totalSupply = totalSupply(); for (uint256 i = 0; i < _redeemTokens.length; i++) { uint256 _balance = IERC20Upgradeable(_redeemTokens[i]).balanceOf(address(this)); if (_balance == 0) continue; _redeemAmounts[i] = _balance.mul(_withdrawAmount).div(_totalSupply); } return (_redeemTokens, _redeemAmounts, _fee); }
24,916
2
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) }
if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) }
25,292
8
// Allows to make a payment from the sender to an address given an allowance to this contract Equivalent to xchf.transferAndCall(recipient, xchfamount)
function payAndNotify(address recipient, uint256 xchfamount, bytes calldata ref) public { payAndNotify(currency, recipient, xchfamount, ref); }
function payAndNotify(address recipient, uint256 xchfamount, bytes calldata ref) public { payAndNotify(currency, recipient, xchfamount, ref); }
59,986
1,148
// Expiry price pulled from the DVM in the case of an emergency shutdown.
FixedPoint.Unsigned public emergencyShutdownPrice;
FixedPoint.Unsigned public emergencyShutdownPrice;
12,463
14
// Only 1 free token per address
require(address_to_referrer[msg.sender] == address(0x0));
require(address_to_referrer[msg.sender] == address(0x0));
46,558
20
// receive asset + cost of hedge
if(receiveAsset) _receiveAsset(msg.sender, amount, total);
if(receiveAsset) _receiveAsset(msg.sender, amount, total);
9,843
10
// Config for a list of orders to take sequentially as part of a `takeOrders`/ call./output Output token from the perspective of the order taker./input Input token from the perspective of the order taker./minimumInput Minimum input from the perspective of the order taker./maximumInput Maximum input from the perspective of the order taker./maximumIORatio Maximum IO ratio as calculated by the order being/ taken. The input is from the perspective of the order so higher ratio means/ worse deal for the order taker./orders Ordered list of orders that will be taken until the limit is/ hit. Takers are expected to prioritise orders that
struct TakeOrdersConfig { address output; address input; uint256 minimumInput; uint256 maximumInput; uint256 maximumIORatio; TakeOrderConfig[] orders; }
struct TakeOrdersConfig { address output; address input; uint256 minimumInput; uint256 maximumInput; uint256 maximumIORatio; TakeOrderConfig[] orders; }
18,130
31
// LXL `client` or `clientOracle` can release milestone `amount` to `provider`.registration Registered LXL number. /
function release(uint256 registration) external nonReentrant { Locker storage locker = lockers[registration]; uint256 milestone = locker.currentMilestone-1; uint256 payment = locker.amount[milestone]; uint256 released = locker.released; uint256 sum = locker.sum; require(msg.sender == locker.client || msg.sender == locker.clientOracle, "!client/oracle"); require(locker.confirmed == 1, "!confirmed"); require(locker.locked == 0, "locked"); require(released < sum, "released"); IERC20(locker.token).safeTransfer(locker.provider, payment); locker.released = released.add(payment); if (locker.released < sum) {locker.currentMilestone++;} emit Release(milestone+1, payment, registration); }
function release(uint256 registration) external nonReentrant { Locker storage locker = lockers[registration]; uint256 milestone = locker.currentMilestone-1; uint256 payment = locker.amount[milestone]; uint256 released = locker.released; uint256 sum = locker.sum; require(msg.sender == locker.client || msg.sender == locker.clientOracle, "!client/oracle"); require(locker.confirmed == 1, "!confirmed"); require(locker.locked == 0, "locked"); require(released < sum, "released"); IERC20(locker.token).safeTransfer(locker.provider, payment); locker.released = released.add(payment); if (locker.released < sum) {locker.currentMilestone++;} emit Release(milestone+1, payment, registration); }
64,600
58
// add the initiate's address to the tracking array
allInitiates.push(_user); return _token.transferFrom(msg.sender, address(this), minimumStake);
allInitiates.push(_user); return _token.transferFrom(msg.sender, address(this), minimumStake);
17,727
32
// 判断用户是否存在,存在才增加贡献值
if (userExisted(username)) {
if (userExisted(username)) {
14,440
110
// Calculates the base value in relationship to `elastic` and `total`.
function toBase( Rebase memory total, uint256 elastic, bool roundUp
function toBase( Rebase memory total, uint256 elastic, bool roundUp
15,202
41
// Checks that the msg.sender can open an account for onBehalfOf
_revertIfOpenCreditAccountNotAllowed(onBehalfOf); // F:[FA-4A, 4B, 57]
_revertIfOpenCreditAccountNotAllowed(onBehalfOf); // F:[FA-4A, 4B, 57]
26,239
13
// verify mint pass for given index exists
require(passes[passId].totalPassAmount != 0, "Err: Mint pass does not exist");
require(passes[passId].totalPassAmount != 0, "Err: Mint pass does not exist");
22,843
52
// The basics of a proxy read call Note that msg.sender in the underlying will always be the address of this contract.
assembly { calldatacopy(0, 0, calldatasize)
assembly { calldatacopy(0, 0, calldatasize)
4,656
89
// Address of the token used for rewards
IERC20 public token;
IERC20 public token;
51,945
7
// sending received ethers to the coinbase/ escaping the possibility of reentrancy attack
tokenContractCoinbase.transfer(msg.value);
tokenContractCoinbase.transfer(msg.value);
45,983
10
// Create a Borrow, deploy a Loan Pool and delegate voting power_delegatee Address to delegate the voting power to_amount Amount of underlying to borrow_feeAmount Amount of fee to pay to start the loan return uint : amount of paid fees/
function borrow(address _delegatee, uint _amount, uint _feeAmount) public override(PalPool) returns(uint){ require(claimFromAave()); return super.borrow(_delegatee, _amount, _feeAmount); }
function borrow(address _delegatee, uint _amount, uint _feeAmount) public override(PalPool) returns(uint){ require(claimFromAave()); return super.borrow(_delegatee, _amount, _feeAmount); }
22,146
53
// Returns true if the two strings are equal. /
function equal(string memory a, string memory b) internal pure returns (bool) { return keccak256(bytes(a)) == keccak256(bytes(b)); }
function equal(string memory a, string memory b) internal pure returns (bool) { return keccak256(bytes(a)) == keccak256(bytes(b)); }
2,761
5
// if token transfer is not allow
if(!tokenTransfer) { require(unlockaddress[msg.sender]); }
if(!tokenTransfer) { require(unlockaddress[msg.sender]); }
49,472
226
// calculate total USDT gain
uint totalProfits = holderETHProfit .mul(strikePrice) .div(1 ether) // remember to div ETH price unit (1 ether .div(1e12); // remember to div 1e12 previous multipied
uint totalProfits = holderETHProfit .mul(strikePrice) .div(1 ether) // remember to div ETH price unit (1 ether .div(1e12); // remember to div 1e12 previous multipied
25,542
32
// Remove vendor from the system by address. Only owner can operate _vendor The address of vendorreturn Success /
function removeVendorByAddress(address _vendor) public onlyOwner
function removeVendorByAddress(address _vendor) public onlyOwner
47,970
170
// Update totalSupply
totalSupply = totalSupply.Sub(investorStruct.exhSentCrowdsaleType1);
totalSupply = totalSupply.Sub(investorStruct.exhSentCrowdsaleType1);
3,653
11
// ------------------------------------------------------------------------ Transfer the balance from owner's account to another account ------------------------------------------------------------------------
function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] >= _amount // User has balance && _amount > 0 // Non-zero transfer && balances[_to] + _amount > balances[_to] // Overflow check ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } }
function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] >= _amount // User has balance && _amount > 0 // Non-zero transfer && balances[_to] + _amount > balances[_to] // Overflow check ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } }
20,501
178
// AddressArrayUtils Set Protocol Utility functions to handle Address Arrays CHANGELOG:- 4/21/21: Added validatePairsWithArray methods /
library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } }
library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } }
21,952
15
// return the token uri, this delegates to the receipt renderer contract
function tokenURI( uint tokenId_
function tokenURI( uint tokenId_
30,823
35
// mint 100,000 tokens with 18 decimals and send them to token deployer mint function is internal and can not be called after deployment
_mint(msg.sender,100000e18 );
_mint(msg.sender,100000e18 );
42,663
40
// Reinvest all dividends/
function reinvest() public { // get all dividends uint funds = dividendsOf(msg.sender); require(funds > 0, "You have no dividends"); // make correction, dividents will be 0 after that UserRecord storage user = user_data[msg.sender]; user.funds_correction = user.funds_correction.add(int(funds)); // apply fee (uint fee_funds, uint taxed_funds) = fee_purchase.split(funds); require(fee_funds != 0, "Insufficient dividends to do that"); // apply referral bonus if (user.referrer != 0x0) { fee_funds = rewardReferrer(msg.sender, user.referrer, fee_funds, funds); require(fee_funds != 0, "Insufficient dividends to do that"); } // calculate amount of tokens and change price (uint tokens, uint _price) = fundsToTokens(taxed_funds); require(tokens != 0, "Insufficient dividends to do that"); price = _price; // mint tokens and increase shared profit mintTokens(msg.sender, tokens); shared_profit = shared_profit.add(fee_funds); emit Reinvestment(msg.sender, funds, tokens, price / precision_factor, now); }
function reinvest() public { // get all dividends uint funds = dividendsOf(msg.sender); require(funds > 0, "You have no dividends"); // make correction, dividents will be 0 after that UserRecord storage user = user_data[msg.sender]; user.funds_correction = user.funds_correction.add(int(funds)); // apply fee (uint fee_funds, uint taxed_funds) = fee_purchase.split(funds); require(fee_funds != 0, "Insufficient dividends to do that"); // apply referral bonus if (user.referrer != 0x0) { fee_funds = rewardReferrer(msg.sender, user.referrer, fee_funds, funds); require(fee_funds != 0, "Insufficient dividends to do that"); } // calculate amount of tokens and change price (uint tokens, uint _price) = fundsToTokens(taxed_funds); require(tokens != 0, "Insufficient dividends to do that"); price = _price; // mint tokens and increase shared profit mintTokens(msg.sender, tokens); shared_profit = shared_profit.add(fee_funds); emit Reinvestment(msg.sender, funds, tokens, price / precision_factor, now); }
63,659
1
// loanAmount;
totalPayable; yearss; creditScore;
totalPayable; yearss; creditScore;
38,412
127
// calculates required collateral for simulated position/loanToken address of loan token/collateralToken address of collateral token/newPrincipal principal amount of the loan/marginAmount margin amount of the loan/isTorqueLoan boolean torque or non torque loan/ return collateralAmountRequired amount required
function getRequiredCollateral( address loanToken, address collateralToken, uint256 newPrincipal, uint256 marginAmount, bool isTorqueLoan ) external view returns (uint256 collateralAmountRequired); function getRequiredCollateralByParams( bytes32 loanParamsId,
function getRequiredCollateral( address loanToken, address collateralToken, uint256 newPrincipal, uint256 marginAmount, bool isTorqueLoan ) external view returns (uint256 collateralAmountRequired); function getRequiredCollateralByParams( bytes32 loanParamsId,
64,338
46
// Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. Tokens start existing when they are minted (`_mint`), /
function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; }
function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; }
9,517
23
// Need an equal number of CLAIM and NOCLAIM tokens
claimToken.transferFrom(data.caller, address(this), data.amount);
claimToken.transferFrom(data.caller, address(this), data.amount);
47,324
13
// Emitted when pendingAdmin is accepted, which means admin is updated
event NewAdmin(address oldAdmin, address newAdmin);
event NewAdmin(address oldAdmin, address newAdmin);
18,711
9
// uint16 _referralCode
);
);
8,833
54
// The start bonus must be some fraction of the max. (i.e. <= 100%)
require(startBonus_ <= 10**BONUS_DECIMALS, 'Cradle: start bonus too high');
require(startBonus_ <= 10**BONUS_DECIMALS, 'Cradle: start bonus too high');
27,984
19
// ---------- Market Resolution ---------- /
function _oraclePriceAndTimestamp() internal view returns (uint price, uint updatedAt) { return _exchangeRates().rateAndUpdatedTime(oracleDetails.key); }
function _oraclePriceAndTimestamp() internal view returns (uint price, uint updatedAt) { return _exchangeRates().rateAndUpdatedTime(oracleDetails.key); }
32,908
167
// keccak256("PAUSER_ROLE");
bytes32 public constant PAUSER_ROLE = 0x65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a;
bytes32 public constant PAUSER_ROLE = 0x65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a;
8,016
11
// get data about the latest round. Consumers are encouraged to checkthat they're receiving fresh data by inspecting the updatedAt value.return roundId is the round ID for which data was retrievedreturn answer is the answer for the given roundreturn startedAt is always equal to updatedAt because the underlyingAggregator contract does not expose this information.return updatedAt is the timestamp when the round last was updated (i.e.answer was last computed)return answeredInRound is always equal to roundId because the underlyingAggregator contract does not expose this information. Note that for rounds that haven't yet received responses from alloracles, answer and updatedAt may change between queries.
function latestRoundData() external virtual override returns ( uint256 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint256 answeredInRound
function latestRoundData() external virtual override returns ( uint256 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint256 answeredInRound
34,787
19
// Determine the amount of insurance that was placed on this flight by this passenger
( , ,uint iAmount, , ) = fsData.getPolicy(account, flightKey);
( , ,uint iAmount, , ) = fsData.getPolicy(account, flightKey);
31,166
103
// create new tokens for this buyer
crowdsaleToken.issue(_recepient, tokensSold); emit SellToken(_recepient, tokensSold, _value);
crowdsaleToken.issue(_recepient, tokensSold); emit SellToken(_recepient, tokensSold, _value);
37,098
230
// Calculates the exchange rate from the underlying to the CToken This function does not accrue efore calculating the exchange ratereturn calculated exchange rate scaled by 1e18 /
function exchangeRateStoredInternal() virtual internal view returns (uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return initialExchangeRateMantissa; } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves = totalCash + totalBorrows - totalReserves; uint exchangeRate = cashPlusBorrowsMinusReserves * expScale / _totalSupply; return exchangeRate; } }
function exchangeRateStoredInternal() virtual internal view returns (uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return initialExchangeRateMantissa; } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves = totalCash + totalBorrows - totalReserves; uint exchangeRate = cashPlusBorrowsMinusReserves * expScale / _totalSupply; return exchangeRate; } }
21,246
167
// See {IERC721-isApprovedForAll}. /
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; }
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; }
5,682
16
// set default delay for redeem
claimRedeemDelay = 2 days; noclaimRedeemDelay = 10 days; initializeOwner();
claimRedeemDelay = 2 days; noclaimRedeemDelay = 10 days; initializeOwner();
32,143
37
// 配置上链文本 购得时段后(包含拍卖和私募),可以设置时段文本每时段文字接受中文30字以内(含标点和空格),多出字符不显示。审核截止时间是,每个时段播出前30分钟 /
function setText(string _text) public { require(INITIAL_SUPPLY == balances[msg.sender]); // 拥有时段币的人可以设置文本 require(bytes(_text).length > 0 && bytes(_text).length <= 90); // 汉字使用UTF8编码,1个汉字最多占用3个字节,所以最多写90个字节的字 require(now < tvUseStartTime - 30 minutes); // 开播前30分钟不能再设置文本 text = _text; }
function setText(string _text) public { require(INITIAL_SUPPLY == balances[msg.sender]); // 拥有时段币的人可以设置文本 require(bytes(_text).length > 0 && bytes(_text).length <= 90); // 汉字使用UTF8编码,1个汉字最多占用3个字节,所以最多写90个字节的字 require(now < tvUseStartTime - 30 minutes); // 开播前30分钟不能再设置文本 text = _text; }
69,450