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
72
// 日志&事件CarveUpDone(theLoserIndex, carveUpTokens[0], carveUpTokens[1], carveUpTokens[2], carveUpTokens[3], carveUpTokens[4], carveUpTokens[5], carveUpTokens[6], carveUpTokens[7], carveUpTokens[8], carveUpTokens[9]);
carveUpTokens = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
carveUpTokens = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
47,814
26
// mint
_rOwned[_msgSender()] = _rTotal; emit Transfer(address(0), _msgSender(), _tTotal);
_rOwned[_msgSender()] = _rTotal; emit Transfer(address(0), _msgSender(), _tTotal);
8,423
42
// General Information // Return all of the MSD tokensreturn _allMSDs The list of MSD token addresses /
function getAllMSDs() public view returns (address[] memory _allMSDs) { EnumerableSetUpgradeable.AddressSet storage _msdTokens = msdTokens; uint256 _len = _msdTokens.length(); _allMSDs = new address[](_len); for (uint256 i = 0; i < _len; i++) { _allMSDs[i] = _msdTokens.at(i); } }
function getAllMSDs() public view returns (address[] memory _allMSDs) { EnumerableSetUpgradeable.AddressSet storage _msdTokens = msdTokens; uint256 _len = _msdTokens.length(); _allMSDs = new address[](_len); for (uint256 i = 0; i < _len; i++) { _allMSDs[i] = _msdTokens.at(i); } }
52,977
6
// Returns the current admin. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the`0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` /
function _dispatchAdmin() private returns (bytes memory) { _requireZeroValue(); address admin = _getAdmin(); return abi.encode(admin); }
function _dispatchAdmin() private returns (bytes memory) { _requireZeroValue(); address admin = _getAdmin(); return abi.encode(admin); }
4,879
15
// Nonces for each VRF key from which randomness has been requested. Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 => uint256) /* keyHash */ /* nonce */ private nonces;
mapping(bytes32 => uint256) /* keyHash */ /* nonce */ private nonces;
28,839
167
// Signal to OpenSea that mfrankrz is eternal (he is gift to humanity)
emit PermanentURI(tokenURI(currentSupply), currentSupply);
emit PermanentURI(tokenURI(currentSupply), currentSupply);
47,723
189
// 9
Order.NotaryFee=0; if(NewOrder>0) SaveNewOrder(ConfData,Order,0); else SaveOrder(Order);
Order.NotaryFee=0; if(NewOrder>0) SaveNewOrder(ConfData,Order,0); else SaveOrder(Order);
46,006
145
// Increase the total stake for a delegate and updates its 'lastActiveStakeUpdateRound' _delegate The delegate to increase the stake for _amount The amount to increase the stake for '_delegate' by /
function increaseTotalStake( address _delegate, uint256 _amount, address _newPosPrev, address _newPosNext
function increaseTotalStake( address _delegate, uint256 _amount, address _newPosPrev, address _newPosNext
33,936
10
// Used to describe withdraws in ERC1155.batchOperationWithdraw /
struct Withdraw { // Destination of the address to withdraw to address to; // Currency Id to withdraw uint16 currencyId; // Amount of tokens to withdraw uint128 amount; }
struct Withdraw { // Destination of the address to withdraw to address to; // Currency Id to withdraw uint16 currencyId; // Amount of tokens to withdraw uint128 amount; }
40,144
113
// Initial checks:- Caller is TroveManager---Cancels out the specified debt against the LUSD contained in the Stability Pool (as far as possible)and transfers the Trove's ETH collateral from ActivePool to StabilityPool.Only called by liquidation functions in the TroveManager. /
function offset(uint _debt, uint _coll) external;
function offset(uint _debt, uint _coll) external;
3,548
357
// trigger migration from the new Unlock
IUnlock(newUnlockAddress).postLockUpgrade();
IUnlock(newUnlockAddress).postLockUpgrade();
18,257
144
// Since storeman group admin receiver address may be changed, system should make sure the new address/can be used, and the old address can not be used. The solution is add timestamp./unit: second
uint public smgFeeReceiverTimeout = uint(10*60);
uint public smgFeeReceiverTimeout = uint(10*60);
17,401
29
// AmountDeriver 0age AmountDeriver contains view and pure functions related to derivingitem amounts based on partial fill quantity and on linearinterpolation based on current time when the start amount and endamount differ. /
contract AmountDeriver is AmountDerivationErrors { /** * @dev Internal view function to derive the current amount of a given item * based on the current price, the starting price, and the ending * price. If the start and end prices differ, the current price will be * interpolated on a linear basis. Note that this function expects that * the startTime parameter of orderParameters is not greater than the * current block timestamp and that the endTime parameter is greater * than the current block timestamp. If this condition is not upheld, * duration / elapsed / remaining variables will underflow. * * @param startAmount The starting amount of the item. * @param endAmount The ending amount of the item. * @param startTime The starting time of the order. * @param endTime The end time of the order. * @param roundUp A boolean indicating whether the resultant amount * should be rounded up or down. * * @return amount The current amount. */ function _locateCurrentAmount( uint256 startAmount, uint256 endAmount, uint256 startTime, uint256 endTime, bool roundUp ) internal view returns (uint256 amount) { // Only modify end amount if it doesn't already equal start amount. if (startAmount != endAmount) { // Declare variables to derive in the subsequent unchecked scope. uint256 duration; uint256 elapsed; uint256 remaining; // Skip underflow checks as startTime <= block.timestamp < endTime. unchecked { // Derive the duration for the order and place it on the stack. duration = endTime - startTime; // Derive time elapsed since the order started & place on stack. elapsed = block.timestamp - startTime; // Derive time remaining until order expires and place on stack. remaining = duration - elapsed; } // Aggregate new amounts weighted by time with rounding factor. uint256 totalBeforeDivision = ((startAmount * remaining) + (endAmount * elapsed)); // Use assembly to combine operations and skip divide-by-zero check. assembly { // Multiply by iszero(iszero(totalBeforeDivision)) to ensure // amount is set to zero if totalBeforeDivision is zero, // as intermediate overflow can occur if it is zero. amount := mul( iszero(iszero(totalBeforeDivision)), // Subtract 1 from the numerator and add 1 to the result if // roundUp is true to get the proper rounding direction. // Division is performed with no zero check as duration // cannot be zero as long as startTime < endTime. add( div(sub(totalBeforeDivision, roundUp), duration), roundUp ) ) } // Return the current amount. return amount; } // Return the original amount as startAmount == endAmount. return endAmount; } /** * @dev Internal pure function to return a fraction of a given value and to * ensure the resultant value does not have any fractional component. * Note that this function assumes that zero will never be supplied as * the denominator parameter; invalid / undefined behavior will result * should a denominator of zero be provided. * * @param numerator A value indicating the portion of the order that * should be filled. * @param denominator A value indicating the total size of the order. Note * that this value cannot be equal to zero. * @param value The value for which to compute the fraction. * * @return newValue The value after applying the fraction. */ function _getFraction( uint256 numerator, uint256 denominator, uint256 value ) internal pure returns (uint256 newValue) { // Return value early in cases where the fraction resolves to 1. if (numerator == denominator) { return value; } // Ensure fraction can be applied to the value with no remainder. Note // that the denominator cannot be zero. assembly { // Ensure new value contains no remainder via mulmod operator. // Credit to @hrkrshnn + @axic for proposing this optimal solution. if mulmod(value, numerator, denominator) { mstore(0, InexactFraction_error_signature) revert(0, InexactFraction_error_len) } } // Multiply the numerator by the value and ensure no overflow occurs. uint256 valueTimesNumerator = value * numerator; // Divide and check for remainder. Note that denominator cannot be zero. assembly { // Perform division without zero check. newValue := div(valueTimesNumerator, denominator) } } /** * @dev Internal view function to apply a fraction to a consideration * or offer item. * * @param startAmount The starting amount of the item. * @param endAmount The ending amount of the item. * @param numerator A value indicating the portion of the order that * should be filled. * @param denominator A value indicating the total size of the order. * @param startTime The starting time of the order. * @param endTime The end time of the order. * @param roundUp A boolean indicating whether the resultant * amount should be rounded up or down. * * @return amount The received item to transfer with the final amount. */ function _applyFraction( uint256 startAmount, uint256 endAmount, uint256 numerator, uint256 denominator, uint256 startTime, uint256 endTime, bool roundUp ) internal view returns (uint256 amount) { // If start amount equals end amount, apply fraction to end amount. if (startAmount == endAmount) { // Apply fraction to end amount. amount = _getFraction(numerator, denominator, endAmount); } else { // Otherwise, apply fraction to both and interpolated final amount. amount = _locateCurrentAmount( _getFraction(numerator, denominator, startAmount), _getFraction(numerator, denominator, endAmount), startTime, endTime, roundUp ); } } }
contract AmountDeriver is AmountDerivationErrors { /** * @dev Internal view function to derive the current amount of a given item * based on the current price, the starting price, and the ending * price. If the start and end prices differ, the current price will be * interpolated on a linear basis. Note that this function expects that * the startTime parameter of orderParameters is not greater than the * current block timestamp and that the endTime parameter is greater * than the current block timestamp. If this condition is not upheld, * duration / elapsed / remaining variables will underflow. * * @param startAmount The starting amount of the item. * @param endAmount The ending amount of the item. * @param startTime The starting time of the order. * @param endTime The end time of the order. * @param roundUp A boolean indicating whether the resultant amount * should be rounded up or down. * * @return amount The current amount. */ function _locateCurrentAmount( uint256 startAmount, uint256 endAmount, uint256 startTime, uint256 endTime, bool roundUp ) internal view returns (uint256 amount) { // Only modify end amount if it doesn't already equal start amount. if (startAmount != endAmount) { // Declare variables to derive in the subsequent unchecked scope. uint256 duration; uint256 elapsed; uint256 remaining; // Skip underflow checks as startTime <= block.timestamp < endTime. unchecked { // Derive the duration for the order and place it on the stack. duration = endTime - startTime; // Derive time elapsed since the order started & place on stack. elapsed = block.timestamp - startTime; // Derive time remaining until order expires and place on stack. remaining = duration - elapsed; } // Aggregate new amounts weighted by time with rounding factor. uint256 totalBeforeDivision = ((startAmount * remaining) + (endAmount * elapsed)); // Use assembly to combine operations and skip divide-by-zero check. assembly { // Multiply by iszero(iszero(totalBeforeDivision)) to ensure // amount is set to zero if totalBeforeDivision is zero, // as intermediate overflow can occur if it is zero. amount := mul( iszero(iszero(totalBeforeDivision)), // Subtract 1 from the numerator and add 1 to the result if // roundUp is true to get the proper rounding direction. // Division is performed with no zero check as duration // cannot be zero as long as startTime < endTime. add( div(sub(totalBeforeDivision, roundUp), duration), roundUp ) ) } // Return the current amount. return amount; } // Return the original amount as startAmount == endAmount. return endAmount; } /** * @dev Internal pure function to return a fraction of a given value and to * ensure the resultant value does not have any fractional component. * Note that this function assumes that zero will never be supplied as * the denominator parameter; invalid / undefined behavior will result * should a denominator of zero be provided. * * @param numerator A value indicating the portion of the order that * should be filled. * @param denominator A value indicating the total size of the order. Note * that this value cannot be equal to zero. * @param value The value for which to compute the fraction. * * @return newValue The value after applying the fraction. */ function _getFraction( uint256 numerator, uint256 denominator, uint256 value ) internal pure returns (uint256 newValue) { // Return value early in cases where the fraction resolves to 1. if (numerator == denominator) { return value; } // Ensure fraction can be applied to the value with no remainder. Note // that the denominator cannot be zero. assembly { // Ensure new value contains no remainder via mulmod operator. // Credit to @hrkrshnn + @axic for proposing this optimal solution. if mulmod(value, numerator, denominator) { mstore(0, InexactFraction_error_signature) revert(0, InexactFraction_error_len) } } // Multiply the numerator by the value and ensure no overflow occurs. uint256 valueTimesNumerator = value * numerator; // Divide and check for remainder. Note that denominator cannot be zero. assembly { // Perform division without zero check. newValue := div(valueTimesNumerator, denominator) } } /** * @dev Internal view function to apply a fraction to a consideration * or offer item. * * @param startAmount The starting amount of the item. * @param endAmount The ending amount of the item. * @param numerator A value indicating the portion of the order that * should be filled. * @param denominator A value indicating the total size of the order. * @param startTime The starting time of the order. * @param endTime The end time of the order. * @param roundUp A boolean indicating whether the resultant * amount should be rounded up or down. * * @return amount The received item to transfer with the final amount. */ function _applyFraction( uint256 startAmount, uint256 endAmount, uint256 numerator, uint256 denominator, uint256 startTime, uint256 endTime, bool roundUp ) internal view returns (uint256 amount) { // If start amount equals end amount, apply fraction to end amount. if (startAmount == endAmount) { // Apply fraction to end amount. amount = _getFraction(numerator, denominator, endAmount); } else { // Otherwise, apply fraction to both and interpolated final amount. amount = _locateCurrentAmount( _getFraction(numerator, denominator, startAmount), _getFraction(numerator, denominator, endAmount), startTime, endTime, roundUp ); } } }
32,715
28
// pay out percentage cannot be higher than 100 (so double the investment) it also cannot be lower than the fee percentage
if (_percentage > 100 || _percentage < feePercentage) throw; _;
if (_percentage > 100 || _percentage < feePercentage) throw; _;
19,339
3
// require(block.timestamp >= _startTime, "Invalid time to start the auction!");
require(block.timestamp < _endTime, "End time must be greater than the start time!"); require(_startPrice > 0, "Start price cannot be 0!"); auctions.push(); uint auctionId = totalAuctionCount; Auction storage auction = auctions[auctionId]; auction.id = auctionId; auction.owner = msg.sender; // who calls this function, owns the auction. auction.ownerName = _ownerName;
require(block.timestamp < _endTime, "End time must be greater than the start time!"); require(_startPrice > 0, "Start price cannot be 0!"); auctions.push(); uint auctionId = totalAuctionCount; Auction storage auction = auctions[auctionId]; auction.id = auctionId; auction.owner = msg.sender; // who calls this function, owns the auction. auction.ownerName = _ownerName;
30,979
218
// import { ICKToken } from "contracts/interfaces/ICKToken.sol";
function calculateCKTokenValuation(ICKToken _ckToken, address _quoteAsset) external view returns (uint256);
function calculateCKTokenValuation(ICKToken _ckToken, address _quoteAsset) external view returns (uint256);
8,911
55
// Update storage balance of previous bin
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
22,502
16
// Each angel can only be on one board at a time.
mapping (uint64 => bool) angelsOnBattleboards;
mapping (uint64 => bool) angelsOnBattleboards;
51,144
22
// Utility library of inline functions on addresses /
library AddressUtils { /** * @notice Returns whether there is code in the target address * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address address to check * @return whether there is code in the target address */ function isContract(address addr) internal view returns (bool) { uint256 size; // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } }
library AddressUtils { /** * @notice Returns whether there is code in the target address * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address address to check * @return whether there is code in the target address */ function isContract(address addr) internal view returns (bool) { uint256 size; // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } }
40,336
215
// Retrieve the rate for a specific currency /
function rateForCurrency(bytes4 currencyKey) public view returns (uint)
function rateForCurrency(bytes4 currencyKey) public view returns (uint)
25,459
4
// external
function deposit(uint256 tokenId, uint256 amount, address operator) external; function withdraw(uint256 tokenId, uint256 amount) external; function claimCvgRewards(uint256 tokenId, uint256 _cycleId) external; function claimTokeRewards(uint256 tokenId, uint256 _cycleId) external; function claimMultipleCvgRewards(uint256 tokenId, uint256[] memory _cycleIds, address operator) external;
function deposit(uint256 tokenId, uint256 amount, address operator) external; function withdraw(uint256 tokenId, uint256 amount) external; function claimCvgRewards(uint256 tokenId, uint256 _cycleId) external; function claimTokeRewards(uint256 tokenId, uint256 _cycleId) external; function claimMultipleCvgRewards(uint256 tokenId, uint256[] memory _cycleIds, address operator) external;
7,646
381
// round 27
ark(i, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719); sbox_partial(i, q); mix(i, q);
ark(i, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719); sbox_partial(i, q); mix(i, q);
51,207
106
// Initialize only once
require(address(token) == 0x0); token = MiniMeToken(_token); require(token.totalSupply() == 0); require(token.controller() == address(this)); require(token.decimals() == 8); require(_destTokensReserve != 0x0); destTokensReserve = _destTokensReserve;
require(address(token) == 0x0); token = MiniMeToken(_token); require(token.totalSupply() == 0); require(token.controller() == address(this)); require(token.decimals() == 8); require(_destTokensReserve != 0x0); destTokensReserve = _destTokensReserve;
36,386
11
// V2 AggregatorInterface
function latestAnswer(address base, address quote) external view returns (int256 answer); function latestTimestamp(address base, address quote) external view returns (uint256 timestamp); function latestRound(address base, address quote) external view returns (uint256 roundId); function getAnswer( address base, address quote,
function latestAnswer(address base, address quote) external view returns (int256 answer); function latestTimestamp(address base, address quote) external view returns (uint256 timestamp); function latestRound(address base, address quote) external view returns (uint256 roundId); function getAnswer( address base, address quote,
12,783
10
// same as the one above, just in case. Require reverts everything so the end is not tracked
require(checkIfProjectEnded() != true, "The project is not raising capital at the moment anymore. Use checkIfProjectEnded to end the project.");
require(checkIfProjectEnded() != true, "The project is not raising capital at the moment anymore. Use checkIfProjectEnded to end the project.");
17,239
270
// withdraw addresses
address wt = 0x622De517E4225d6D2371A9c4c89415174987D4Dd;
address wt = 0x622De517E4225d6D2371A9c4c89415174987D4Dd;
2,860
70
// make HashesDAO the owner of this Factory contract
transferOwnership(IOwnable(address(hashesToken)).owner());
transferOwnership(IOwnable(address(hashesToken)).owner());
11,783
76
// Returns the number of elements on the set. O(1). /
function length(Bytes32Set storage set) internal view returns (uint256)
function length(Bytes32Set storage set) internal view returns (uint256)
4,286
110
// require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount); _callonERC1155Received(_from, _to, _id, _amount, _data);
_safeTransferFrom(_from, _to, _id, _amount); _callonERC1155Received(_from, _to, _id, _amount, _data);
24,311
7
// 0 = no debt, 1 = stable, 2 = variable
uint256[] memory modes = new uint256[](1); modes[0] = 0; address onBehalfOf = address(this); bytes memory params = ""; uint16 referralCode = 0; _lendingPool.flashLoan( receiverAddress, assets,
uint256[] memory modes = new uint256[](1); modes[0] = 0; address onBehalfOf = address(this); bytes memory params = ""; uint16 referralCode = 0; _lendingPool.flashLoan( receiverAddress, assets,
2,690
13
// CONSTRUCTOR// Contract constructor /
constructor(address dataContract) public { flightSuretyData = FlightSuretyDataInterface(dataContract); }
constructor(address dataContract) public { flightSuretyData = FlightSuretyDataInterface(dataContract); }
28,634
42
// slash the staker and distribute rewards to voters message the message about the slash infos /
function slash(SlashMsg memory message) internal { // slashing params check require(isSetParam,"have not set the slash amount"); bytes memory jailNodePubKey = operators[message.jailNode]; if (message.slashType == SlashType.uptime) { // jail and transfer deposits ITssGroupManager(tssGroupContract).memberJail(jailNodePubKey); transformDeposit(message.jailNode, 0); } else if (message.slashType == SlashType.animus) { // remove the member and transfer deposits ITssGroupManager(tssGroupContract).memberJail(jailNodePubKey); transformDeposit(message.jailNode, 1); } else { revert("err type for slashing"); } }
function slash(SlashMsg memory message) internal { // slashing params check require(isSetParam,"have not set the slash amount"); bytes memory jailNodePubKey = operators[message.jailNode]; if (message.slashType == SlashType.uptime) { // jail and transfer deposits ITssGroupManager(tssGroupContract).memberJail(jailNodePubKey); transformDeposit(message.jailNode, 0); } else if (message.slashType == SlashType.animus) { // remove the member and transfer deposits ITssGroupManager(tssGroupContract).memberJail(jailNodePubKey); transformDeposit(message.jailNode, 1); } else { revert("err type for slashing"); } }
4,090
36
// Check if the passenger is already insured for a flight return true if the passenger is insured for the flight /
function isInsured(address passenger, string flight) external view requireAuthorizedCaller returns(bool)
function isInsured(address passenger, string flight) external view requireAuthorizedCaller returns(bool)
22,193
15
// returning all papers
function getUsers() public view returns(User[] memory){ return usersArray; }
function getUsers() public view returns(User[] memory){ return usersArray; }
10,747
14
// Рассчитываем 5% от общей суммы баттла для джекпота
uint256 jackpotAmount = (rewardAmount * 5) / 100;
uint256 jackpotAmount = (rewardAmount * 5) / 100;
15,056
163
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage); uint256 c = a / b;
require(b > 0, errorMessage); uint256 c = a / b;
18,070
440
// Returns utf8-encoded bytes32 string that can be read via web3.utils.hexToUtf8. Will return bytes32 in all lower case hex characters and without the leading 0x.This has minor changes from the toUtf8BytesAddress to control for the size of the input. bytesIn bytes32 to encode.return utf8 encoded bytes32. /
function toUtf8Bytes(bytes32 bytesIn) internal pure returns (bytes memory) { return abi.encodePacked(toUtf8Bytes32Bottom(bytesIn >> 128), toUtf8Bytes32Bottom(bytesIn)); }
function toUtf8Bytes(bytes32 bytesIn) internal pure returns (bytes memory) { return abi.encodePacked(toUtf8Bytes32Bottom(bytesIn >> 128), toUtf8Bytes32Bottom(bytesIn)); }
29,410
8
// initial block reward
uint256 public OPABlockReward = 0;
uint256 public OPABlockReward = 0;
29,083
0
// Set an amount as the allowance of `spender` over the caller's tokens. Returns a boolean value indicating whether the operation succeeded. IMPORTANT: Beware that changing an allowance with this method brings the riskthat someone may use both the old and the new allowance by unfortunatetransaction ordering. One possible solution to mitigate this racecondition is to first reduce the spender's allowance to 0 and set thedesired value afterwards:
* Emits an {Approval} event. * * @param _spender The account address that will be able to spend the tokens. * @param _value The amount of tokens allowed to spend. * */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
* Emits an {Approval} event. * * @param _spender The account address that will be able to spend the tokens. * @param _value The amount of tokens allowed to spend. * */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
4,188
223
// Transfer funding amount from the FundingLocker to the Borrower, then drain remaining funds to the Loan.
uint256 treasuryFee = globals.treasuryFee(); uint256 investorFee = globals.investorFee(); address treasury = globals.mapleTreasury(); uint256 _feePaid = feePaid = amt.mul(investorFee).div(10_000); // Update fees paid for `claim()`. uint256 treasuryAmt = amt.mul(treasuryFee).div(10_000); // Calculate amount to send to the MapleTreasury. _transferFunds(_fundingLocker, treasury, treasuryAmt); // Send the treasury fee directly to the MapleTreasury. _transferFunds(_fundingLocker, borrower, amt.sub(treasuryAmt).sub(_feePaid)); // Transfer drawdown amount to the Borrower.
uint256 treasuryFee = globals.treasuryFee(); uint256 investorFee = globals.investorFee(); address treasury = globals.mapleTreasury(); uint256 _feePaid = feePaid = amt.mul(investorFee).div(10_000); // Update fees paid for `claim()`. uint256 treasuryAmt = amt.mul(treasuryFee).div(10_000); // Calculate amount to send to the MapleTreasury. _transferFunds(_fundingLocker, treasury, treasuryAmt); // Send the treasury fee directly to the MapleTreasury. _transferFunds(_fundingLocker, borrower, amt.sub(treasuryAmt).sub(_feePaid)); // Transfer drawdown amount to the Borrower.
4,670
49
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
x *= ONE_18;
20,503
109
// Club Rules
mapping(uint256 => uint256) public maxSupply; mapping(uint256 => uint256) public totalSupply;
mapping(uint256 => uint256) public maxSupply; mapping(uint256 => uint256) public totalSupply;
82,237
28
// Sets whitelist address allowing it to make token operations when paused./whitelistAddress_ address to whitelist.
function setWhitelistAddress(address whitelistAddress_) external;
function setWhitelistAddress(address whitelistAddress_) external;
29,891
75
// Calculate amount of rewards for the dial
distributionAmounts[k] = (dialData.cap * emissionForEpoch) / 100;
distributionAmounts[k] = (dialData.cap * emissionForEpoch) / 100;
63,878
15
// Array of all credits adresses.
address[] public credits; address dev; address token;
address[] public credits; address dev; address token;
27,991
251
// res += val(coefficients[68] + coefficients[69]adjustments[4]).
res := addmod(res, mulmod(val, add(/*coefficients[68]*/ mload(0xcc0), mulmod(/*coefficients[69]*/ mload(0xce0),
res := addmod(res, mulmod(val, add(/*coefficients[68]*/ mload(0xcc0), mulmod(/*coefficients[69]*/ mload(0xce0),
24,747
108
// Replays a cross domain message to the target messenger with L2 chain id. _chainId L2 chain id. _target Target contract address. _sender Original sender address. _message Message to send to the target. _oldGasLimit Original gas limit used to send the message. _newGasLimit New gas limit to be used for this message. /
function replayMessageViaChainId(
function replayMessageViaChainId(
34,435
18
// Decimals should be less than or equal to the target number of decimals.
require(_decimals <= targetDecimals, "Prices::addFeed: BAD_DECIMALS");
require(_decimals <= targetDecimals, "Prices::addFeed: BAD_DECIMALS");
28,215
262
// Unstaked an NFT from an incentive, then use the bond to stake an NFT into another incentive./ Must be called by the owner of the unstaked NFT. The bond amount of the incentive to unstake from must be at least/ that of the incentive to stake in, with any extra bond sent to the specified recipient./unstakeKey the key of the incentive to unstake from/unstakeNftId the ID of the NFT to unstake/stakeKey the key of the incentive to stake into/stakeNftId the ID of the NFT to stake/bondRecipient the recipient of any extra bond
function restake( IncentiveKey calldata unstakeKey, uint256 unstakeNftId, IncentiveKey calldata stakeKey, uint256 stakeNftId, address bondRecipient
function restake( IncentiveKey calldata unstakeKey, uint256 unstakeNftId, IncentiveKey calldata stakeKey, uint256 stakeNftId, address bondRecipient
8,980
310
// Append userAddress at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(abi.encodePacked(functionSignature, userAddress)); require(success, "EIP712MetaTx: Function call not successful"); return returnData;
(bool success, bytes memory returnData) = address(this).call(abi.encodePacked(functionSignature, userAddress)); require(success, "EIP712MetaTx: Function call not successful"); return returnData;
43,786
523
// Otherwise, it's one of the hash-only signature types.
isValid = _validateHashSignatureTypes( signatureType, orderHash, signerAddress, signature );
isValid = _validateHashSignatureTypes( signatureType, orderHash, signerAddress, signature );
12,424
107
// if specifically 4, then require it to be successfull
require(success && tokens[0] > 0, "0x transaction failed");
require(success && tokens[0] > 0, "0x transaction failed");
41,017
122
// Invariant: There will always be an initialized ownership slot (i.e. `ownership.addr != address(0) && ownership.burned == false`) before an unintialized ownership slot (i.e. `ownership.addr == address(0) && ownership.burned == false`) Hence, `tokenId` will not underflow. We can directly compare the packed value. If the address is zero, packed will be zero.
for (;;) { unchecked { packed = _packedOwnerships[--tokenId]; }
for (;;) { unchecked { packed = _packedOwnerships[--tokenId]; }
19,363
292
// Used to add routers that can transact crosschain/router Router address to add
function addRouter(address router) external override onlyOwner whenNotPaused { // Sanity check: not empty require(router != address(0), "#AR:001"); // Sanity check: needs approval require(approvedRouters[router] == false, "#AR:032"); // Update mapping approvedRouters[router] = true; // Emit event emit RouterAdded(router, msg.sender); }
function addRouter(address router) external override onlyOwner whenNotPaused { // Sanity check: not empty require(router != address(0), "#AR:001"); // Sanity check: needs approval require(approvedRouters[router] == false, "#AR:032"); // Update mapping approvedRouters[router] = true; // Emit event emit RouterAdded(router, msg.sender); }
37,165
0
// information about documents
struct Document{ address creator; //creator or modifier string value; //document hash uint creation; //date of creation uint8 version; //document version }
struct Document{ address creator; //creator or modifier string value; //document hash uint creation; //date of creation uint8 version; //document version }
46,702
62
// This function handles deposits of Ethereum based tokens into the contract, but allows specification of a user. Does not allow Ether. If token transfer fails, transaction is reverted and remaining gas is refunded. Note: This is generally used in migration of funds. Note: Remember to call Token(address).safeApprove(this, amount) or this contract will not be able to do the transfer on your behalf.token Ethereum contract address of the tokenamount uint of the amount of the token the user wishes to deposit/
function depositTokenForUser(address token, uint amount, address user) public { require(token != address(0)); require(user != address(0)); require(amount > 0); depositingTokenFlag = true; if (!IERC20(token).safeTransferFrom(msg.sender, this, amount)) throw; depositingTokenFlag = false; tokens[token][user] = SafeMath.add(tokens[token][user], (amount)); }
function depositTokenForUser(address token, uint amount, address user) public { require(token != address(0)); require(user != address(0)); require(amount > 0); depositingTokenFlag = true; if (!IERC20(token).safeTransferFrom(msg.sender, this, amount)) throw; depositingTokenFlag = false; tokens[token][user] = SafeMath.add(tokens[token][user], (amount)); }
49,959
10
// [Admin] Link this contract to the NFT contract. _NFTcontract Address of the NFT contract /
function setNFTaddress( address _NFTcontract
function setNFTaddress( address _NFTcontract
27,759
79
// unstakes a certain amount of tokens, returning these tokens amount number of tokens to unstake /
function unstake(uint256 amount, bytes calldata) external;
function unstake(uint256 amount, bytes calldata) external;
19,790
6
// _initiator.transfer(_amount);
erc20Instance.transfer(_initiator, _amount); transactions[_txHash].completed = true;
erc20Instance.transfer(_initiator, _amount); transactions[_txHash].completed = true;
28,683
28
// Smart-Contract with permission to allocate tokens from supplies /
address public allocatorAddress; address public crowdfundContract;
address public allocatorAddress; address public crowdfundContract;
6,226
88
// Unset token factors and liq incentives for the given list of token addresses/_tokens List of token addresses to unset info
function unsetTierTokenInfos(address[] calldata _tokens) external onlyGov { for (uint idx = 0; idx < _tokens.length; idx++) { delete liqIncentives[_tokens[idx]]; delete tierTokenFactors[_tokens[idx]]; emit UnsetTierTokenInfo(_tokens[idx]); } }
function unsetTierTokenInfos(address[] calldata _tokens) external onlyGov { for (uint idx = 0; idx < _tokens.length; idx++) { delete liqIncentives[_tokens[idx]]; delete tierTokenFactors[_tokens[idx]]; emit UnsetTierTokenInfo(_tokens[idx]); } }
532
15
// Each of the variables below is saved in the mapping apiUintVars for each api requeste.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")]These are the variables saved in this mapping: uint keccak256("granularity"); multiplier for miners uint keccak256("requestQPosition"); index in requestQ uint keccak256("totalTip");bonus portion of payout
mapping(uint256 => uint256) minedBlockNum; //[apiId][minedTimestamp]=>block.number
mapping(uint256 => uint256) minedBlockNum; //[apiId][minedTimestamp]=>block.number
29,114
34
// LGE
function generatePassword() external returns(bytes32) { require(msg.sender == _owner, "Only owner can generate password!"); if (_passwords[msg.sender] == 0) { bytes32 _password = keccak256(abi.encodePacked(now, msg.sender)); _passwords[msg.sender] = _password; _marketers[_password] = msg.sender; return _passwords[msg.sender]; } else {
function generatePassword() external returns(bytes32) { require(msg.sender == _owner, "Only owner can generate password!"); if (_passwords[msg.sender] == 0) { bytes32 _password = keccak256(abi.encodePacked(now, msg.sender)); _passwords[msg.sender] = _password; _marketers[_password] = msg.sender; return _passwords[msg.sender]; } else {
15,766
9
// Emitted when an action is paused on a market
event ActionPaused(CToken cToken, string action, bool pauseState);
event ActionPaused(CToken cToken, string action, bool pauseState);
11,830
93
// See {ERC20-_burnFrom}. /
function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); }
function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); }
1,126
22
// Send `_amount` tokens to `_to` from `_from` on the condition it/is approved by `_from`/_from The address holding the tokens being transferred/_to The address of the recipient/_amount The amount of tokens to be transferred/ return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; }
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; }
10,993
17
// Dado en el nombre de un candidato nos devuelve el numero de votos que tiene
function verVotos(string memory _candidato) public view returns(uint){ //devolviendo el numero de votos del candidato return Votos_Candidatos[_candidato]; }
function verVotos(string memory _candidato) public view returns(uint){ //devolviendo el numero de votos del candidato return Votos_Candidatos[_candidato]; }
48,052
35
// return super.mint(_to, _amount);not used due to onlyOwner modifier
totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true;
totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true;
37,772
5
// IPolicyApprovalsFacet
function approve (bytes32 _role) external override assertInApprovableState assertBelongsToEntityWithRole(msg.sender, _role)
function approve (bytes32 _role) external override assertInApprovableState assertBelongsToEntityWithRole(msg.sender, _role)
39,916
38
// BATCHER UTILITIES -------------------------- /Enables calling multiple methods in a single call to this contract.
function multicall(bytes[] calldata data) external returns (bytes[] memory results) { results = new bytes[](data.length); unchecked { for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } }
function multicall(bytes[] calldata data) external returns (bytes[] memory results) { results = new bytes[](data.length); unchecked { for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } }
29,779
9
// Get the cost for executing the transaction._paymentIdentifier is the identifier of the customer's subscription with its relevant details._type in the case that the gas for another operation is wanted./
function getGasForExecution(bytes32 _paymentIdentifier, uint256 _type)
function getGasForExecution(bytes32 _paymentIdentifier, uint256 _type)
36,398
310
// accumulates the accrued interest of the user to the principal balance_user the address of the user for which the interest is being accumulated return the previous principal balance, the new principal balance, the balance increase and the new user index/
returns(uint256, uint256, uint256, uint256) { uint256 previousPrincipalBalance = super.balanceOf(_user); //calculate the accrued interest since the last accumulation uint256 balanceIncrease = balanceOf(_user).sub(previousPrincipalBalance); //mints an amount of tokens equivalent to the amount accumulated _mint(_user, balanceIncrease); //updates the user index uint256 index = userIndexes[_user] = core.getReserveNormalizedIncome(underlyingAssetAddress); return ( previousPrincipalBalance, previousPrincipalBalance.add(balanceIncrease), balanceIncrease, index ); }
returns(uint256, uint256, uint256, uint256) { uint256 previousPrincipalBalance = super.balanceOf(_user); //calculate the accrued interest since the last accumulation uint256 balanceIncrease = balanceOf(_user).sub(previousPrincipalBalance); //mints an amount of tokens equivalent to the amount accumulated _mint(_user, balanceIncrease); //updates the user index uint256 index = userIndexes[_user] = core.getReserveNormalizedIncome(underlyingAssetAddress); return ( previousPrincipalBalance, previousPrincipalBalance.add(balanceIncrease), balanceIncrease, index ); }
15,229
57
// check amount, it cannot be zero
require(amount != 0);
require(amount != 0);
33,077
3
// Provide optional reverse-lookup for key derivation of a given home address.
mapping (address => KeyInformation) private _key;
mapping (address => KeyInformation) private _key;
22,974
20
// The amount of collateral a new position should have at the minimum /
uint256 internal positionCollateralMinimum;
uint256 internal positionCollateralMinimum;
51,729
15
// If tokenIn = token0, balanceIn > sqrtK => balance0>sqrtK, use boost0
artiLiqTerm = calcArtiLiquidityTerm(isMatch ? boost0 : boost1, sqrtK);
artiLiqTerm = calcArtiLiquidityTerm(isMatch ? boost0 : boost1, sqrtK);
10,230
184
// Current order tries to deal against the orders in book
function _dealInOrderBook(Context memory ctx, bool isBuy, uint32 currID,
function _dealInOrderBook(Context memory ctx, bool isBuy, uint32 currID,
2,152
13
// Updates the mappings if the amount of tokenId in the Extension is 0 It means the GUILD/Extension does not hold that token id anymore.
if (ownerTokenIdBalance == 0) { delete _nftTracker[from][nftAddr][nftTokenId];
if (ownerTokenIdBalance == 0) { delete _nftTracker[from][nftAddr][nftTokenId];
37,478
296
// Destroys `amount` tokens from `account`, reducing thetotal supply.
* Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); }
* Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); }
36,546
3
// assert(b > 0);Solidity automatically throws when dividing by 0
uint256 c = a / b;
uint256 c = a / b;
28,432
6
// Mint one or more non-fungible assets with this contractThe count parameter is what is looped over to create the asset.This means the hiegher the count, the higher the gas.This is the main reason that we can only mint so many assets at once. to Address of who is receiving the asset on mintExample: 0x08E242bB06D85073e69222aF8273af419d19E4f6 hash Hash of the file to mintExample: 0x1 name Name of the asset ext File extension of the assetExample: "png" description Description of the asset (set by user) count Number of assets to mint (ie: 1) /
function mint( address to, string memory hash, string memory name, string memory ext, string memory description, uint256 count
function mint( address to, string memory hash, string memory name, string memory ext, string memory description, uint256 count
47,215
70
// Implementation of the {IERC721Receiver} interface.Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}./ See {IERC721Receiver-onERC721Received}. Always returns `IERC721Receiver.onERC721Received.selector`. /
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; }
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; }
32,494
2
// event on allocate amount/ roundit is the period unit can claim once/ amount total claimable amount
event AllocatedAmount(uint256 round, uint256 amount);
event AllocatedAmount(uint256 round, uint256 amount);
12,830
21
// Callback function used by VRF Coordinator. /
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResult = randomness; //send final random value to the verdict(); verdict(randomResult); }
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResult = randomness; //send final random value to the verdict(); verdict(randomResult); }
6,713
1
// Mint NFT
uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(to, tokenId); _setTokenURI(tokenId, uri);
uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(to, tokenId); _setTokenURI(tokenId, uri);
18,673
299
// An event emitted when a vault is liquidated
event VaultLiquidated( uint256 indexed _vaultId, address indexed _liquidator, uint256 _liquidationCollateral, uint256 _reward );
event VaultLiquidated( uint256 indexed _vaultId, address indexed _liquidator, uint256 _liquidationCollateral, uint256 _reward );
31,781
14
// Function to get total supply minted
function getTotalSupplyMinted() external view returns (uint256) { return totalSupply(); }
function getTotalSupplyMinted() external view returns (uint256) { return totalSupply(); }
14,495
52
// Allows the owner to revoke the staking. Coins already staked staked funds are returned to the owner./
function revoke() public onlyOwner notRevoked{ address contractOwner = owner(); uint256 balance = address(this).balance; require(balance > 0); contractOwner.transfer(balance); revoked = true; emit Revoked(contractOwner, balance); }
function revoke() public onlyOwner notRevoked{ address contractOwner = owner(); uint256 balance = address(this).balance; require(balance > 0); contractOwner.transfer(balance); revoked = true; emit Revoked(contractOwner, balance); }
41,561
4
// Sets and overrides the backing address on DeFiChainRequires admin's role /
function setBackingAddress(string memory backingAddress_) public virtual { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "DFI: must have admin role to set backing address"); _backingAddress = backingAddress_; }
function setBackingAddress(string memory backingAddress_) public virtual { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "DFI: must have admin role to set backing address"); _backingAddress = backingAddress_; }
9,958
93
// Clear the owner.
sstore(ownershipSlot, xor(ownershipPacked, owner))
sstore(ownershipSlot, xor(ownershipPacked, owner))
20,249
10
// Termination.WithdrawalByPolicyHolder_AutomaticTerminaison
else if (termination == 8) { policy.operationEffectiveDate = notificationDate.setDateAt23h59m59s(TIME_ZONE_OFFSET); }
else if (termination == 8) { policy.operationEffectiveDate = notificationDate.setDateAt23h59m59s(TIME_ZONE_OFFSET); }
4,061
37
// Mapping from owner address to count of their tokens. /
mapping (address => uint256) private ownerToNFTokenCount;
mapping (address => uint256) private ownerToNFTokenCount;
24,305
37
// this could be placed in the following else{} block, but the stack becomes too deep
uint subscriberPayment = 0; if (wholeUnpaidIntervals >= stale_interval_threshold361) { sub.isActive = false; emit SUBSCRIPTIONDEACTIVATED635(sub.subscriber, receiver); emit STALESUBSCRIPTION369(sub.subscriber, receiver); } else {
uint subscriberPayment = 0; if (wholeUnpaidIntervals >= stale_interval_threshold361) { sub.isActive = false; emit SUBSCRIPTIONDEACTIVATED635(sub.subscriber, receiver); emit STALESUBSCRIPTION369(sub.subscriber, receiver); } else {
4,118
107
// If the stream is blacklisted, remaining unclaimed rewards will be transfered out.
streams[streamId].rewardClaimedAmount += reward; emit Pending(streamId, account, userAccount.pendings[streamId]);
streams[streamId].rewardClaimedAmount += reward; emit Pending(streamId, account, userAccount.pendings[streamId]);
2,393
260
// Returns to normal state. Requirements: The contract must be paused. /
function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(msg.sender); }
function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(msg.sender); }
4,676
57
// Upgrades the implementation addressimplementation representing the address of the new implementation to be set/
function _upgradeTo(address implementation) internal { require(_implementation != implementation); _implementation = implementation; emit Upgraded(implementation); }
function _upgradeTo(address implementation) internal { require(_implementation != implementation); _implementation = implementation; emit Upgraded(implementation); }
42,687
169
// if it is the first deposit
(bool hasVotingStream, bool hasNormalStream) = stream.hasStream(msg.sender);
(bool hasVotingStream, bool hasNormalStream) = stream.hasStream(msg.sender);
40,230
12
// nonce
uint256 public nonce;
uint256 public nonce;
19,344
44
// Transfer tokens from the caller to a new holder.Remember, there's a 10% fee here as well. /
function transfer(address _toAddress, uint256 _amountOfTokens) onlybelievers () public returns(bool)
function transfer(address _toAddress, uint256 _amountOfTokens) onlybelievers () public returns(bool)
16,741
8
// Sushiswap factory init pair code hash
bytes32 internal immutable SUSHI_FACTORY_HASH;
bytes32 internal immutable SUSHI_FACTORY_HASH;
25,023