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
28
// Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),Reverts with custom message when dividing by zero. Counterpart to Solidity's `%` operator. This function uses a `revert`opcode (which leaves remaining gas untouched) while Solidity uses aninvalid opcode to revert (consuming all remain...
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; }
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; }
4,846
21
// Given specific MoonCat trait information, assemble the main visual SVG objects to represent a MoonCat with those traits. /
function getPixelData (uint8 facing, uint8 expression, uint8 pose, uint8 pattern, uint8[24] memory colors) public view returns (bytes memory)
function getPixelData (uint8 facing, uint8 expression, uint8 pose, uint8 pattern, uint8[24] memory colors) public view returns (bytes memory)
56,505
126
// mint total supply to deployer
_mint(_msgSender(), _totalSupply);
_mint(_msgSender(), _totalSupply);
33,031
12
// ERC20Basic interface Basic ERC20 interface /
contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); }
contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); }
3,231
45
// The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, it is recommended to avoid using short time durations (less than a minute). Typical vesting schem...
using SafeMath for uint256; event LogReleased(uint256 amount); event LogRevoked(bool releaseSuccessful);
using SafeMath for uint256; event LogReleased(uint256 amount); event LogRevoked(bool releaseSuccessful);
11,335
647
// Add voter tokens to participation
survey.participation = survey.participation.add(totalVoted); assert(survey.participation <= survey.votingPower);
survey.participation = survey.participation.add(totalVoted); assert(survey.participation <= survey.votingPower);
62,840
29
// Returns Voken address of `account`. /
function address2voken( address account ) public view returns (uint160)
function address2voken( address account ) public view returns (uint160)
1,461
28
// Returns day details
function getDay (uint16 dayId) public view onlyValidDay(dayId)
function getDay (uint16 dayId) public view onlyValidDay(dayId)
19,161
2
// Creates and sponsors a financing proposal. Applicant address must not be reserved. Token address must be allowed/supported by the DAO Bank. Requested amount must be greater than zero. Only members of the DAO can sponsor a financing proposal. dao The DAO Address. proposalId The proposal id. applicant The applicant ad...
function submitProposal( DaoRegistry dao, bytes32 proposalId, address applicant, address token, uint256 amount, bytes memory data
function submitProposal( DaoRegistry dao, bytes32 proposalId, address applicant, address token, uint256 amount, bytes memory data
23,878
52
// Function set new wallet address. newWallet Address of new wallet. /
function changeWallet(address payable newWallet) public onlyOwner { require(newWallet != address(0)); wallet = newWallet; }
function changeWallet(address payable newWallet) public onlyOwner { require(newWallet != address(0)); wallet = newWallet; }
600
32
// need temporary storage solidity disallow size changes
uint256[] memory tmp = new uint256[](max); uint256 found; for (uint256 i = 0; i < max; i++) { if (_userInfo[i][user].bonus) { tmp[found] = i; found += 1; }
uint256[] memory tmp = new uint256[](max); uint256 found; for (uint256 i = 0; i < max; i++) { if (_userInfo[i][user].bonus) { tmp[found] = i; found += 1; }
22,347
9
// Send approved tokens to seven addressesdests1 -> address where you want to send tokensdests2 -> address where you want to send tokensdests3 -> address where you want to send tokensdests4 -> address where you want to send tokensdests5 -> address where you want to send tokensdests6 -> address where you want to send to...
function sendTokensTo7(address dests1, address dests2, address dests3, address dests4, address dests5,
function sendTokensTo7(address dests1, address dests2, address dests3, address dests4, address dests5,
57,718
6
// Withdrawable Allow withdrwaing any ERC20 or native tokens from the contract. @custom:type eip-2535-facet@custom:category Finance@custom:provides-interfaces IWithdrawable /
contract Withdrawable is IWithdrawable, WithdrawableInternal { function withdraw(address[] calldata claimTokens, uint256[] calldata amounts) external { _withdraw(claimTokens, amounts); } function withdrawRecipient() external view override returns (address) { return _withdrawRecipient(); ...
contract Withdrawable is IWithdrawable, WithdrawableInternal { function withdraw(address[] calldata claimTokens, uint256[] calldata amounts) external { _withdraw(claimTokens, amounts); } function withdrawRecipient() external view override returns (address) { return _withdrawRecipient(); ...
30,527
24
// DSProxy Allows code execution using a persistant identity This can be very useful to execute a sequence of atomic actions. Since the owner of the proxy can be changed, this allows for dynamic ownership models i.e. a multisig
contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } function() public payable { } // use the proxy to execute calldata _data on contract _code function execute(byte...
contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } function() public payable { } // use the proxy to execute calldata _data on contract _code function execute(byte...
50,027
140
// AMO Minter related
address private amo_minter_address;
address private amo_minter_address;
70,505
174
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team;
uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team;
1,856
222
// ratio of all pair liquidity owned by this contract
function _ratioOwned() internal view returns (Decimal.D256 memory) { uint256 balance = liquidityOwned(); uint256 total = pair.totalSupply(); return Decimal.ratio(balance, total); }
function _ratioOwned() internal view returns (Decimal.D256 memory) { uint256 balance = liquidityOwned(); uint256 total = pair.totalSupply(); return Decimal.ratio(balance, total); }
22,816
38
// Increase the amount of tokens that an owner allowed to a spender. approve should be called when allowed[_spender] == 0. To incrementallowed value is better to use this function to avoid 2 calls (and wait untilthe first transaction is mined)From MonolithDAO Token.sol _spender The address which will spend the funds. _...
function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
1,340
123
// we substract fee amount from recipient amount
amountReceived = amount - feeAmount1 - feeAmount2; if (feeAmount2 > 0) platformFeeAmount += feeAmount2;
amountReceived = amount - feeAmount1 - feeAmount2; if (feeAmount2 > 0) platformFeeAmount += feeAmount2;
29,915
29
// There are scenarios when we want to call _calculateBorrowPosition and act on it. 1. Strategy got some collateral from pool which will allow strategy to borrow more. 2. Collateral and/or borrow token price is changed which leads to repay or borrow. 3. BorrowLimits are updated. In some edge scenarios, below call is re...
(uint256 _borrowAmount, uint256 _repayAmount) = _calculateBorrowPosition( 0, 0, vdToken.balanceOf(address(this)), IERC20(receiptToken).balanceOf(address(this)) ); if (_repayAmount > 0) {
(uint256 _borrowAmount, uint256 _repayAmount) = _calculateBorrowPosition( 0, 0, vdToken.balanceOf(address(this)), IERC20(receiptToken).balanceOf(address(this)) ); if (_repayAmount > 0) {
27,764
9
// Delegate your vote to the voter 'to'. to address to which vote is delegated /
function delegate(address to) public { Voter storage sender = voters[msg.sender]; require(!sender.voted, "You already voted."); require(to != msg.sender, "Self-delegation is disallowed."); while (voters[to].delegate != address(0)) { to = voters[to].delegate; ...
function delegate(address to) public { Voter storage sender = voters[msg.sender]; require(!sender.voted, "You already voted."); require(to != msg.sender, "Self-delegation is disallowed."); while (voters[to].delegate != address(0)) { to = voters[to].delegate; ...
2,175
68
// Instantiate contracts
ERC20 DSHS = ERC20(DSHSContractAddress); ERC20 XCHF = ERC20(XCHFContractAddress);
ERC20 DSHS = ERC20(DSHSContractAddress); ERC20 XCHF = ERC20(XCHFContractAddress);
41,371
48
// This contract only defines a modifier but does not use it: it will be used in derived contracts. The function body is inserted where the special symbol `_;` in the definition of a modifier appears. This means that if the owner calls this function, the function is executed and otherwise, an exception is thrown.
modifier onlyOwner { require( msg.sender == owner, "Only owner can call this function." ); _; }
modifier onlyOwner { require( msg.sender == owner, "Only owner can call this function." ); _; }
3,601
23
// Check if the internal administration is correct. The safeguarded user balances added to the un-retrieved admin commission should be the same as the ETH balance of this contract.return uint256 The total current safeguarded balance of all users 'userBalance' + 'privacyfund'.return uint256 The outstanding admin commiss...
function AuditBalances() external view returns(uint256, uint256) { assert(address(this).balance >= userBalance); uint256 pendingBalance = userBalance.add(privacyFund); uint256 commissions = address(this).balance.sub(pendingBalance); return(pendingBalance, commissions); }...
function AuditBalances() external view returns(uint256, uint256) { assert(address(this).balance >= userBalance); uint256 pendingBalance = userBalance.add(privacyFund); uint256 commissions = address(this).balance.sub(pendingBalance); return(pendingBalance, commissions); }...
60,518
92
//
* See {_mint} * Requires * - msg.sender must be the token owner * */ function mint(address account, uint256 amount) public onlyOwner returns(bool){ _mint(account, amount); return true; }
* See {_mint} * Requires * - msg.sender must be the token owner * */ function mint(address account, uint256 amount) public onlyOwner returns(bool){ _mint(account, amount); return true; }
30,015
3
// (tokenId => (listingId => Listing)) mapping
mapping(uint256 => mapping(uint256 => Listing)) public listings; mapping(uint256 => uint256) public listingCount;
mapping(uint256 => mapping(uint256 => Listing)) public listings; mapping(uint256 => uint256) public listingCount;
37,943
109
// burn sUSD from messageSender (liquidator) and reduce account's debt
_burnSynthsForLiquidation(account, liquidator, amountToLiquidate, debtBalance, totalDebtIssued); if (amountToLiquidate == amountToFixRatio) {
_burnSynthsForLiquidation(account, liquidator, amountToLiquidate, debtBalance, totalDebtIssued); if (amountToLiquidate == amountToFixRatio) {
42,975
91
// Determine whether or not deposit is active or inactive.
if (d.timeDeposited <= lastTimeEnteredStrategy) {
if (d.timeDeposited <= lastTimeEnteredStrategy) {
43,718
32
// replace facet address with last facet address and delete last facet address
uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1; uint256 facetAddressPosition = ds.facetFunctionSelectors[_facetAddress].facetAddressPosition; if (facetAddressPosition != lastFacetAddressPosition) { address lastFacetAddress = ds.facetAddresses[lastFace...
uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1; uint256 facetAddressPosition = ds.facetFunctionSelectors[_facetAddress].facetAddressPosition; if (facetAddressPosition != lastFacetAddressPosition) { address lastFacetAddress = ds.facetAddresses[lastFace...
29,380
5,522
// 2763
entry "tephrochronologically" : ENG_ADVERB
entry "tephrochronologically" : ENG_ADVERB
23,599
34
// Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. /
function transfer(address recipient, uint256 amount) external returns (bool); function mint(address account, uint amount) external;
function transfer(address recipient, uint256 amount) external returns (bool); function mint(address account, uint amount) external;
14,340
196
// 触发拍卖创建事件
AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) );
AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) );
44,094
374
// 188
entry "insinewed" : ENG_ADJECTIVE
entry "insinewed" : ENG_ADJECTIVE
16,800
15
// max cap on a single direct deposit (granularity of 1e9) max possible cap - type(uint32).max1e9 zkBOB units ~= 4.3e9 BOB
uint32 directDepositCap;
uint32 directDepositCap;
12,770
10
// Overwrite the previous allowance.
_allowances[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true;
_allowances[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true;
33,130
13
// ----------------------------------------------------------------------------Basic tokenBasic version of StandardToken, with no allowances. ----------------------------------------------------------------------------
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { req...
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { req...
25,841
330
// round 49
ark(i, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524); sbox_partial(i, q); mix(i, q);
ark(i, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524); sbox_partial(i, q); mix(i, q);
19,763
20
// calculate the withdrawal root
bytes32 withdrawalRoot = calculateWithdrawalRoot(queuedWithdrawal);
bytes32 withdrawalRoot = calculateWithdrawalRoot(queuedWithdrawal);
3,905
53
// is the account in Limbo?
if (account == address(0)) return false; return _limboState[account];
if (account == address(0)) return false; return _limboState[account];
29,001
191
// It allows owner to modify allAvailableTokens array in case of emergency ie if a bug on a interest bearing token is discovered and reset protocolWrappers associated with those tokens.protocolTokens : array of protocolTokens addresses (eg [cDAI, ...])wrappers : array of wrapper addresses (eg [AFICompound, ...])allocat...
function setAllAvailableTokensAndWrappers( address[] calldata protocolTokens, address[] calldata wrappers, uint256[] calldata allocations, bool keepAllocations
function setAllAvailableTokensAndWrappers( address[] calldata protocolTokens, address[] calldata wrappers, uint256[] calldata allocations, bool keepAllocations
10,443
118
// Deploys a new proxy instance that DELEGATECALLs this contract Must be called on the implementation (reverts if a proxy is called) /
function createProxy() external returns (address proxy) { _throwProxy(); // CREATE an EIP-1167 proxy instance with the target being this contract bytes20 target = bytes20(address(this)); assembly { let initCode := mload(0x40) mstore( initCode,...
function createProxy() external returns (address proxy) { _throwProxy(); // CREATE an EIP-1167 proxy instance with the target being this contract bytes20 target = bytes20(address(this)); assembly { let initCode := mload(0x40) mstore( initCode,...
16,768
65
// Callable by admin to ensure LIQUIDATION_TIME_PERIOD won't elapse /
function certifyAdmin() public onlyOwnerOrManager { _updateAdminActiveTimestamp(); }
function certifyAdmin() public onlyOwnerOrManager { _updateAdminActiveTimestamp(); }
35,603
16
// Send payback that's too low - this shouldn't accept our tokens and should not advance the state.
uint256 beforePayback = loanToken.balanceOf(borrower); borrower.approveLoan(this, 1337); l.paybackProcess(borrower); Assert.equal(uint(l.state), uint(InvestorLedger.State.Payback), "Ledger should be in Payback"); Assert.equal(loanToken.balanceOf(borrower), beforePayback, "Payback...
uint256 beforePayback = loanToken.balanceOf(borrower); borrower.approveLoan(this, 1337); l.paybackProcess(borrower); Assert.equal(uint(l.state), uint(InvestorLedger.State.Payback), "Ledger should be in Payback"); Assert.equal(loanToken.balanceOf(borrower), beforePayback, "Payback...
47,505
252
// Cancel an open order in the orderbook. An order can be cancelled/ by the trader who opened the order, or by the broker verifier contract./ This allows the settlement layer to implement their own logic for/ cancelling orders without trader interaction (e.g. to ban a trader from/ a specific darkpool, or to use multipl...
function cancelOrder(bytes32 _orderID) external { require(orders[_orderID].state == OrderState.Open, "invalid order state"); // Require the msg.sender to be the trader or the broker verifier address brokerVerifier = address(settlementRegistry.brokerVerifierContract(orders[_orderID].settleme...
function cancelOrder(bytes32 _orderID) external { require(orders[_orderID].state == OrderState.Open, "invalid order state"); // Require the msg.sender to be the trader or the broker verifier address brokerVerifier = address(settlementRegistry.brokerVerifierContract(orders[_orderID].settleme...
33,880
18
// https:docs.synthetix.io/contracts/source/contracts/stakingrewards
contract StakingRewards is ReentrancyGuard, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 public rewardsToken; IERC20 public stakingToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 publ...
contract StakingRewards is ReentrancyGuard, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 public rewardsToken; IERC20 public stakingToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 publ...
828
314
// Checks if id is registered
getIdAddress(_ids[i]);
getIdAddress(_ids[i]);
9,763
199
// we need to move to last position
uint16 tmp = _cpTop_Indices[_cpTop_SelectionList[i]][ii]; _cpTop_Indices[_cpTop_SelectionList[i]][ii] = _cpTop_Indices[_cpTop_SelectionList[i]][_cpTop_IndiccesLeft[_cpTop_SelectionList[i]]-1]; _cpTop_Indices[_cpTop_SelectionList[i]][_cpTop_IndiccesLeft[_cpTop_SelectionList[i]]-1] = tmp; _cpTop_IndiccesL...
uint16 tmp = _cpTop_Indices[_cpTop_SelectionList[i]][ii]; _cpTop_Indices[_cpTop_SelectionList[i]][ii] = _cpTop_Indices[_cpTop_SelectionList[i]][_cpTop_IndiccesLeft[_cpTop_SelectionList[i]]-1]; _cpTop_Indices[_cpTop_SelectionList[i]][_cpTop_IndiccesLeft[_cpTop_SelectionList[i]]-1] = tmp; _cpTop_IndiccesL...
15,535
44
// GamePlayerCoin token contract. Implements /
contract GamePlayerCoin is StandardToken, Ownable { string public constant name = "GamePlayerCoin"; string public constant symbol = "GPC"; uint public constant decimals = 18; // Constructor function GamePlayerCoin() { totalSupply = 100 * (10**6) * (10 ** decimals); // 100 million balances[msg.sen...
contract GamePlayerCoin is StandardToken, Ownable { string public constant name = "GamePlayerCoin"; string public constant symbol = "GPC"; uint public constant decimals = 18; // Constructor function GamePlayerCoin() { totalSupply = 100 * (10**6) * (10 ** decimals); // 100 million balances[msg.sen...
32,122
30
// No time delay revoke minter emergency function
function revokeMinter(address _auth) external onlyVault { isMinter[_auth] = false; }
function revokeMinter(address _auth) external onlyVault { isMinter[_auth] = false; }
27,543
64
// Returns the name of the token. /
event removeLiquidityETHSupportingFeeOnTransferTokens(
event removeLiquidityETHSupportingFeeOnTransferTokens(
28,966
119
// 接受nft 避免没有实现转账功能
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; }
14,233
19
// Set the lock state of the market Only the market admin can access this function _lock Flag for locking the market _allowPurchase Flag for allowing purchases while locked /
function adminSetLock(bool _lock, bool _allowPurchase) public onlyAdmin
function adminSetLock(bool _lock, bool _allowPurchase) public onlyAdmin
50,523
33
// Get reward token per block /
function getRewardTokenPerBlock() public view returns (uint256) { return rewardTokensPerBlock; }
function getRewardTokenPerBlock() public view returns (uint256) { return rewardTokensPerBlock; }
20,133
83
// update max limit. This happens before checks, to ensure maxSacrificable is correctly calculated.
if ((block.timestamp - lastUpdatedTimestamp) > SECONDS_IN_DAY) { globalDoublingIndex *= 2; lastUpdatedTimestamp += SECONDS_IN_DAY; }
if ((block.timestamp - lastUpdatedTimestamp) > SECONDS_IN_DAY) { globalDoublingIndex *= 2; lastUpdatedTimestamp += SECONDS_IN_DAY; }
78,988
37
// Function to set minimum require approval variable value. _value uint The value by which minRequiredApprovals variable will be set.return true. /
function setMinApprovalCounts(uint _value) public isController returns (bool){ require(_value > 0); minRequiredApprovals = _value; return true; }
function setMinApprovalCounts(uint _value) public isController returns (bool){ require(_value > 0); minRequiredApprovals = _value; return true; }
3,667
127
// overflow checked above
collateralToWithdraw = collateralToWithdraw - cashClaim;
collateralToWithdraw = collateralToWithdraw - cashClaim;
10,723
13
// Event emitted when the public sale begins. /
event SaleBegins(); bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; uint256 public constant TOKEN_LIMIT = 15000; mapping(bytes4 => bool) internal supportedInterfaces; mapping(uint256 => address) internal idToOwner;
event SaleBegins(); bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; uint256 public constant TOKEN_LIMIT = 15000; mapping(bytes4 => bool) internal supportedInterfaces; mapping(uint256 => address) internal idToOwner;
5,252
111
// function initialiseBalances(uint256) // `selectTemplate` Select a proposed template for the issuance _templateIndex Array index of the delegates proposed templatereturn bool success /
function selectTemplate(uint8 _templateIndex) public onlyOwner returns (bool success) { require(!isSTOProposed); address _template = PolyCompliance.getTemplateByProposal(this, _templateIndex); require(_template != address(0)); Template = ITemplate(_template); var (_fee, _quor...
function selectTemplate(uint8 _templateIndex) public onlyOwner returns (bool success) { require(!isSTOProposed); address _template = PolyCompliance.getTemplateByProposal(this, _templateIndex); require(_template != address(0)); Template = ITemplate(_template); var (_fee, _quor...
3,556
48
// Read the gas and the ETH prices
uint256 gasPrice = gasPriceOracle.read(); uint256 ethPrice = ethPriceOracle.read();
uint256 gasPrice = gasPriceOracle.read(); uint256 ethPrice = ethPriceOracle.read();
11,366
311
// borrow the amount we want
ironBankToken.borrow(amount);
ironBankToken.borrow(amount);
10,766
10
// If the function selector has not been overwritten, it is an out-of-gas error.
if eq(shr(224, mload(0x00)), functionSelector) {
if eq(shr(224, mload(0x00)), functionSelector) {
7,891
59
// Vaidates the purchaseCheck if the _participant address is not null and the weiAmount is not zero
validatePurchase(_participant, _weiAmount); uint currentLevelTokens; uint nextLevelTokens;
validatePurchase(_participant, _weiAmount); uint currentLevelTokens; uint nextLevelTokens;
5,573
160
// Function to mint tokens. to The address that will receive the minted tokens. tokenId The token id to mint. tokenURI The token URI of the minted token.return A boolean that indicates if the operation was successful. /
function mintWithTokenURI(address to, uint256 tokenId, string memory tokenURI) public onlyMinter returns (bool) { _mint(to, tokenId); _setTokenURI(tokenId, tokenURI); return true; }
function mintWithTokenURI(address to, uint256 tokenId, string memory tokenURI) public onlyMinter returns (bool) { _mint(to, tokenId); _setTokenURI(tokenId, tokenURI); return true; }
17,296
44
// allowance[_from][msg.sender] -= _value;Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true;
totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true;
68,208
34
// Is the base negative and the exponent an odd number?
bool isNegative = x < 0 && y & 1 == 1; result = isNegative ? -int256(absResult) : int256(absResult);
bool isNegative = x < 0 && y & 1 == 1; result = isNegative ? -int256(absResult) : int256(absResult);
27,861
84
// This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For anexplanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}./ Returns the current implementation of `proxy`.Requirements:- This contract must be the admin of `proxy`. /
function getProxyImplementation(TransparentUpgradeableProxy proxy) public view returns (address) {
function getProxyImplementation(TransparentUpgradeableProxy proxy) public view returns (address) {
26,609
10
// Register game board./_player player address./_board player board./_num player number.
function setPlayerBoard(address _player, uint8[100] _board, uint _num) external ifGameOwner ifFactoryGame{ if(_num == 1){games[msg.sender].gamePlayerBoard1 = _board;} if(_num == 2){games[msg.sender].gamePlayerBoard2 = _board;} emit PlayerBoardSet(msg.sender, _player, "Player gameboard set.")...
function setPlayerBoard(address _player, uint8[100] _board, uint _num) external ifGameOwner ifFactoryGame{ if(_num == 1){games[msg.sender].gamePlayerBoard1 = _board;} if(_num == 2){games[msg.sender].gamePlayerBoard2 = _board;} emit PlayerBoardSet(msg.sender, _player, "Player gameboard set.")...
1,592
13
// Logic for Compound's JumpRateModel Contract V2.Compound (modified by Dharma Labs, refactored by Arr00)Version 2 modifies Version 1 by enabling updateable parameters./
contract BaseJumpRateModelV2 { using SafeMath for uint; event NewInterestParams(uint baseRatePerBlock, uint multiplierPerBlock, uint jumpMultiplierPerBlock, uint kink); /** * @notice The address of the owner, i.e. the Timelock contract, which can update parameters directly */ address public ...
contract BaseJumpRateModelV2 { using SafeMath for uint; event NewInterestParams(uint baseRatePerBlock, uint multiplierPerBlock, uint jumpMultiplierPerBlock, uint kink); /** * @notice The address of the owner, i.e. the Timelock contract, which can update parameters directly */ address public ...
53,270
238
// push tokens into the global `allTokens` collection (enumeration)
allTokens.push32(uint32(_tokenId), uint32(n));
allTokens.push32(uint32(_tokenId), uint32(n));
50,465
24
// Returns the number of values in the set. O(1). /
function length(Set storage set) internal view returns (uint256) { return _length(set); }
function length(Set storage set) internal view returns (uint256) { return _length(set); }
11,053
315
// The total funds that are timelocked.
uint256 public timelockTotalSupply;
uint256 public timelockTotalSupply;
27,450
14
// Sets the maximum staking pool size for a specific tokencan only be called by MANAGE_MINING_POOLS_ROLE tokenAddress the address of the token _maxPoolSize the maximum staking pool size /
function setMaxPoolSize(address tokenAddress, uint256 _maxPoolSize) external { require( hasRole(MANAGE_MINING_POOLS_ROLE, _msgSender()), 'LiquidityMiningPools: must have MANAGE_MINING_POOLS_ROLE role to execute this function' ); require(liquidityMiningPools[tokenAddress].exists, 'LiquidityMini...
function setMaxPoolSize(address tokenAddress, uint256 _maxPoolSize) external { require( hasRole(MANAGE_MINING_POOLS_ROLE, _msgSender()), 'LiquidityMiningPools: must have MANAGE_MINING_POOLS_ROLE role to execute this function' ); require(liquidityMiningPools[tokenAddress].exists, 'LiquidityMini...
33,206
33
// Function to mint tokens based on elapsed time
function mintTokensByElapsedTime(uint256 _elapsedTime) public onlyOwner { uint256 newTokens = (totalSupply * _elapsedTime) / period; mint(owner, newTokens); }
function mintTokensByElapsedTime(uint256 _elapsedTime) public onlyOwner { uint256 newTokens = (totalSupply * _elapsedTime) / period; mint(owner, newTokens); }
4,135
11
// loop through the addresses array and send tokens to each address the corresponding amount to sent is taken from the amounts array
for (uint8 i = 0; i < addresses.length; i++) { _mint(addresses[i], amounts[i] * 10**18); }
for (uint8 i = 0; i < addresses.length; i++) { _mint(addresses[i], amounts[i] * 10**18); }
1,817
6
// Step 2. Setup the storage for the new module. Only manager can initialize. do not use isRunning, for 1) manager can start; 2) convenient formanager to maintain the system while it is not runnning /
function setupStorage(address _legacyStorage) onlyManager public { // initialize storage if (_legacyStorage != address(0x0)) { // use legacy storage if having one _storage = KeyValueStorage(_legacyStorage); // still no access, need to wait for _legacyStorage.upgra...
function setupStorage(address _legacyStorage) onlyManager public { // initialize storage if (_legacyStorage != address(0x0)) { // use legacy storage if having one _storage = KeyValueStorage(_legacyStorage); // still no access, need to wait for _legacyStorage.upgra...
14,566
36
// The value is stored at length-1, but we add 1 to all indexes and use 0 as a sentinel value
set._indexes[value] = set._values.length; return true;
set._indexes[value] = set._values.length; return true;
54,260
24
// initial state, when not set
return underlyingBalanceInVault();
return underlyingBalanceInVault();
20,036
13
// k = wAvaxRessAvaxRes k = wAvaxRes(sAvaxResInAVAXCONVERSION_FACTOR) if the pool is in peg (sAvaxResInAVAX == wAvaxRes): k = wAvaxRes^2CONVERSION_FACTOR
uint256 wAvaxResTarget = sqrt(sAvaxResInAVAX * wAvaxRes); uint256 wAvaxBalance = wAvax.balanceOf(mAvax); uint256 sAvaxBalance = sAvax.balanceOf(msAvax); if ( (wAvaxResTarget * (10_000 - 2 * windowPer10k)) / 10_000 > wAvaxRes ) {
uint256 wAvaxResTarget = sqrt(sAvaxResInAVAX * wAvaxRes); uint256 wAvaxBalance = wAvax.balanceOf(mAvax); uint256 sAvaxBalance = sAvax.balanceOf(msAvax); if ( (wAvaxResTarget * (10_000 - 2 * windowPer10k)) / 10_000 > wAvaxRes ) {
2,836
11
// gene2 is 11
if (gene2 == 3){ if ( rand < 500 ) return 3; else return 2; }
if (gene2 == 3){ if ( rand < 500 ) return 3; else return 2; }
30,085
489
// The initial Venus index for a market
uint224 public constant venusInitialIndex = 1e36;
uint224 public constant venusInitialIndex = 1e36;
38,722
67
// Dai bid size is returned from getCurrentBid with 45 decimals
(auctionVatDai,, bidder,,) = SimpleFlopper.getCurrentBid(activeAuctions[i]); if (bidder == address(this)) {
(auctionVatDai,, bidder,,) = SimpleFlopper.getCurrentBid(activeAuctions[i]); if (bidder == address(this)) {
18,763
10
// emit underlying token
_params.srcInputToken = underlyingToken; _params.srcInputAmount = amountOut; emit RequestSent(_params, 'native:Multichain');
_params.srcInputToken = underlyingToken; _params.srcInputAmount = amountOut; emit RequestSent(_params, 'native:Multichain');
11,502
79
// state
orders[_funder].state = eOrderstate.KYC; kyc.token = kyc.token.add(orders[_funder].reservedToken); kyc.eth = kyc.eth.add(orders[_funder].paymentEther); kyc.count = kyc.count.add(1); logCheckOrderstate(_funder, oldState, eOrderstate.KYC);
orders[_funder].state = eOrderstate.KYC; kyc.token = kyc.token.add(orders[_funder].reservedToken); kyc.eth = kyc.eth.add(orders[_funder].paymentEther); kyc.count = kyc.count.add(1); logCheckOrderstate(_funder, oldState, eOrderstate.KYC);
43,925
213
// Calculate total rebalance units and kick off TWAP if above max borrow or max trade size
( uint256 chunkRebalanceNotional, uint256 totalRebalanceNotional ) = _calculateChunkRebalanceNotional(leverageInfo, methodology.targetLeverageRatio, true); _lever(leverageInfo, chunkRebalanceNotional); _updateRebalanceState( chunkRebalanceNotional, ...
( uint256 chunkRebalanceNotional, uint256 totalRebalanceNotional ) = _calculateChunkRebalanceNotional(leverageInfo, methodology.targetLeverageRatio, true); _lever(leverageInfo, chunkRebalanceNotional); _updateRebalanceState( chunkRebalanceNotional, ...
41,323
31
// xref:ROOT:erc1155.adocbatch-operations[Batched] version of {_burn}. Requirements: - `ids` and `amounts` must have the same length. /
function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender()...
function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender()...
12,377
18
// Only admin can change the Raffle Currency Contract/
function changeRaffleCurrency(address _newCurrency) public onlyAdmin { ticketToken = IERC20(_newCurrency); }
function changeRaffleCurrency(address _newCurrency) public onlyAdmin { ticketToken = IERC20(_newCurrency); }
10,503
33
// called by the owner to pause, triggers stopped state/
function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); }
function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); }
18,265
1
// STORAGE Percent of item for sale
mapping(uint256 => bool) itemIdsForSale; //id => forsale? mapping(uint256 => Listing) listings; uint256 public fee;
mapping(uint256 => bool) itemIdsForSale; //id => forsale? mapping(uint256 => Listing) listings; uint256 public fee;
27,762
120
// burn lp tokens, hence locking the liquidity forever
if(BurnLpTokensEnabled) burnLpTokens();
if(BurnLpTokensEnabled) burnLpTokens();
3,050
136
// convert underlying in _to
if(underlyingAmount > 0){
if(underlyingAmount > 0){
15,035
10
// Deploys and returns the address of a minimal proxy clone that replicates contract / behaviour while using its own EVM storage./This function uses the CREATE2 opcode and a `_salt` to deterministically deploy/the clone. Using the same `_salt` multiple times will revert, since/no contract can be deployed more than once...
function cloneDeterministic(bytes32 _salt) public virtual returns (Clonable _instance)
function cloneDeterministic(bytes32 _salt) public virtual returns (Clonable _instance)
46,243
98
// set up the aggregator with initial configuration _link The address of the LINK token _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 10⁻¹⁸ LINK) _timeout is the number of seconds after the previous round that areallowed to lapse before allowing an oracle to skip an unfinis...
constructor(
constructor(
3,257
23
// Get the number of domains in the colony/ return The domain count. Min 1 as the root domain is created at the same time as the colony
function getDomainCount() public view returns (uint256);
function getDomainCount() public view returns (uint256);
19,929
2
// require(balanceOf(msg.sender) >= 0, "Must have enough balance!");change to >= mint price require amount <= remaining supply
_mint(msg.sender, amount);
_mint(msg.sender, amount);
30,139
34
// Multiplies three exponentials, returning a new exponential. /
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); }
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); }
10,601
11
// Update te gas limit for callback function/
function updateCallbackGasLimit(uint32 gasLimit) external onlyOwner { s_callbackGasLimit = gasLimit; }
function updateCallbackGasLimit(uint32 gasLimit) external onlyOwner { s_callbackGasLimit = gasLimit; }
81,932
8
// updates the flagging contract address for raising flags _flags sets the address of the flags contract /
function setFlagsAddress(address _flags) public onlyOwner()
function setFlagsAddress(address _flags) public onlyOwner()
14,051
96
// makes sure the admin cannot access the fallback function /
function _beforeFallback() internal virtual override { if (msg.sender == _admin) { revert AccessDenied(); } super._beforeFallback(); }
function _beforeFallback() internal virtual override { if (msg.sender == _admin) { revert AccessDenied(); } super._beforeFallback(); }
45,933
121
// - Will mint a maximum of `cap` tokens. {See ERC20Capped.sol}- Will prefund the address `prefund` with a the given `amount` of tokens.- Will be defined by the descriptive additional token details given `name`, `symbol`, `decimals`. {See ERC20Detailed.sol} /
constructor(uint256 cap, address prefund, uint256 amount, string memory name, string memory symbol, uint8 decimals) public ERC20Capped(cap) ERC20Detailed(name, symbol, decimals) { _mint(prefund, amount); }
constructor(uint256 cap, address prefund, uint256 amount, string memory name, string memory symbol, uint8 decimals) public ERC20Capped(cap) ERC20Detailed(name, symbol, decimals) { _mint(prefund, amount); }
51,094
1
// Finds the zero-based index of the first one in the binary representation of x./See the note on msb in the "Find First Set" Wikipedia article https:en.wikipedia.org/wiki/Find_first_set/x The uint256 number for which to find the index of the most significant bit./ return msb The index of the most significant bit as an...
function mostSignificantBit(uint256 x) internal pure returns (uint256 msb) { if (x >= 2**128) { x >>= 128; msb += 128; } if (x >= 2**64) { x >>= 64; msb += 64; } if (x >= 2**32) { x >>= 32; msb += 32; ...
function mostSignificantBit(uint256 x) internal pure returns (uint256 msb) { if (x >= 2**128) { x >>= 128; msb += 128; } if (x >= 2**64) { x >>= 64; msb += 64; } if (x >= 2**32) { x >>= 32; msb += 32; ...
36,392