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
563
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require( _reserveWeight > 0 && _reserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT" );
require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require( _reserveWeight > 0 && _reserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT" );
66,263
4
// rewards wallet, default to the rewards contract itself, not a wallet. But if rewards are disabled then they'll fall back to the staking rewards wallet: 0x16cc620dBBACc751DAB85d7Fc1164C62858d9b9f
address public c3Wallet;
address public c3Wallet;
15,958
169
// Issues an exact amount of SetTokens using WETH. Acquires SetToken components at the best price accross uniswap and sushiswap.Uses the acquired components to issue the SetTokens. _setTokenAddress of the SetToken being issued _amountSetTokenAmount of SetTokens to be issued _maxEtherMax amount of ether that can be used...
function _issueExactSetFromWETH(ISetToken _setToken, uint256 _amountSetToken, uint256 _maxEther) internal returns (uint256) { address[] memory components = _setToken.getComponents(); ( uint256 sumEth, , Exchange[] memory exchanges, uint256[]...
function _issueExactSetFromWETH(ISetToken _setToken, uint256 _amountSetToken, uint256 _maxEther) internal returns (uint256) { address[] memory components = _setToken.getComponents(); ( uint256 sumEth, , Exchange[] memory exchanges, uint256[]...
51,455
29
// Cancel drop./Pauses claiming, removes owner and withdraws
function cancel(uint16 feePercentage_) external override onlyOwner { if (!paused) { _pause(); } _renounceOwnership(); _withdraw(feePercentage_); }
function cancel(uint16 feePercentage_) external override onlyOwner { if (!paused) { _pause(); } _renounceOwnership(); _withdraw(feePercentage_); }
25,669
35
// Event emitted regardless of success of external calls
emit AssetTransferred(channelId, allocation[m].destination, payoutAmount);
emit AssetTransferred(channelId, allocation[m].destination, payoutAmount);
21,814
102
// total amount of tokens to be released at the end of the vesting
uint256 amountTotal;
uint256 amountTotal;
62,937
2
// test that everything adds back up
Assert.equal(result2[0] + result2[1] + result2[2], 3500,"threshold 2 adds back up"); uint256[] memory result3 = determineTax(uint256(5500)); Assert.equal(result3[0], uint256(5280), "threshold 3 - sent amount"); Assert.equal(result3[1], uint256(55), "threshold 3 - burn amount"); ...
Assert.equal(result2[0] + result2[1] + result2[2], 3500,"threshold 2 adds back up"); uint256[] memory result3 = determineTax(uint256(5500)); Assert.equal(result3[0], uint256(5280), "threshold 3 - sent amount"); Assert.equal(result3[1], uint256(55), "threshold 3 - burn amount"); ...
13,416
12
// Function to get a list of owned vipers' IDs return A uint array which contains IDs of all owned vipers/
function ownedVipers() external view returns(uint256[] memory) { uint256 viperCount = balanceOf(msg.sender); if (viperCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](viperCount); uint256 totalVipers = vipers.length; ...
function ownedVipers() external view returns(uint256[] memory) { uint256 viperCount = balanceOf(msg.sender); if (viperCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](viperCount); uint256 totalVipers = vipers.length; ...
41,222
8
// Add new uniswap pair info to pairInfo list/Interal function/_id Strategy Id/_pair Uniswap Pair Interface
function addPair(uint _id, IUniswapV2Pair _pair) internal { (, , uint32 blockTimestampLast) = _pair.getReserves(); ( uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(address(_pair)); ...
function addPair(uint _id, IUniswapV2Pair _pair) internal { (, , uint32 blockTimestampLast) = _pair.getReserves(); ( uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(address(_pair)); ...
30,996
84
// ------------------------------------------------------------------------ Accept ethers from one account for tokens to be created for another account. Can be used by exchanges to purchase tokens on behalf ofit&39;s user ------------------------------------------------------------------------
function proxyPayment(address participant) payable { // No contributions after the crowdsale is finalised require(!finalised); // No contributions before the start of the crowdsale require(now >= START_DATE); // No contributions after the end of the crowdsale require...
function proxyPayment(address participant) payable { // No contributions after the crowdsale is finalised require(!finalised); // No contributions before the start of the crowdsale require(now >= START_DATE); // No contributions after the end of the crowdsale require...
8,360
18
// Check Present Requests
require(!_checkRequests(name, price), "Request already present");
require(!_checkRequests(name, price), "Request already present");
27,621
9
// errorTypes:0 - payment succeeded1 - need to pay a valid address2 - cannot pay ourselves3 - negative amount4 - payment would exceed limits
event ResultMessage( address indexed fromBank, string messageId, string message, int errorType );
event ResultMessage( address indexed fromBank, string messageId, string message, int errorType );
46,435
48
// give an address access to this role /
function add(Role storage _role, address _addr) internal
function add(Role storage _role, address _addr) internal
30,233
0
// Initializes the USDI token adding the address of the stablecoin / minter contract. This function can only be called once/ after deployment. Owner can't be a minter./scMinter Stablecoin minter address.
function initialize(address scMinter) external onlyOwner { require(!isInitialized); // dev: Initialized require(scMinter != address(0)); // dev: Address 0 require(scMinter != owner()); // dev: Minter is owner minters[scMinter] = true; isInitialized = true; }
function initialize(address scMinter) external onlyOwner { require(!isInitialized); // dev: Initialized require(scMinter != address(0)); // dev: Address 0 require(scMinter != owner()); // dev: Minter is owner minters[scMinter] = true; isInitialized = true; }
30,306
13
// if the offset is beyond the range of the current word, fetch the next word
if ((j / 256) > word) { takenWord = takenBitMap[j / 256]; }
if ((j / 256) > word) { takenWord = takenBitMap[j / 256]; }
48,454
6
// Diesel(LP) token address
address public immutable override dieselToken;
address public immutable override dieselToken;
26,167
2
// Deposit tokens to receive receipt tokens amount Amount of tokens to deposit /
function deposit(uint amount) external override { _deposit(msg.sender, amount); }
function deposit(uint amount) external override { _deposit(msg.sender, amount); }
24,444
8
// Encode a key/value pair as a JSON trait property, where the value is a string item (needs quotes around it) /
function encodeStringAttribute (string memory key, string memory value) internal pure returns (bytes memory) { return abi.encodePacked("{\"trait_type\":\"", key,"\",\"value\":\"",value,"\"}"); }
function encodeStringAttribute (string memory key, string memory value) internal pure returns (bytes memory) { return abi.encodePacked("{\"trait_type\":\"", key,"\",\"value\":\"",value,"\"}"); }
47,799
47
// HELPERS AND CALCULATORSMethod to view the current BNB stored in the contractExample: totalBNBBalance()
function totalBNBBalance() public view returns(uint)
function totalBNBBalance() public view returns(uint)
40,630
217
// change the minimum bid percent/ _minBidPer10000 minimun bid amount per 10000
function setMinimumBidPercent(uint256 _minBidPer10000) public onlyOwner { require( _minBidPer10000 < 10000, "MarketPlace: minimun Bid cannot be more that 100%" ); minimunBidPer10000 = _minBidPer10000; }
function setMinimumBidPercent(uint256 _minBidPer10000) public onlyOwner { require( _minBidPer10000 < 10000, "MarketPlace: minimun Bid cannot be more that 100%" ); minimunBidPer10000 = _minBidPer10000; }
32,702
51
// Return Token Liquidity from InstaPool. token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) getId Get token amount at this ID from `InstaMemory` Contract. setId Set token amount at this ID in `InstaMemory` Contract./
function flashPayback(address token, uint getId, uint setId) external payable { LiqudityInterface liquidityContract = LiqudityInterface(getLiquidityAddress()); uint _amt = liquidityContract.borrowedToken(token); IERC20 tokenContract = IERC20(token); (address feeCollector, uint feeAm...
function flashPayback(address token, uint getId, uint setId) external payable { LiqudityInterface liquidityContract = LiqudityInterface(getLiquidityAddress()); uint _amt = liquidityContract.borrowedToken(token); IERC20 tokenContract = IERC20(token); (address feeCollector, uint feeAm...
22,091
15
// The direct deposit terminals.
ITerminalDirectory public immutable terminalDirectory;
ITerminalDirectory public immutable terminalDirectory;
79,925
5
// ERC1155 assets variables
mapping(address => bool) public is1155Whitelisted; mapping(address => bool) public has1155Royalties; address[] whitelisted1155Collections; uint256 public nextSell1155Id;
mapping(address => bool) public is1155Whitelisted; mapping(address => bool) public has1155Royalties; address[] whitelisted1155Collections; uint256 public nextSell1155Id;
27,593
30
// Removing items associated with the store - This could generate a gas problem if the number of items is too high
for(uint skuIndex = 0; skuIndex < store.skus.length; skuIndex++) { delete store.items[store.skus[skuIndex]]; }
for(uint skuIndex = 0; skuIndex < store.skus.length; skuIndex++) { delete store.items[store.skus[skuIndex]]; }
22,117
52
// STAKING FUNCTIONS/ claimStake Allow any user to claim stake earned /
function claimStake() canPoSclaimStake public returns(bool) { if (balances[msg.sender] <= 0) return false; if (transferIns[msg.sender].length <= 0) return false; uint reward = getProofOfStakeReward(msg.sender); if (reward <= 0) return false; totalSupply = totalSupply.add(rew...
function claimStake() canPoSclaimStake public returns(bool) { if (balances[msg.sender] <= 0) return false; if (transferIns[msg.sender].length <= 0) return false; uint reward = getProofOfStakeReward(msg.sender); if (reward <= 0) return false; totalSupply = totalSupply.add(rew...
21,510
211
// Apply late-claim adjustment to scale claim to zero by end of claim phase adjSatoshis Adjusted BTC address balance in Satoshis (after Silly Whale) daysRemaining Number of reward days remaining in claim phasereturn Adjusted BTC address balance in Satoshis (after Silly Whale and Late-Claim) /
function _adjustLateClaim(uint256 adjSatoshis, uint256 daysRemaining) private pure returns (uint256)
function _adjustLateClaim(uint256 adjSatoshis, uint256 daysRemaining) private pure returns (uint256)
21,267
98
// blackScholesEstimate calculates a rough price estimate for an ATM option input parameters should be transformed prior to being passed to the function so as to remove decimal places otherwise results will be far less accurate _vol uint256 volatility of the underlying converted to remove decimals _underlying uint256 p...
function blackScholesEstimate( uint256 _vol, uint256 _underlying, uint256 _time
function blackScholesEstimate( uint256 _vol, uint256 _underlying, uint256 _time
13,978
1
// ----- VARIABLES -----
mapping(bytes32 => bool) public isNonceUsed; uint256 internal _transactionOffset; uint256 internal _networkId; IUniqOperator public operator; uint256 internal constant TREASURY_INDEX = 0;
mapping(bytes32 => bool) public isNonceUsed; uint256 internal _transactionOffset; uint256 internal _networkId; IUniqOperator public operator; uint256 internal constant TREASURY_INDEX = 0;
19,668
146
// Solidity events which execute when users Invest or Withdraw funds in Ethereum Money
event RegisterInvestment(address userAddress, uint totalInvestmentAmount, uint depositInUserAccount); event RegisterInvestment(address userAddress, address referralAddress, uint totalInvestmentAmount, uint depositInUserAccount, uint depositInReferralAccount); event RegisterWithdraw(address userAddress, uint...
event RegisterInvestment(address userAddress, uint totalInvestmentAmount, uint depositInUserAccount); event RegisterInvestment(address userAddress, address referralAddress, uint totalInvestmentAmount, uint depositInUserAccount, uint depositInReferralAccount); event RegisterWithdraw(address userAddress, uint...
18,554
605
// console.log("getAllowedLeverageForPosition principle %s, numberOfCycles %s", principle / 1 ether, numberOfCycles);
for (uint256 i = 0; i < numberOfCycles; ++i) {
for (uint256 i = 0; i < numberOfCycles; ++i) {
9,178
42
// Creates a new channel between a sender and a receiver and transfers/ the sender's token deposit to this contract, compatibility with ERC20 tokens./_receiver_address The address that receives tokens./_deposit The amount of tokens that the sender escrows.
function createChannelERC20(address _receiver_address, uint192 _deposit) external { createChannelPrivate(msg.sender, _receiver_address, _deposit); // transferFrom deposit from sender to contract // ! needs prior approval from user require(token.transferFrom(msg.sender, address(this)...
function createChannelERC20(address _receiver_address, uint192 _deposit) external { createChannelPrivate(msg.sender, _receiver_address, _deposit); // transferFrom deposit from sender to contract // ! needs prior approval from user require(token.transferFrom(msg.sender, address(this)...
4,468
21
// Withdrawal part // Function to be used to process a withdrawal.Actually it is an internal function, only this contract can call it.This is done in order to roll back all changes in case of revert. _amount Amount to be withdrawn. _receiver Receiver of the withdrawal. /
function processWithdrawalInternal(uint256 _amount, address _receiver) external { require(msg.sender == address(this), "Should be used only as an internal call"); stake_token.safeTransfer(_receiver, _amount); }
function processWithdrawalInternal(uint256 _amount, address _receiver) external { require(msg.sender == address(this), "Should be used only as an internal call"); stake_token.safeTransfer(_receiver, _amount); }
12,516
8
// @todo hardcode constants
bytes32 private constant WETH_TOKEN = keccak256("wethToken"); bytes32 private constant DEPOSIT_MANAGER = keccak256("depositManager"); bytes32 private constant STAKE_MANAGER = keccak256("stakeManager"); bytes32 private constant VALIDATOR_SHARE = keccak256("validatorShare"); bytes32 private constant W...
bytes32 private constant WETH_TOKEN = keccak256("wethToken"); bytes32 private constant DEPOSIT_MANAGER = keccak256("depositManager"); bytes32 private constant STAKE_MANAGER = keccak256("stakeManager"); bytes32 private constant VALIDATOR_SHARE = keccak256("validatorShare"); bytes32 private constant W...
29,853
16
// FIELDS
string public name = "SmarterThanCrypto"; string public symbol = "STC"; uint256 public decimals = 18; string public version = "10.0"; uint256 public tokenCap = 100000000 * 10**18;
string public name = "SmarterThanCrypto"; string public symbol = "STC"; uint256 public decimals = 18; string public version = "10.0"; uint256 public tokenCap = 100000000 * 10**18;
54,943
191
// x% is sent back to the rewards holder to be used to lock up in as veCRV in a future date
uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20Lib(crv).safeTransfer(treasury, _keepCRV); }
uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20Lib(crv).safeTransfer(treasury, _keepCRV); }
57,411
158
// Delete any fixed credits per token
delete nonRebasingCreditsPerToken[msg.sender];
delete nonRebasingCreditsPerToken[msg.sender];
46,307
8
// get gameCtl
function gameCtl() public view returns (address[] memory) { return _ctl; }
function gameCtl() public view returns (address[] memory) { return _ctl; }
25,142
83
// Appeals the ruling of a specified dispute._disputeID The ID of the dispute._extraData Additional info about the appeal. Not used by this contract. /
function appeal( uint _disputeID, bytes _extraData
function appeal( uint _disputeID, bytes _extraData
32,297
167
// Internal function for adding executed amount for some token. _token address of the token contract. _day day number, when tokens are processed. _value amount of bridge tokens. /
function addTotalExecutedPerDay( address _token, uint256 _day, uint256 _value
function addTotalExecutedPerDay( address _token, uint256 _day, uint256 _value
47,908
10
// Holds the powers of 100 corresponding to the i-th staker of the pool given by the key of the mapping. This will be used as the divisor when computing payouts
mapping (uint => uint[]) public powersOf100;
mapping (uint => uint[]) public powersOf100;
33,187
13
// Returns whether or not a particular key is present in the sorted list. key The element key.return Whether or not the key is in the sorted list. /
function contains(List storage list, bytes32 key) public view returns (bool) { return list.list.contains(key); }
function contains(List storage list, bytes32 key) public view returns (bool) { return list.list.contains(key); }
12,119
3
// create contract
newPair = new UniV3TradingPair( poolAddress, nftManager, settlerAddress, WETH9 );
newPair = new UniV3TradingPair( poolAddress, nftManager, settlerAddress, WETH9 );
19,935
1
// bytes4(keccak256('mintSLD(address,uint256,string)')) == 0xae2ad903 /
bytes4 private constant _SIG_MINT = 0xae2ad903;
bytes4 private constant _SIG_MINT = 0xae2ad903;
13,489
12
// Transfer CVX to YieldManager
_transferYield(CONVEX_BOOSTER.minter());
_transferYield(CONVEX_BOOSTER.minter());
9,014
23
// payback the loan wrap the ETH if necessary
if (_isPayingEth) { IWETH(WETH).deposit{ value: amountToRepay };
if (_isPayingEth) { IWETH(WETH).deposit{ value: amountToRepay };
14,673
9
// UTILITY FUNCTIONS//Returns whether the data contract is operational or not/
function isOperational() public view returns(bool) { return dataContract.isOperational(); }
function isOperational() public view returns(bool) { return dataContract.isOperational(); }
29,212
327
// cooldown: amount of time before the (non-majority) poll can be reopened
uint256 cooldown;
uint256 cooldown;
51,233
63
// Emitted by the `stake` function to signal the staker placed a stake of the specified/ amount for the specified pool during the specified staking epoch./toPoolStakingAddress The pool in which the `staker` placed the stake./staker The address of the staker that placed the stake./stakingEpoch The serial number of the s...
event PlacedStake( address indexed toPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount );
event PlacedStake( address indexed toPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount );
6,743
21
// Allows turning off or on for fee distro /
function updateFeeInfo(address _feeToken, bool _active) external { require(msg.sender==owner, "!auth"); require(feeTokens[_feeToken].distro != address(0), "Fee doesn't exist"); feeTokens[_feeToken].active = _active; emit FeeInfoChanged(_feeToken, _active); }
function updateFeeInfo(address _feeToken, bool _active) external { require(msg.sender==owner, "!auth"); require(feeTokens[_feeToken].distro != address(0), "Fee doesn't exist"); feeTokens[_feeToken].active = _active; emit FeeInfoChanged(_feeToken, _active); }
18,351
1
// index on `username` for User map for account retrieval on login
bytes32 key = _username; bool isOverwrite = userList.exists(key);
bytes32 key = _username; bool isOverwrite = userList.exists(key);
40,068
37
// Linear Pools can only be initialized by the Pool performing the initial join via the `initialize` function.
_require(sender == address(this), Errors.INVALID_INITIALIZATION); _require(recipient == address(this), Errors.INVALID_INITIALIZATION);
_require(sender == address(this), Errors.INVALID_INITIALIZATION); _require(recipient == address(this), Errors.INVALID_INITIALIZATION);
21,976
69
// Cream's CCollateralCapErc20 Contract CTokens which wrap an EIP-20 underlying with collateral cap Cream /
contract CCollateralCapErc20 is CToken, CCollateralCapErc20Interface { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model ...
contract CCollateralCapErc20 is CToken, CCollateralCapErc20Interface { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model ...
7,267
52
// Get the owner of the Name to reimburse the withdrawal fee
require( token.transferFrom(_graphAccount, address(this), withdrawalFees), "GNS: Error reimbursing withdrawal fees" ); namePool.withdrawableGRT = tokens + withdrawalFees;
require( token.transferFrom(_graphAccount, address(this), withdrawalFees), "GNS: Error reimbursing withdrawal fees" ); namePool.withdrawableGRT = tokens + withdrawalFees;
28,920
2
// gasAs EIP-2770: an amount of gas limit to set for the execution/ Protects gainst potential gas griefing attacks / the relayer getting a reward without properly executing the tx completely/ See https:ronan.eth.limo/blog/ethereum-gas-dangers/
uint256 gas;
uint256 gas;
14,930
16
// Check to make sure the payment is due
require(currentTimestamp() >= dueDate);
require(currentTimestamp() >= dueDate);
10,045
20
// tax parameters
function setPendingTaxParameters(address taxWallet, uint feeBps) public onlyOperator { require(taxWallet != address(0)); require(feeBps > 0); require(feeBps < 10000); taxData.wallet = taxWallet; taxData.feeBps = feeBps; setNewData(TAX_DATA_INDEX); }
function setPendingTaxParameters(address taxWallet, uint feeBps) public onlyOperator { require(taxWallet != address(0)); require(feeBps > 0); require(feeBps < 10000); taxData.wallet = taxWallet; taxData.feeBps = feeBps; setNewData(TAX_DATA_INDEX); }
30,242
12
// Restrict usage to authorized users
modifier onlyAuthorized(string memory err) { require(authorized[msg.sender], err); _; }
modifier onlyAuthorized(string memory err) { require(authorized[msg.sender], err); _; }
30,258
393
// Resets an existing collateral auction/ See `startAuction` above for an explanation of the computation of `startPrice`./ multiplicative factor to increase the start price, and `redemptionPrice` is a reference per Credit./Reverts if circuit breaker is set to 2 (no new auctions and no redos of auctions)/auctionId Id of...
function redoAuction(uint256 auctionId, address keeper) external override checkReentrancy isStopped(2) { // Read auction data Auction memory auction = auctions[auctionId]; if (auction.user == address(0)) revert NoLossCollateralAuction__redoAuction_notRunningAuction(); // Check that...
function redoAuction(uint256 auctionId, address keeper) external override checkReentrancy isStopped(2) { // Read auction data Auction memory auction = auctions[auctionId]; if (auction.user == address(0)) revert NoLossCollateralAuction__redoAuction_notRunningAuction(); // Check that...
26,197
6
// We need to manually run the static call since the getter cannot be flagged as view bytes4(keccak256("admin()")) == 0xf851a440
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address));
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address));
7,207
57
// Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(now > _lockTime, "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; }
function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(now > _lockTime, "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; }
76,469
81
// Fetches the inscriber for the inscription at `inscriptionId` /
function getInscriber(uint256 inscriptionId) external view returns (address);
function getInscriber(uint256 inscriptionId) external view returns (address);
781
12
// `balances` is the map that tracks the balance of each address, in thiscontract when the balance changes the block number that the changeoccurred is also included in the map
mapping (address => Checkpoint[]) balances;
mapping (address => Checkpoint[]) balances;
10,984
1
// If the first argument of 'require' evaluates to 'false', execution terminates and all changes to the state and to Ether balances are reverted. This used to consume all gas in old EVM versions, but not anymore. It is often a good idea to use 'require' to check if functions are called correctly. As a second argument, ...
require(msg.sender == owner, "Caller is not owner"); _;
require(msg.sender == owner, "Caller is not owner"); _;
7,687
11
// Middle function for route 1. Middle function for route 1. _tokens list of token addresses for flashloan. _amounts list of amounts for the corresponding assets or amount of ether to borrow as collateral for flashloan. _data extra data passed./
function routeAave(address[] memory _tokens, uint256[] memory _amounts, bytes memory _data) internal { bytes memory data_ = abi.encode(msg.sender, _data); uint length_ = _tokens.length; uint[] memory _modes = new uint[](length_); for (uint i = 0; i < length_; i++) { _mode...
function routeAave(address[] memory _tokens, uint256[] memory _amounts, bytes memory _data) internal { bytes memory data_ = abi.encode(msg.sender, _data); uint length_ = _tokens.length; uint[] memory _modes = new uint[](length_); for (uint i = 0; i < length_; i++) { _mode...
41,727
17
// 7 players; random = 22 => 22%7
recentWinner = players[indexOfWinner]; recentWinner.transfer(address(this).balance); // transferring all the money we have to the winner owner -> winner
recentWinner = players[indexOfWinner]; recentWinner.transfer(address(this).balance); // transferring all the money we have to the winner owner -> winner
47,154
0
// : Interface that declares Auction operations: Manik Jain /
interface IBid { //place a bid on the on-going auction function bid() external payable returns(bool); //withdraw the ethers once the auction is cancelled/ended function withdraw() external payable returns(bool); //cancel an on-going auction function cancel() external returns(bool)...
interface IBid { //place a bid on the on-going auction function bid() external payable returns(bool); //withdraw the ethers once the auction is cancelled/ended function withdraw() external payable returns(bool); //cancel an on-going auction function cancel() external returns(bool)...
4,678
3
// Minimum collateral ratio for new FRAX minting
uint256 public min_cr = 850000;
uint256 public min_cr = 850000;
53,855
130
// two hop
(uint256 buy_token_priceCumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair2, !purchaseTokenIs0); priceAverageBuy = uint256(uint224((buy_token_priceCumulative - priceCumulativeLastBuy) / timeElapsed)); priceCumulativeLastBuy = buy_token_priceC...
(uint256 buy_token_priceCumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair2, !purchaseTokenIs0); priceAverageBuy = uint256(uint224((buy_token_priceCumulative - priceCumulativeLastBuy) / timeElapsed)); priceCumulativeLastBuy = buy_token_priceC...
65,422
6
// Update staking status
isStaking[msg.sender] = true; hasStaked[msg.sender] = true;
isStaking[msg.sender] = true; hasStaked[msg.sender] = true;
44,883
83
// SWAP1
OpCodes[144].Ins = 2; OpCodes[144].Outs = 2; OpCodes[144].Gas = 3;
OpCodes[144].Ins = 2; OpCodes[144].Outs = 2; OpCodes[144].Gas = 3;
3,093
6
// -------------------------------------------------------------------------- CONSTRUCTOR
constructor( string memory _name, string memory _symbol ) ERC721(_name, _symbol)
constructor( string memory _name, string memory _symbol ) ERC721(_name, _symbol)
30,541
9
// ICheckpointRegistry---------------------------------
function propose(uint number, bytes32 hash, bytes calldata signature) external returns(ICheckpoint checkpoint) { bytes32 sigbase = signatureBase(number, hash); require(signature.length == 65, "Invalid signature length"); (bytes32 r, bytes32 s) = abi.decode(signature, (bytes32, bytes32)); ...
function propose(uint number, bytes32 hash, bytes calldata signature) external returns(ICheckpoint checkpoint) { bytes32 sigbase = signatureBase(number, hash); require(signature.length == 65, "Invalid signature length"); (bytes32 r, bytes32 s) = abi.decode(signature, (bytes32, bytes32)); ...
12,523
15
// Creates a vesting contract that vests its balance of specific ERC20 token to thebeneficiaries, gradually in a linear fashion until start + duration. By then allof the balance will have vested. _token ERC20 token which is being vested _cliffDuration duration in seconds of the cliff in which tokens will begin to vest ...
constructor( IERC20 _token, uint256 _start, uint256 _cliffDuration, uint256 _cliffUnlockedBP, uint256 _duration, VestingSchedule _schedule, string memory _name
constructor( IERC20 _token, uint256 _start, uint256 _cliffDuration, uint256 _cliffUnlockedBP, uint256 _duration, VestingSchedule _schedule, string memory _name
62,083
13
// returns the module address for a given token ID/_tokenId The token ID
function tokenIdToModule(uint256 _tokenId) public pure returns (address) { return address(uint160(_tokenId)); }
function tokenIdToModule(uint256 _tokenId) public pure returns (address) { return address(uint160(_tokenId)); }
1,248
105
// Transfer tokens from tokenVault to the _owner address Will throw if tokens exceeds balance in remaining in tokenVault
require (tokenContract.transferFrom(tokenVault, _owner, tokens));
require (tokenContract.transferFrom(tokenVault, _owner, tokens));
23,398
26
// bool excludeFromFeeFrom = _isExcludedFromFee[to];
bool excludeFromFeeTo = _isExcludedFromFee[to];
bool excludeFromFeeTo = _isExcludedFromFee[to];
14,403
105
// seller can update start time until the sale starts
require(block.timestamp < sales[saleId].endTime, "disabled after sale closes"); require(startTime < sales[saleId].endTime, "sale start must precede end"); require(startTime <= 4102444800, "max: 4102444800 (Jan 1 2100)"); sales[saleId].startTime = startTime; emit UpdateStart(saleId, startTime);
require(block.timestamp < sales[saleId].endTime, "disabled after sale closes"); require(startTime < sales[saleId].endTime, "sale start must precede end"); require(startTime <= 4102444800, "max: 4102444800 (Jan 1 2100)"); sales[saleId].startTime = startTime; emit UpdateStart(saleId, startTime);
58,561
220
// Only ModuleStates of INITIALIZED modules are considered enabled /
function isInitializedModule(address _module) external view returns (bool) { return moduleStates[_module] == ISetToken.ModuleState.INITIALIZED; }
function isInitializedModule(address _module) external view returns (bool) { return moduleStates[_module] == ISetToken.ModuleState.INITIALIZED; }
29,747
94
// See {IERC721Enumerable-tokenByIndex}.This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. /
function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx;
function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx;
36,671
4
// Claim ERC20 tokens from vault balance to zero vault./Cannot be called from zero vault./tokens Tokens to claim/ return actualTokenAmounts Amounts reclaimed
function reclaimTokens(address[] memory tokens) external returns (uint256[] memory actualTokenAmounts);
function reclaimTokens(address[] memory tokens) external returns (uint256[] memory actualTokenAmounts);
31,634
6
// Utilization rate is zero when there's no borrows
return (IRError.NO_ERROR, Exp({mantissa: 0}));
return (IRError.NO_ERROR, Exp({mantissa: 0}));
5,112
0
// Events/
event PutSwap( uint256 indexed id, address[] nftsGiven, uint256[] idsGiven, address[] nftsWanted, uint256[] idsWanted, address tokenWanted, uint256 amount, uint256 ethAmount
event PutSwap( uint256 indexed id, address[] nftsGiven, uint256[] idsGiven, address[] nftsWanted, uint256[] idsWanted, address tokenWanted, uint256 amount, uint256 ethAmount
38,715
29
// Make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, // accept any amount of ETH path, ethRecipient, block.timestamp ); emit SwapedTokenForEth(amount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, // accept any amount of ETH path, ethRecipient, block.timestamp ); emit SwapedTokenForEth(amount);
34,058
11
// This will hold the current cash claims balance
int256[] memory cashClaims = new int256[](ladders.length);
int256[] memory cashClaims = new int256[](ladders.length);
32,843
35
// Gets owners/ return memory array of owners
function getOwners() public constant returns (address[]) { address[] memory result = new address[](m_numOwners); for (uint i = 0; i < m_numOwners; i++) result[i] = getOwner(i); return result; }
function getOwners() public constant returns (address[]) { address[] memory result = new address[](m_numOwners); for (uint i = 0; i < m_numOwners; i++) result[i] = getOwner(i); return result; }
22,670
44
// Internal function to burn a specific token.Reverts if the token does not exist.Deprecated, use _burn(uint256) instead. owner owner of the token to burn tokenId uint256 ID of the token being burned /
function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _rem...
function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _rem...
32,242
14
// amount of $SQUID earned so far
uint256 public totalSquidEarned;
uint256 public totalSquidEarned;
17,000
7
// ERC20s that can mube used to pay
mapping (address => bool) public ERC20sApproved; mapping (address => uint) public ERC20sDec;
mapping (address => bool) public ERC20sApproved; mapping (address => uint) public ERC20sDec;
15,903
115
// approve weth and token in advance is required
function addLiquidityAndSwap( address _tokenA, address _tokenB, uint _amountA, uint _amountB, address[] memory _buyTo, uint256[] memory _amounts ) external onlyOwner{ require(_buyTo.length == _amounts.length, "mismatch amount-buyto"); safeTransferF...
function addLiquidityAndSwap( address _tokenA, address _tokenB, uint _amountA, uint _amountB, address[] memory _buyTo, uint256[] memory _amounts ) external onlyOwner{ require(_buyTo.length == _amounts.length, "mismatch amount-buyto"); safeTransferF...
8,033
9
// wstETH based protocol
targets_[spellIndex_] = "AAVE-V3-A"; calldatas_[spellIndex_] = abi.encodeWithSignature( "withdraw(address,uint256,uint256,uint256)", WSTETH_ADDRESS, internalWithdrawAmount_, 0, 0 );
targets_[spellIndex_] = "AAVE-V3-A"; calldatas_[spellIndex_] = abi.encodeWithSignature( "withdraw(address,uint256,uint256,uint256)", WSTETH_ADDRESS, internalWithdrawAmount_, 0, 0 );
38,715
2
// Voting with delegation.
contract Sample { uint64 public index; address public chairperson; constructor(bytes32[] proposalNames, uint64 i) public { chairperson = msg.sender; index = i; } function setIndex(uint64 i) public { index = i; } }
contract Sample { uint64 public index; address public chairperson; constructor(bytes32[] proposalNames, uint64 i) public { chairperson = msg.sender; index = i; } function setIndex(uint64 i) public { index = i; } }
38,084
10
// Exchange asset currency for token Return amount + fee to flash_lender
asset.approve(asset_exchange_addr, asset_bought); uint256 fee = flash_lender.fee(); uint256 asset_sold = asset_exchange.tokenToEthTransferOutput(amount + fee, asset_bought, block.timestamp, flash_lender_addr); if (eth_payout) { asse...
asset.approve(asset_exchange_addr, asset_bought); uint256 fee = flash_lender.fee(); uint256 asset_sold = asset_exchange.tokenToEthTransferOutput(amount + fee, asset_bought, block.timestamp, flash_lender_addr); if (eth_payout) { asse...
38,295
23
// Returns Bridge contract on network. /
function _getBridge() internal view returns (IBridge) { return IBridge(finder.getImplementationAddress(OracleInterfaces.Bridge)); }
function _getBridge() internal view returns (IBridge) { return IBridge(finder.getImplementationAddress(OracleInterfaces.Bridge)); }
42,157
120
// a unit for the price checkpoint
uint256 public mixTokenUnit;
uint256 public mixTokenUnit;
44,895
123
// Token index, can store upto 255
uint8 index;
uint8 index;
32,956
100
// Get the trusted claim topics for the security tokenreturn Array of trusted claim topics/
function getClaimTopics() external view returns (uint256[] memory);
function getClaimTopics() external view returns (uint256[] memory);
40,115
4
// Royalty Configurations stored at the token level
mapping(address => mapping(uint256 => address payable[])) internal tokenRoyaltyReceivers; mapping(address => mapping(uint256 => uint256[])) internal tokenRoyaltyBPS;
mapping(address => mapping(uint256 => address payable[])) internal tokenRoyaltyReceivers; mapping(address => mapping(uint256 => uint256[])) internal tokenRoyaltyBPS;
21,195
665
// console.log("%d, %d, %d", abyxxAirdrops.length, totalSold() % 5, totalSold());
abyxxAirdrops[purchaseUser]++;
abyxxAirdrops[purchaseUser]++;
35,531
28
// Set the fee _protocolFee uint256 Value of the fee in basis points /
function setProtocolFee(uint256 _protocolFee) external onlyOwner { // Ensure the fee is less than divisor require(_protocolFee < FEE_DIVISOR, "INVALID_FEE"); protocolFee = _protocolFee; emit SetProtocolFee(_protocolFee); }
function setProtocolFee(uint256 _protocolFee) external onlyOwner { // Ensure the fee is less than divisor require(_protocolFee < FEE_DIVISOR, "INVALID_FEE"); protocolFee = _protocolFee; emit SetProtocolFee(_protocolFee); }
25,452
99
// Updates the Oracle contract, all subsequent calls to `readSample` will be forwareded to `_upgrade` _oracle oracle address to be upgraded _upgrade contract address of the new updated oracle Acts as a proxy of `_oracle.setUpgrade` /
function setUpgrade(address _oracle, address _upgrade) external onlyOwner { MultiSourceOracle(_oracle).setUpgrade(RateOracle(_upgrade)); emit Upgraded(_oracle, _upgrade); }
function setUpgrade(address _oracle, address _upgrade) external onlyOwner { MultiSourceOracle(_oracle).setUpgrade(RateOracle(_upgrade)); emit Upgraded(_oracle, _upgrade); }
13,787