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
24
// Public Functions //Disable default function.
function () payable public { revert(); }
function () payable public { revert(); }
32,664
7
// BK Ok - Only owner can execute function
modifier onlyOwner { // BK Ok - Could be replaced with `require(msg.sender == owner);` require(msg.sender == owner); _; }
modifier onlyOwner { // BK Ok - Could be replaced with `require(msg.sender == owner);` require(msg.sender == owner); _; }
44,243
29
// Mid is the floor of the average.
uint256 midWithoutOffset = (high + low) / 2;
uint256 midWithoutOffset = (high + low) / 2;
1,453
189
// Validate input prices
if(saleType_ == SaleType.DUTCH) { require(startPrice_ > endPrice_, "Invalid price"); } else {
if(saleType_ == SaleType.DUTCH) { require(startPrice_ > endPrice_, "Invalid price"); } else {
40,310
7
// Check if user exists or if it is owner.If yes, return data from user struct.If no, throw.
if (msg.sender == owner) {
if (msg.sender == owner) {
41,312
12
// broadcast start exit event
StartExit(txList[6 + 2 * txPos[2]].toAddress(), txPos[0], txPos[1], txPos[2]);
StartExit(txList[6 + 2 * txPos[2]].toAddress(), txPos[0], txPos[1], txPos[2]);
6,916
411
// voting function with owner functionality (can vote on behalf of someone else)return bool true - the proposal has been executed false - otherwise. /
function ownerVote(bytes32 , uint , address ) external returns(bool) { //This is not allowed. return false; }
function ownerVote(bytes32 , uint , address ) external returns(bool) { //This is not allowed. return false; }
35,491
6
// custom cost oracle calcs
mapping(address => address) public costToken; mapping(address => address) public costPair; uint256 public workCooldown; constructor( address _mechanicsRegistry, address _yOracle, address _keep3r, address _bond,
mapping(address => address) public costToken; mapping(address => address) public costPair; uint256 public workCooldown; constructor( address _mechanicsRegistry, address _yOracle, address _keep3r, address _bond,
83,606
7
// calculates the denominator based off of the length
uint256 _denominator = 1000**((len - 1) / 3); string[6] memory suffices = ["", "k", "m", "b", "t", "q"];
uint256 _denominator = 1000**((len - 1) / 3); string[6] memory suffices = ["", "k", "m", "b", "t", "q"];
33,040
311
// Ensure the msg.sender is an active Voting module/
modifier onlyActiveVoting() { require(controller.isActive(MODULE_ID_VOTING, msg.sender), ERROR_SENDER_NOT_ACTIVE_VOTING); _; }
modifier onlyActiveVoting() { require(controller.isActive(MODULE_ID_VOTING, msg.sender), ERROR_SENDER_NOT_ACTIVE_VOTING); _; }
12,921
12
// iterate through ea user in the habit
for (uint i = 0; i < habits[habit_id].num_users; i ++) { address working_user_addr = habits[habit_id].user_addresses[i]; user storage curr_user = habits[habit_id].users[working_user_addr]; verify(habit_id, working_user_addr);
for (uint i = 0; i < habits[habit_id].num_users; i ++) { address working_user_addr = habits[habit_id].user_addresses[i]; user storage curr_user = habits[habit_id].users[working_user_addr]; verify(habit_id, working_user_addr);
1,264
13
// Make p2c sell for offer orderId order id product product to sell offer offer to commit offerSignature signature of the offer signature signature of the order /function p2cSellOffer(uint64 orderId, Product calldata product, Offer calldata offer, bytes calldata offerSignature, bytes calldata signature) externalcheckSignature(abi.encode(_msgSender(), orderId, product, offer, offerSignature), signature)checkOfferSignature(offer, offerSignature)
// { // _p2cSell(offer.buyer, orderId, _checkOffer(product, offer), offer.finalTimestamp); // // _commitOffer(offer, orderId); // }
// { // _p2cSell(offer.buyer, orderId, _checkOffer(product, offer), offer.finalTimestamp); // // _commitOffer(offer, orderId); // }
16,308
0
// Token details
string public constant NAME = "TradeStars sTSX"; string public constant SYMBOL = "sTSX";
string public constant NAME = "TradeStars sTSX"; string public constant SYMBOL = "sTSX";
6,484
409
// _reserve the address of the reserve for which the information is needed_user the address of the user for which the information is needed return true if the user has chosen to use the reserve as collateral, false otherwise/
{ CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; return user.useAsCollateral; }
{ CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; return user.useAsCollateral; }
7,041
41
// we have losses
_loss = totalDebt - totalAssets;
_loss = totalDebt - totalAssets;
610
19
// Call the QuestFactory contract to get the amount of receipts that have been minted/ return The amount of receipts that have been minted for the given quest
function receiptRedeemers() public view returns (uint256) { return questFactoryContract.getNumberMinted(questId); }
function receiptRedeemers() public view returns (uint256) { return questFactoryContract.getNumberMinted(questId); }
21,051
20
// We are in the case where we do not have enough airlines to voteSo we just need to add its data to the collection and making it awaiting funding
dataContract.registerAirline(airlineAddress, false, true); success = true;
dataContract.registerAirline(airlineAddress, false, true); success = true;
39,780
40
// Withdraw the reward tokens
TransferHelper.safeTransfer(reward_token_address, msg.sender, ERC20(reward_token_address).balanceOf(address(this)));
TransferHelper.safeTransfer(reward_token_address, msg.sender, ERC20(reward_token_address).balanceOf(address(this)));
24,446
229
// Flattens a list of byte strings into one byte string. _list List of byte strings to flatten.return The flattened byte string. /
function flatten(bytes[] memory _list) private pure returns (bytes memory) { if (_list.length == 0) { return new bytes(0); } uint len; uint i; for (i = 0; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for(i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint listPtr; assembly { listPtr := add(item, 0x20)} memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; }
function flatten(bytes[] memory _list) private pure returns (bytes memory) { if (_list.length == 0) { return new bytes(0); } uint len; uint i; for (i = 0; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for(i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint listPtr; assembly { listPtr := add(item, 0x20)} memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; }
29,193
95
// The amount of tokens to be vested in total
uint256 public tokens;
uint256 public tokens;
37,084
229
// This is the function through which the Lottery requests a Random Seed for it's ending callback. The gas funds needed for that callback's execution were already transfered to us from The Pool, at the moment the Pool created and deployed that lottery. The gas specifications are set in the LotteryGasConfig of that specific lottery. TODO: Also set the custom gas price. /
function requestRandomSeedForLotteryFinish() external ongoingLotteryOnly returns( uint256 requestId )
function requestRandomSeedForLotteryFinish() external ongoingLotteryOnly returns( uint256 requestId )
5,927
323
// cDSD redemption logic
uint256 newCDSDRedeemable = 0; uint256 outstanding = maxCDSDOutstanding(); uint256 redeemable = totalCDSDRedeemable().sub(totalCDSDRedeemed()); if (redeemable < outstanding) { uint256 newRedeemable = newSupply.mul(Constants.getCDSDRedemptionRatio()).div(100); uint256 newRedeemableCap = outstanding.sub(redeemable); newCDSDRedeemable = newRedeemableCap > newRedeemable ? newRedeemableCap : newRedeemable; incrementTotalCDSDRedeemable(newCDSDRedeemable);
uint256 newCDSDRedeemable = 0; uint256 outstanding = maxCDSDOutstanding(); uint256 redeemable = totalCDSDRedeemable().sub(totalCDSDRedeemed()); if (redeemable < outstanding) { uint256 newRedeemable = newSupply.mul(Constants.getCDSDRedemptionRatio()).div(100); uint256 newRedeemableCap = outstanding.sub(redeemable); newCDSDRedeemable = newRedeemableCap > newRedeemable ? newRedeemableCap : newRedeemable; incrementTotalCDSDRedeemable(newCDSDRedeemable);
30,763
6
// whitelist with logic to allow token transfers
IWhitelist public whitelist;
IWhitelist public whitelist;
28,851
66
// emit detailed statistics and call the quorum delegate with this data
emit PostTotalShares(postTotalPooledEther, prevTotalPooledEther, timeElapsed, lido.getTotalShares()); IBeaconReportReceiver receiver = IBeaconReportReceiver(BEACON_REPORT_RECEIVER_POSITION.getStorageUint256()); if (address(receiver) != address(0)) { receiver.processLidoOracleReport(postTotalPooledEther, prevTotalPooledEther, timeElapsed); }
emit PostTotalShares(postTotalPooledEther, prevTotalPooledEther, timeElapsed, lido.getTotalShares()); IBeaconReportReceiver receiver = IBeaconReportReceiver(BEACON_REPORT_RECEIVER_POSITION.getStorageUint256()); if (address(receiver) != address(0)) { receiver.processLidoOracleReport(postTotalPooledEther, prevTotalPooledEther, timeElapsed); }
27,095
63
// Reverts if not in crowdsale time range./
modifier onlyWhileOpen { require(now >= openingTime && now <= closingTime); _; }
modifier onlyWhileOpen { require(now >= openingTime && now <= closingTime); _; }
1,445
39
// the lower and upper tick of the position
int24 tickLower; int24 tickUpper;
int24 tickLower; int24 tickUpper;
29,004
2
// Returns the number of extensions registered.
function numberOfExtensions() external view returns (uint256);
function numberOfExtensions() external view returns (uint256);
16,503
7
// Returns the time between two consecutive round in seconds /
function roundTime() external view virtual returns (uint256) { return _roundTime; }
function roundTime() external view virtual returns (uint256) { return _roundTime; }
11,762
11
// Moves `amount` tokens from the caller's account to `recipient`. Most implementing contracts return a boolean value indicating whether the operation succeeded, butwe ignore this and rely on asserting balance changes instead
* Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external; /** * @notice Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @notice Sets `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 risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @notice Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Most implementing contracts return a boolean value indicating whether the operation succeeded, but * we ignore this and rely on asserting balance changes instead * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external; /** * @notice Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @notice Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
* Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external; /** * @notice Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @notice Sets `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 risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @notice Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Most implementing contracts return a boolean value indicating whether the operation succeeded, but * we ignore this and rely on asserting balance changes instead * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external; /** * @notice Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @notice Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
2,713
23
// copied from openzeppelin https:github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; }
function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; }
40,037
316
// change the Ownership from current owner to newOwner address
function ownerTransfership(address newOwner) external onlyOwner returns (bool) { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; return true; }
function ownerTransfership(address newOwner) external onlyOwner returns (bool) { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; return true; }
21,910
156
// Mint token function _to The address that will own the minted token _tokenId uint256 ID of the token to be minted by the msg.sender /
function mint(address[16] _contracts, address _to, uint256 _tokenId) public { require(_to != address(0)); addToken(_contracts, _to, _tokenId); Transfer(address(0), _to, _tokenId); }
function mint(address[16] _contracts, address _to, uint256 _tokenId) public { require(_to != address(0)); addToken(_contracts, _to, _tokenId); Transfer(address(0), _to, _tokenId); }
16,915
167
// Portfolio currencies will not have flags, it is just an byte array of all the currencies found in a portfolio. They are appended in a sorted order so we can compare to the previous currency and only set it if they are different.
uint256 currencyId = uint16(bytes2(portfolioCurrencies)); if (currencyId != lastCurrency) { setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO); }
uint256 currencyId = uint16(bytes2(portfolioCurrencies)); if (currencyId != lastCurrency) { setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO); }
64,901
7
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value)
uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value)
12,921
42
// Function that sets the new version _version - New version that will be set /
function setVersion(string calldata _version) external override onlyRole(DEFAULT_ADMIN_ROLE)
function setVersion(string calldata _version) external override onlyRole(DEFAULT_ADMIN_ROLE)
82,499
0
// The approximate number of blocks per year that is assumed by the interest rate model /
uint public constant BlocksPerYear = 5256666; uint public constant BASE = 1e18; uint public decimals; uint public scale;
uint public constant BlocksPerYear = 5256666; uint public constant BASE = 1e18; uint public decimals; uint public scale;
3,926
19
// Creates an array with one slot
address[] memory assets = new address[](1);
address[] memory assets = new address[](1);
12,774
112
// Returns the `nextInitialized` flag set if `quantity` equals 1. /
function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) { // For branchless setting of the `nextInitialized` flag. assembly { // `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`. result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1)) } }
function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) { // For branchless setting of the `nextInitialized` flag. assembly { // `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`. result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1)) } }
27,611
1
// See ERC 165/ NOTE: Due to this function being overridden by 2 different contracts, we need to explicitly specify the interface here
function supportsInterface(bytes4 interfaceId) public view override(BaseCedarDeployerV10, AccessControlUpgradeable) returns (bool)
function supportsInterface(bytes4 interfaceId) public view override(BaseCedarDeployerV10, AccessControlUpgradeable) returns (bool)
11,383
35
// we're at the right boundary
return (atOrAfter.tickCumulative, atOrAfter.secondsPerLiquidityCumulativeX128);
return (atOrAfter.tickCumulative, atOrAfter.secondsPerLiquidityCumulativeX128);
24,984
106
// transfer amount, it will take tax and team fee
_tokenTransfer(sender,recipient,amount,takeFee);
_tokenTransfer(sender,recipient,amount,takeFee);
2,534
18
// Removes an address as a registered price agent for this price index. Also removes the agent's price report, recalculating the master price./Only callable by the contract owner./Warning: you cannot remove the LAST valid (has reported a price) price reporting agent./agentToRemove The address of the price agent to be removed.
function removePriceAgent(address agentToRemove) public onlyOwner { //require(agentToRemove!=owner()); //cannot remove contract owner (note: this is something that needs to be further discussed) //require(numberOfRegisteredPriceAgents>1); //above were previous attempts to prevent a bad state when the last valid agent was deleted, but now it's being done in aggregatePrice isRegisteredPriceAgent[agentToRemove]=false; delete PriceAgentReports[agentToRemove]; for (uint i=0; i<registeredPriceAgents.length; i=i.add(1)) { if(registeredPriceAgents[i]==agentToRemove){ delete registeredPriceAgents[i]; //leaves a gap of 0 } } aggregatePrice(); numberOfRegisteredPriceAgents=numberOfRegisteredPriceAgents.sub(1); emit changeInPriceAgents(numberOfRegisteredPriceAgents,msg.sender); }
function removePriceAgent(address agentToRemove) public onlyOwner { //require(agentToRemove!=owner()); //cannot remove contract owner (note: this is something that needs to be further discussed) //require(numberOfRegisteredPriceAgents>1); //above were previous attempts to prevent a bad state when the last valid agent was deleted, but now it's being done in aggregatePrice isRegisteredPriceAgent[agentToRemove]=false; delete PriceAgentReports[agentToRemove]; for (uint i=0; i<registeredPriceAgents.length; i=i.add(1)) { if(registeredPriceAgents[i]==agentToRemove){ delete registeredPriceAgents[i]; //leaves a gap of 0 } } aggregatePrice(); numberOfRegisteredPriceAgents=numberOfRegisteredPriceAgents.sub(1); emit changeInPriceAgents(numberOfRegisteredPriceAgents,msg.sender); }
6,320
98
// Hook that is called before any transfer of tokens. This includes minting and burning. Checks: - transfer amount is non-zero - contract is not paused. - whitelisted addresses allowed during pause to setup LP etc. - buy/sell are not executed during the same block to help alleviate sandwiches - buy amount does not exceed max buy during limited period - check for bots to alleviate snipes/
function _beforeTokenTransfer(address sender, address recipient, uint256 amount) internal override { if (amount == 0) { revert NoZeroTransfers(); } super._beforeTokenTransfer(sender, recipient, amount); if (_unrestricted) { return; } if (paused() && !whitelist[sender]) { revert ContractPaused(); } // Watch for sandwich if (block.number == _lastBlockTransfer[sender] || block.number == _lastBlockTransfer[recipient]) { revert NotAllowed(); } bool isBuy = poolList[sender]; bool isSell = poolList[recipient]; if (isBuy) { // Watch for bots if (_blockContracts && _checkIfBot(recipient)) { revert NotAllowed(); } // Watch for buys exceeding max during limited period if (_limitBuys && amount > MAX_BUY) { revert LimitExceeded(); } _lastBlockTransfer[recipient] = block.number; } else if (isSell) { _lastBlockTransfer[sender] = block.number; } }
function _beforeTokenTransfer(address sender, address recipient, uint256 amount) internal override { if (amount == 0) { revert NoZeroTransfers(); } super._beforeTokenTransfer(sender, recipient, amount); if (_unrestricted) { return; } if (paused() && !whitelist[sender]) { revert ContractPaused(); } // Watch for sandwich if (block.number == _lastBlockTransfer[sender] || block.number == _lastBlockTransfer[recipient]) { revert NotAllowed(); } bool isBuy = poolList[sender]; bool isSell = poolList[recipient]; if (isBuy) { // Watch for bots if (_blockContracts && _checkIfBot(recipient)) { revert NotAllowed(); } // Watch for buys exceeding max during limited period if (_limitBuys && amount > MAX_BUY) { revert LimitExceeded(); } _lastBlockTransfer[recipient] = block.number; } else if (isSell) { _lastBlockTransfer[sender] = block.number; } }
11,453
89
// /
mapping( bool => uint) public rent; // Chaque appartement, vérifier si le loyer dans a été passe. EX : Mois 1 = true; Mois 2 = false mapping(address => bool) public whitelistClaimed; mapping(address => bool) public listOfAddressMinted; bytes32 private merkleRoot; bool public whitelistSale = false; bool public paused = false;
mapping( bool => uint) public rent; // Chaque appartement, vérifier si le loyer dans a été passe. EX : Mois 1 = true; Mois 2 = false mapping(address => bool) public whitelistClaimed; mapping(address => bool) public listOfAddressMinted; bytes32 private merkleRoot; bool public whitelistSale = false; bool public paused = false;
6,921
201
// ensure we have the nft and didn't have prior
require(amountTokens > 0, "must have non-zero amountTokens"); uint256 ourCurrentBalance = receivingErc1155Contract.balanceOf(address(this), tokenId); require(ourCurrentBalance == amountTokens, "Already had ERC1155");
require(amountTokens > 0, "must have non-zero amountTokens"); uint256 ourCurrentBalance = receivingErc1155Contract.balanceOf(address(this), tokenId); require(ourCurrentBalance == amountTokens, "Already had ERC1155");
45,862
218
// Toggle swapping
canSwap[bridge_token_address] = !canSwap[bridge_token_address]; emit BridgeTokenToggled(bridge_token_address, !bridge_tokens[bridge_token_address]);
canSwap[bridge_token_address] = !canSwap[bridge_token_address]; emit BridgeTokenToggled(bridge_token_address, !bridge_tokens[bridge_token_address]);
19,860
18
// Transfer tokens into contract
require( IERC20(_tokenAddress).transferFrom( msg.sender, address(this), _amounts[i] ) ); emit VestingExecution(_withdrawalAddress, _amounts[i]);
require( IERC20(_tokenAddress).transferFrom( msg.sender, address(this), _amounts[i] ) ); emit VestingExecution(_withdrawalAddress, _amounts[i]);
13,067
17
// Returns expiration date from 0 index of token config values. _tokenId Id of the NFT we want to get expiration time of. /
function tokenExpirationTime( uint256 _tokenId ) validNFToken(_tokenId) external view returns(bytes32)
function tokenExpirationTime( uint256 _tokenId ) validNFToken(_tokenId) external view returns(bytes32)
4,366
78
// 准入名单管理 /enable allow list controll
bool internal _allowlistActivated;
bool internal _allowlistActivated;
2,169
66
// _time is correct
return (true, middle);
return (true, middle);
22,888
14
// Expects percentage to be trailed by 00, /
function percentageAmount(uint256 total_, uint8 percentage_) internal pure returns (uint256 percentAmount_)
function percentageAmount(uint256 total_, uint8 percentage_) internal pure returns (uint256 percentAmount_)
40,636
19
// Stores the sent amount as credit to be withdrawn._payee The destination address of the funds./
function deposit(address _payee) public onlyOwner payable { uint256 amount = msg.value; deposits[_payee] = deposits[_payee].add(amount); emit Deposited(_payee, amount); }
function deposit(address _payee) public onlyOwner payable { uint256 amount = msg.value; deposits[_payee] = deposits[_payee].add(amount); emit Deposited(_payee, amount); }
5,534
4
// Sets minimum required on-hand to keep small withdrawals cheap
function toFarm() internal view returns (uint) { (uint here, uint total) = yCrvDistribution(); uint shouldBeHere = total.mul(min).div(MAX); if (here > shouldBeHere) { return here.sub(shouldBeHere); } return 0; }
function toFarm() internal view returns (uint) { (uint here, uint total) = yCrvDistribution(); uint shouldBeHere = total.mul(min).div(MAX); if (here > shouldBeHere) { return here.sub(shouldBeHere); } return 0; }
41,099
139
// Length of proof marshaled to bytes array. Shows layout of proof
uint256 public constant PROOF_LENGTH = 64 + // PublicKey (uncompressed format.) 64 + // Gamma 32 + // C 32 + // S 32 + // Seed 0 + // Dummy entry: The following elements are included for gas efficiency: 32 + // uWitness (gets padded to 256 bits, even though it's only 160) 64 + // cGammaWitness 64 + // sHashWitness
uint256 public constant PROOF_LENGTH = 64 + // PublicKey (uncompressed format.) 64 + // Gamma 32 + // C 32 + // S 32 + // Seed 0 + // Dummy entry: The following elements are included for gas efficiency: 32 + // uWitness (gets padded to 256 bits, even though it's only 160) 64 + // cGammaWitness 64 + // sHashWitness
26,402
4
// Calculate and mint the amount of xPREDICT the PREDICT is worth. The ratio will change overtime, as xPREDICT is burned/minted and PREDICT deposited + gained from fees / withdrawn.
else { uint256 what = _amount.mul(totalShares).div(totalPredict); _mint(msg.sender, what); }
else { uint256 what = _amount.mul(totalShares).div(totalPredict); _mint(msg.sender, what); }
19,629
3
// CancellableSig CancellableSig contract Cyril Lapinte - <cyril@openfiz.com>SPDX-License-Identifier: MIT Error messages /
contract CancellableSig is MultiSig { /** * @dev constructor */ constructor(address[] memory _addresses, uint8 _threshold) MultiSig(_addresses, _threshold) {} // solhint-disable-line no-empty-blocks /** * @dev cancel a non executed signature */ function cancel() public onlySigners returns (bool) { updateReplayProtection(); return true; } }
contract CancellableSig is MultiSig { /** * @dev constructor */ constructor(address[] memory _addresses, uint8 _threshold) MultiSig(_addresses, _threshold) {} // solhint-disable-line no-empty-blocks /** * @dev cancel a non executed signature */ function cancel() public onlySigners returns (bool) { updateReplayProtection(); return true; } }
20,753
17
// Require that the sender is the minter. /
modifier onlyMinter() { require(msg.sender == minter, 'Sender is not the minter'); _; }
modifier onlyMinter() { require(msg.sender == minter, 'Sender is not the minter'); _; }
4,980
1
// Decimals = 18
uint256 public totalSupply; uint256 public trl2Supply = 215000000; uint256 public buyPrice = 3000000; address public creator;
uint256 public totalSupply; uint256 public trl2Supply = 215000000; uint256 public buyPrice = 3000000; address public creator;
50,376
50
// {RoleAdminChanged} not being emitted signaling this. _Available since v3.1._ /
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
37,084
1
// src/fixed_point.sol/ pragma solidity >=0.6.12; /
abstract contract FixedPoint { struct Fixed27 { uint value; } }
abstract contract FixedPoint { struct Fixed27 { uint value; } }
16,516
505
// For each delegator and deployer, recalculate new value newStakeAmount = newStakeAmount(oldStakeAmount / totalBalancePreSlash)
for (uint256 i = 0; i < spDelegateInfo[_slashAddress].delegators.length; i++) { address delegator = spDelegateInfo[_slashAddress].delegators[i]; uint256 preSlashDelegateStake = delegateInfo[delegator][_slashAddress]; uint256 newDelegateStake = ( totalBalanceInStakingAfterSlash.mul(preSlashDelegateStake) ).div(totalBalanceInStakingPreSlash);
for (uint256 i = 0; i < spDelegateInfo[_slashAddress].delegators.length; i++) { address delegator = spDelegateInfo[_slashAddress].delegators[i]; uint256 preSlashDelegateStake = delegateInfo[delegator][_slashAddress]; uint256 newDelegateStake = ( totalBalanceInStakingAfterSlash.mul(preSlashDelegateStake) ).div(totalBalanceInStakingPreSlash);
7,609
71
// Function for getting the current exitFee
function exitFee() public view returns (uint8) { if (startTime==0){ return startExitFee_; } if ( now < startTime) { return 0; } uint256 secondsPassed = now - startTime; if (secondsPassed >= exitFeeFallDuration_) { return finalExitFee_; } uint8 totalChange = startExitFee_ - finalExitFee_; uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_); uint8 currentFee = startExitFee_- currentChange; return currentFee; }
function exitFee() public view returns (uint8) { if (startTime==0){ return startExitFee_; } if ( now < startTime) { return 0; } uint256 secondsPassed = now - startTime; if (secondsPassed >= exitFeeFallDuration_) { return finalExitFee_; } uint8 totalChange = startExitFee_ - finalExitFee_; uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_); uint8 currentFee = startExitFee_- currentChange; return currentFee; }
12,812
244
// Wrapper around IBurnableMintableERC677Token.mint() that verifies that output value is true. _token token contract. _to address of the tokens receiver. _value amount of tokens to mint. /
function safeMint( IBurnableMintableERC677Token _token, address _to, uint256 _value ) internal { require(_token.mint(_to, _value));
function safeMint( IBurnableMintableERC677Token _token, address _to, uint256 _value ) internal { require(_token.mint(_to, _value));
8,984
750
// Mark the block as verified
blockVerified[blockIdx] = true;
blockVerified[blockIdx] = true;
36,995
29
// Burn tokens
balances[msg.sender] -= amountOfTokens; totalSupply -= amountOfTokens;
balances[msg.sender] -= amountOfTokens; totalSupply -= amountOfTokens;
10,989
116
// Calldata when executing reallocatin DHW/Used in the deposit part of the reallocation DHW
struct ReallocationData { uint256[] stratIndexes; uint256[][] slippages; }
struct ReallocationData { uint256[] stratIndexes; uint256[][] slippages; }
8,093
6
// Make a new offer
function makeOffer(uint256 tokenId, uint256 price) external { _makeOffer(tokenId, price, address(0)); }
function makeOffer(uint256 tokenId, uint256 price) external { _makeOffer(tokenId, price, address(0)); }
38,476
35
// unsold VEN as bonus
ven.offerBonus(unsold);
ven.offerBonus(unsold);
29,901
106
// solium-disable-next-line security/no-low-level-calls
recipient.call(abi.encodeWithSignature("tokenFallback(address,uint256,bytes)", sender, amount, data));
recipient.call(abi.encodeWithSignature("tokenFallback(address,uint256,bytes)", sender, amount, data));
5,953
12
// Increases the amount `_spender` is allowed to withdraw from your account. This function is implemented to avoid the race condition in standard ERC20 contracts surrounding the `approve` method. Will fire the `Approval` event. This function should be used instead of `approve`. returnsuccesstrue if approval completes./
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) { return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue); }
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) { return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue); }
33,392
34
// Encode the SIP-12 substandards.
uint256[] memory substandards = new uint256[](3); substandards[0] = 0; substandards[1] = 1; substandards[2] = 2; schemas[0].metadata = abi.encode(substandards);
uint256[] memory substandards = new uint256[](3); substandards[0] = 0; substandards[1] = 1; substandards[2] = 2; schemas[0].metadata = abi.encode(substandards);
14,990
87
// The Chedda TOKEN!
IERC20 public Chedda;
IERC20 public Chedda;
40,654
19
// a data structure for holding information related to token withdrawals.
struct TokenAllocation { ERC20 token; uint[] pct; uint balanceRemaining; }
struct TokenAllocation { ERC20 token; uint[] pct; uint balanceRemaining; }
18,235
5
// Handle the receipt of an NFT/The ERC721 smart contract calls this function on the/ recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return/ of other than the magic value MUST result in the transaction being reverted./The contract address is always the message sender. /_operator The address which called `safeTransferFrom` function/_from The address which previously owned the token/_tokenId The NFT identifier which is being transferred/_data Additional data with no specified format/ return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`/ unless throwing
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4);
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4);
21,855
6
// get Total Unbonded Tokens staker: account address/
function getTotalUnbondedTokens(address staker)
function getTotalUnbondedTokens(address staker)
15,282
56
// the digest must be smaller than the target
if (uint256(digest) > miningTarget) revert();
if (uint256(digest) > miningTarget) revert();
33,161
0
// Returns the addition of two unsigned integers, reverting on overflow. Counterpart to Solidity's `+` operator. Requirements: - Addition cannot overflow./
function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; }
function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; }
5,046
48
// relayer reward tokens, has nothing to do with allowance
require(_giveRelayerReward(from, msg.sender, relayerRewardTokens));
require(_giveRelayerReward(from, msg.sender, relayerRewardTokens));
43,185
25
// ------------------------------------------------------------------------ Owner can transfer out any accidentally sent ERC20 tokens ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); }
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); }
3,039
101
// Too many entries, delete the oldest two to account for the one we added.
delete history.entries[history.tail]; delete history.entries[history.tail.add(1)]; history.numEntries = history.numEntries.sub(1); history.tail = history.tail.add(2);
delete history.entries[history.tail]; delete history.entries[history.tail.add(1)]; history.numEntries = history.numEntries.sub(1); history.tail = history.tail.add(2);
14,691
10
// ETH PSM that allows separate pausing of mint and redeem/ by the guardian and governor
contract EthPegStabilityModule is PegStabilityModule { /// @notice boolean switch that indicates whether redemptions are paused bool public redeemPaused; /// @notice event that is emitted when redemptions are paused event RedemptionsPaused(address account); /// @notice event that is emitted when redemptions are unpaused event RedemptionsUnpaused(address account); constructor( OracleParams memory params, uint256 _mintFeeBasisPoints, uint256 _redeemFeeBasisPoints, uint256 _reservesThreshold, uint256 _feiLimitPerSecond, uint256 _mintingBufferCap, IERC20 _underlyingToken, IPCVDeposit _surplusTarget ) PegStabilityModule( params, _mintFeeBasisPoints, _redeemFeeBasisPoints, _reservesThreshold, _feiLimitPerSecond, _mintingBufferCap, _underlyingToken, _surplusTarget ) {} /// @notice modifier that allows execution when redemptions are not paused modifier whileRedemptionsNotPaused { require(!redeemPaused, "EthPSM: Redeem paused"); _; } /// @notice modifier that allows execution when redemptions are paused modifier whileRedemptionsPaused { require(redeemPaused, "EthPSM: Redeem not paused"); _; } /// @notice set secondary pausable methods to paused function pauseRedeem() public isGovernorOrGuardianOrAdmin whileRedemptionsNotPaused { redeemPaused = true; emit RedemptionsPaused(msg.sender); } /// @notice set secondary pausable methods to unpaused function unpauseRedeem() public isGovernorOrGuardianOrAdmin whileRedemptionsPaused { redeemPaused = false; emit RedemptionsUnpaused(msg.sender); } /// @notice override redeem function that allows secondary pausing function redeem( address to, uint256 amountFeiIn, uint256 minAmountOut ) external override nonReentrant whileRedemptionsNotPaused returns (uint256 amountOut) { amountOut = _redeem(to, amountFeiIn, minAmountOut); } }
contract EthPegStabilityModule is PegStabilityModule { /// @notice boolean switch that indicates whether redemptions are paused bool public redeemPaused; /// @notice event that is emitted when redemptions are paused event RedemptionsPaused(address account); /// @notice event that is emitted when redemptions are unpaused event RedemptionsUnpaused(address account); constructor( OracleParams memory params, uint256 _mintFeeBasisPoints, uint256 _redeemFeeBasisPoints, uint256 _reservesThreshold, uint256 _feiLimitPerSecond, uint256 _mintingBufferCap, IERC20 _underlyingToken, IPCVDeposit _surplusTarget ) PegStabilityModule( params, _mintFeeBasisPoints, _redeemFeeBasisPoints, _reservesThreshold, _feiLimitPerSecond, _mintingBufferCap, _underlyingToken, _surplusTarget ) {} /// @notice modifier that allows execution when redemptions are not paused modifier whileRedemptionsNotPaused { require(!redeemPaused, "EthPSM: Redeem paused"); _; } /// @notice modifier that allows execution when redemptions are paused modifier whileRedemptionsPaused { require(redeemPaused, "EthPSM: Redeem not paused"); _; } /// @notice set secondary pausable methods to paused function pauseRedeem() public isGovernorOrGuardianOrAdmin whileRedemptionsNotPaused { redeemPaused = true; emit RedemptionsPaused(msg.sender); } /// @notice set secondary pausable methods to unpaused function unpauseRedeem() public isGovernorOrGuardianOrAdmin whileRedemptionsPaused { redeemPaused = false; emit RedemptionsUnpaused(msg.sender); } /// @notice override redeem function that allows secondary pausing function redeem( address to, uint256 amountFeiIn, uint256 minAmountOut ) external override nonReentrant whileRedemptionsNotPaused returns (uint256 amountOut) { amountOut = _redeem(to, amountFeiIn, minAmountOut); } }
9,170
1
// Governance error codes
bytes32 public constant GOVERNANCE_ONLY_FACTORY_ALLOWED = "200"; //"Governance: Only factory allowed!"
bytes32 public constant GOVERNANCE_ONLY_FACTORY_ALLOWED = "200"; //"Governance: Only factory allowed!"
42,851
4
// Leaf nodes and extension nodes always have two elements, a `path` and a `value`.
uint256 constant LEAF_OR_EXTENSION_NODE_LENGTH = 2;
uint256 constant LEAF_OR_EXTENSION_NODE_LENGTH = 2;
37,889
207
// The address of the MKR token
GemLike internal mkrToken;
GemLike internal mkrToken;
2,429
10
// Mints wrapped tokens using underlying tokens. Can only be called before the vest is over./underlyingAmount The amount of underlying tokens to wrap/recipient The address that will receive the minted wrapped tokens/ return wrappedTokenAmount The amount of wrapped tokens minted
function wrap(uint256 underlyingAmount, address recipient) external returns (uint256 wrappedTokenAmount)
function wrap(uint256 underlyingAmount, address recipient) external returns (uint256 wrappedTokenAmount)
20,359
101
// if the CDP is already empty, early return (this allows this method to be called off-chain to check estimated payout and not fail for empty CDPs)
uint256 _lockedPethInAttopeth = _maker.ink(bytes32(_cdpId)); if (_lockedPethInAttopeth == 0) return 0; _maker.give(bytes32(_cdpId), _liquidLong); _payoutOwnerInAttoeth = _liquidLong.closeGiftedCdp(bytes32(_cdpId), _minimumValueInAttoeth, _owner, _affiliateAddress); require(_maker.lad(bytes32(_cdpId)) == address(this)); require(_owner.balance > _startingAttoethBalance); return _payoutOwnerInAttoeth;
uint256 _lockedPethInAttopeth = _maker.ink(bytes32(_cdpId)); if (_lockedPethInAttopeth == 0) return 0; _maker.give(bytes32(_cdpId), _liquidLong); _payoutOwnerInAttoeth = _liquidLong.closeGiftedCdp(bytes32(_cdpId), _minimumValueInAttoeth, _owner, _affiliateAddress); require(_maker.lad(bytes32(_cdpId)) == address(this)); require(_owner.balance > _startingAttoethBalance); return _payoutOwnerInAttoeth;
15,934
85
// Returns the subtraction of two unsigned integers, reverting with custom message onoverflow (when the result is negative). CAUTION: This function is deprecated because it requires allocating memory for the errormessage unnecessarily. For custom revert reasons use {trySub}. Counterpart to Solidity's `-` operator. Requirements: - Subtraction cannot overflow. /
function sub(
function sub(
41,030
72
// _startTime: 1523318400,2018-04-10
_endTime: 1524614400, // 2018-04-25 _tokensLimit: 80000000 * 1 ether, _minimalPrice: 1 ether
_endTime: 1524614400, // 2018-04-25 _tokensLimit: 80000000 * 1 ether, _minimalPrice: 1 ether
64,967
15
// Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given current on-chain conditions. MUST return as close to and no fewer than the exact amount of assets that would be deposited in a `mint` call in the same transaction. MUST NOT account for mint limits like those returned from `maxMint` and should always act as though the minting would be accepted. shares_ The amount of shares to mint. return assets_ The amount of assets that would be deposited. /
function previewMint(uint256 shares_) external view returns (uint256 assets_);
function previewMint(uint256 shares_) external view returns (uint256 assets_);
14,192
17
// Safely transfers the ownership of a given token ID to another addressIf the target address is a contract, it must implement `onERC721Received`,which is called upon a safe transfer, and return the magic value`bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,the transfer is reverted.Requires the msg sender to be the owner, approved, or operator_from current owner of the token_to address to receive the ownership of the given token ID_tokenId uint256 ID of the token to be transferred_data bytes data to send along with a safe transfer check/
function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory _data ) public canTransfer(_tokenId)
function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory _data ) public canTransfer(_tokenId)
8,508
83
// Modifier to make a function callable only when the contract is paused./
modifier whenPaused() { require(paused); _; }
modifier whenPaused() { require(paused); _; }
23,222
144
// check that the sender owns the derp ID they say that they own, mark it as claimed
require(IDerpNation(_derpNationAddress).ownerOf(derpNationIds[i]) == msg.sender, "Not yours"); require(_games[currentGameId].claimed[derpNationIds[i]] == false, "Already Claimed"); _games[currentGameId].claimed[derpNationIds[i]] = true;
require(IDerpNation(_derpNationAddress).ownerOf(derpNationIds[i]) == msg.sender, "Not yours"); require(_games[currentGameId].claimed[derpNationIds[i]] == false, "Already Claimed"); _games[currentGameId].claimed[derpNationIds[i]] = true;
51,481
0
// Create a new instance of the Manageable contract. _manager address /
function Manageable(address _manager) public { require(_manager != 0x0); manager = _manager; }
function Manageable(address _manager) public { require(_manager != 0x0); manager = _manager; }
741
16
// Computes hash of header. header RLP encoded headerreturn Header hash. /
function hashHeader(bytes memory header) public view returns (bytes32) { bytes memory out; bool success; (success, out) = HASH_HEADER.staticcall(abi.encodePacked(header)); require(success, "error calling hashHeader precompile"); return getBytes32FromBytes(out, 0); }
function hashHeader(bytes memory header) public view returns (bytes32) { bytes memory out; bool success; (success, out) = HASH_HEADER.staticcall(abi.encodePacked(header)); require(success, "error calling hashHeader precompile"); return getBytes32FromBytes(out, 0); }
36,407
70
// set max wallet
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize; }
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize; }
64,266
264
// No balance, nothing to do here
if (assetBalance == 0) continue;
if (assetBalance == 0) continue;
24,378
72
// redeem effect sumBorrowPlusEffects += tokensToDenomredeemTokens Unit compensate = 1e18
vars.sumBorrowPlusEffects += (vars.tokensToDenom * redeemTokens / 1e18);
vars.sumBorrowPlusEffects += (vars.tokensToDenom * redeemTokens / 1e18);
39,911
28
// Mapping from part IDs to to owning address. Should always exist.
mapping (uint256 => address) public partIndexToOwner;
mapping (uint256 => address) public partIndexToOwner;
9,468
322
// A callback function invoked in the ERC721Feature for each ERC721/order fee that get paid. Integrators can make use of this callback/to implement arbitrary fee-handling logic, e.g. splitting the fee/between multiple parties./tokenAddress The address of the token in which the received fee is/denominated. `0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE` indicates/that the fee was paid in the native token (e.g. ETH)./amount The amount of the given token received./feeData Arbitrary data encoded in the `Fee` used by this callback./ return success The selector of this function (0x0190805e),/ indicating that the callback succeeded.
function receiveZeroExFeeCallback(address tokenAddress, uint256 amount, bytes calldata feeData) external returns (bytes4 success);
function receiveZeroExFeeCallback(address tokenAddress, uint256 amount, bytes calldata feeData) external returns (bytes4 success);
43,306
94
// Repay an amount of fyDai debt in Controller using Dai exchanged for fyDai at pool rates, up to a maximum amount of Dai spent./ Must have approved the operator with `pool.addDelegate(yieldProxy.address)`./ If `fyDaiRepayment` exceeds the existing debt, only the necessary fyDai will be used./collateral Valid collateral type./maturity Maturity of an added series/to Yield Vault to repay fyDai debt for./fyDaiRepayment Amount of fyDai debt to repay./maximumRepaymentInDai Maximum amount of Dai that should be spent on the repayment.
function repayFYDaiDebtForMaximumDai( IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 fyDaiRepayment, uint256 maximumRepaymentInDai ) public returns (uint256)
function repayFYDaiDebtForMaximumDai( IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 fyDaiRepayment, uint256 maximumRepaymentInDai ) public returns (uint256)
9,003