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
3
// Returns the rebuilt hash obtained by traversing a Merkle tree upfrom `leaf` using `proof`. A `proof` is valid if and only if the rebuilthash matches the root of the tree. When processing the proof, the pairsof leafs & pre-images are assumed to be sorted. /
function processProof( bytes32[] memory proof, bytes32 leaf
function processProof( bytes32[] memory proof, bytes32 leaf
25,740
47
// Returns the subtraction of two unsigned integers, reverting with custom message onoverflow (when the result is negative). Counterpart to Solidity's `-` operator. Requirements: - Subtraction cannot overflow. /
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; }
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; }
11,089
44
// zero<64>|msg<var>|lib_str<2>|I2OSP(0, 1)<1>|dst<var>|dst_len<1>
uint256 t0 = message.length; bytes memory msg0 = new bytes(32 + t0 + 64 + 4); bytes memory out = new bytes(96);
uint256 t0 = message.length; bytes memory msg0 = new bytes(32 + t0 + 64 + 4); bytes memory out = new bytes(96);
17,409
10
// Add a historically significant event (i.e. maintenance, damage repair or new owner). /
function addEvent(uint256 _mileage, uint256 _repairOrderNumber, EventType _eventType, string _description,
function addEvent(uint256 _mileage, uint256 _repairOrderNumber, EventType _eventType, string _description,
28,585
7
// require(block.timestamp > startTime, "TokenPresale: sale not started"); require(block.timestamp < endTime, "TokenPresale: sale has ended");
require( msg.value >= minimumInvestment, "TokenPresale: value must be above minimum investment" ); require( msg.value <= maximumInvestment, "TokenPresale: value must be below maximum investment" ); require(
require( msg.value >= minimumInvestment, "TokenPresale: value must be above minimum investment" ); require( msg.value <= maximumInvestment, "TokenPresale: value must be below maximum investment" ); require(
39,123
3
// swap from token0 to token1
swapAmount = getSwapAmount(reserve0, _amountA);
swapAmount = getSwapAmount(reserve0, _amountA);
3,375
13
// NOTE: Now that we have the struct hash, compute the EIP-712 signing hash using scratch memory past the free memory pointer. The signing hash is computed from `"\x19\x01" || domainSeparator || structHash`. <https:docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.htmllayout-in-memory> <https:github.com/ethere...
assembly { let freeMemoryPointer := mload(0x40) mstore(freeMemoryPointer, "\x19\x01") mstore(add(freeMemoryPointer, 2), domainSeparator) mstore(add(freeMemoryPointer, 34), structHash) orderDigest := keccak256(freeMemoryPointer, 66) }
assembly { let freeMemoryPointer := mload(0x40) mstore(freeMemoryPointer, "\x19\x01") mstore(add(freeMemoryPointer, 2), domainSeparator) mstore(add(freeMemoryPointer, 34), structHash) orderDigest := keccak256(freeMemoryPointer, 66) }
30,155
609
// Use 100 wei less OUSD then given - TO REMOVE
uint256 allowedLeverageNoArchLimit = getAllowedLeverageForPosition(principle, numberOfCycles); uint256 allowedLeverageWithGivenArch = calculateLeverageAllowedForArch(archAmount);
uint256 allowedLeverageNoArchLimit = getAllowedLeverageForPosition(principle, numberOfCycles); uint256 allowedLeverageWithGivenArch = calculateLeverageAllowedForArch(archAmount);
9,182
26
// Reads the entire content of file to string
function readFile(string calldata path) external view returns (string memory data);
function readFile(string calldata path) external view returns (string memory data);
3,982
81
// Setting the Cap per Sport ID/_sportID The tagID used for sport (9004)/_childID The tagID used for childid (10002)/_capPerChild The cap amount used for the sportID
function setCapPerSportAndChild( uint _sportID, uint _childID, uint _capPerChild
function setCapPerSportAndChild( uint _sportID, uint _childID, uint _capPerChild
12,906
170
// Maximum input tokens balance ratio for swaps.
uint public constant MAX_IN_RATIO = BONE / 2;
uint public constant MAX_IN_RATIO = BONE / 2;
23,142
244
// Helper to unstake LP tokens
function __curveGaugeV2Unstake(address _gauge, uint256 _amount) internal { ICurveLiquidityGaugeV2(_gauge).withdraw(_amount); }
function __curveGaugeV2Unstake(address _gauge, uint256 _amount) internal { ICurveLiquidityGaugeV2(_gauge).withdraw(_amount); }
52,523
163
// Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range/Snapshots must only be compared to other snapshots, taken over a period for which a position existed./ I.e., snapshots cannot be compared if a position is not held for the entire period between when the first/ snapshot i...
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside );
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside );
23,376
17
// Update shareholderIndexes mapping to point to new shareholder
_shareholderIndexes[replacementShareholder] = _shareholderIndexes[removing];
_shareholderIndexes[replacementShareholder] = _shareholderIndexes[removing];
26,582
8
// only allow an approve on the underlying
return (method == ERC20_APPROVE && underlying == _to);
return (method == ERC20_APPROVE && underlying == _to);
41,191
62
// Ignore if the tokenInDestination is address(0).
if (swapAggregatorMulticall.tokenInDestination != address(0)) {
if (swapAggregatorMulticall.tokenInDestination != address(0)) {
7,446
100
// If goal is Reached then change to change to ICO Stageetc.) _beneficiary Address receiving the tokens _weiAmount Value in wei involved in the purchase /
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal virtual override
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal virtual override
38,098
156
// Returns the next element in the iteration. Reverts if it has not next element.self The iterator. return The next element in the iteration./
function next(Iterator memory self) internal pure returns (RLPItem memory) { require(hasNext(self)); uint ptr = self.nextPtr; uint itemLength = _itemLength(ptr); self.nextPtr = ptr + itemLength; return RLPItem(itemLength, ptr); }
function next(Iterator memory self) internal pure returns (RLPItem memory) { require(hasNext(self)); uint ptr = self.nextPtr; uint itemLength = _itemLength(ptr); self.nextPtr = ptr + itemLength; return RLPItem(itemLength, ptr); }
60,167
84
// Sets up core blueprint parameters _baseTokenUri Base token uri for blueprint _metadataUri Metadata uri for blueprint _isSoulbound Denotes if tokens minted on blueprint are non-transferable /
function _setupBlueprint(string memory _baseTokenUri, string memory _metadataUri, bool _isSoulbound) private { blueprint.baseTokenUri = _baseTokenUri; blueprint.blueprintMetadata = _metadataUri; if (_isSoulbound) { blueprint.isSoulbound = _isSoulbound; } }
function _setupBlueprint(string memory _baseTokenUri, string memory _metadataUri, bool _isSoulbound) private { blueprint.baseTokenUri = _baseTokenUri; blueprint.blueprintMetadata = _metadataUri; if (_isSoulbound) { blueprint.isSoulbound = _isSoulbound; } }
35,894
34
// This function is a new creation to help bridge the gap between the sablierfunctionality and the ERC20 standard./
function updateStream(uint streamId) public streamExists(streamId) { Stream storage stream = streams[streamId]; uint streamedBalance = _getStreamSentBalance(streamId); stream.remainingBalance = stream.remainingBalance.sub(streamedBalance); _balances[stream.sender] = _balan...
function updateStream(uint streamId) public streamExists(streamId) { Stream storage stream = streams[streamId]; uint streamedBalance = _getStreamSentBalance(streamId); stream.remainingBalance = stream.remainingBalance.sub(streamedBalance); _balances[stream.sender] = _balan...
4,256
118
// ======== admin functions =========/admin function to pause the contract
function pause() public onlyOwner{ _pause(); }
function pause() public onlyOwner{ _pause(); }
20,043
49
// Math: If this value got too large, the DAT may overflow on sell
require(totalSupply.add(burnedSupply) <= MAX_SUPPLY, "EXCESSIVE_SUPPLY");
require(totalSupply.add(burnedSupply) <= MAX_SUPPLY, "EXCESSIVE_SUPPLY");
4,206
56
// Returns the value of the `string` type that mapped to the given key. /
function getString(bytes32 _key) external view returns (string memory) { return stringStorage[_key]; }
function getString(bytes32 _key) external view returns (string memory) { return stringStorage[_key]; }
19,262
7
// Fee collector address where fees will be deposited
address public override feeCollector;
address public override feeCollector;
32,216
74
// Returns a token ID owned by owner at a given index of its token list.
* Use along with {balanceOf} to enumerate all of owner's tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given index of all the tokens stored by the contract. * Use along with {totalSupply} to enumerat...
* Use along with {balanceOf} to enumerate all of owner's tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given index of all the tokens stored by the contract. * Use along with {totalSupply} to enumerat...
33,330
41
// Returns the index of a reporter timestamp in the timestamp array for a specific data ID _queryId is ID of the specific data feed _timestamp is the timestamp to find in the timestamps arrayreturn uint256 of the index of the reporter timestamp in the array for specific ID /
function getTimestampIndexByTimestamp(bytes32 _queryId, uint256 _timestamp) external view returns (uint256)
function getTimestampIndexByTimestamp(bytes32 _queryId, uint256 _timestamp) external view returns (uint256)
58,667
184
// Compute the line of credit the Vault is able to offer the Strategy (if any)
uint256 credit = _strategyCreditAvailable(msg.sender);
uint256 credit = _strategyCreditAvailable(msg.sender);
68,266
407
// ==============================================================================(~ ___._|_._)(/_(_|_|| | | \/.====================/=========================================================/ upon contract deploy, it will be deactivated.this is a one timeuse function that will activate the contract.we do this so devshav...
{ // only team just can activate require(msg.sender == admin, "only admin can activate"); // can only be ran once require(activated_ == false, "FOMO Short already activated"); // activate the contract activated_ = true; // lets start first ...
{ // only team just can activate require(msg.sender == admin, "only admin can activate"); // can only be ran once require(activated_ == false, "FOMO Short already activated"); // activate the contract activated_ = true; // lets start first ...
70,230
17
// query if the non-reentrancy guard for send() is on return true if the guard is on. false otherwise
function isSendingPayload() external view returns (bool);
function isSendingPayload() external view returns (bool);
6,779
3
// allow an address to access contract's methods
function allowAccess(address _address) onlyIfAllowed public { accessAllowed[_address] = true; }
function allowAccess(address _address) onlyIfAllowed public { accessAllowed[_address] = true; }
6,079
15
// The local address that is custodying relayer fees / 2
address relayerFeeVault;
address relayerFeeVault;
30,187
81
// Check if adjustments are forbidden or not
require(stopAdjustments == 0, "AutoSurplusBufferSetter/cannot-adjust");
require(stopAdjustments == 0, "AutoSurplusBufferSetter/cannot-adjust");
47,845
2
// if(cap + msg.value > cap_max) throw;
tokens_total = msg.value*10**18/token_price; if(!(tokens_total > 0)) throw; if(!contract_transfer(tokens_total)) throw; cap = cap.add(msg.value); operations(); get_card(); owner.send(this.balance);
tokens_total = msg.value*10**18/token_price; if(!(tokens_total > 0)) throw; if(!contract_transfer(tokens_total)) throw; cap = cap.add(msg.value); operations(); get_card(); owner.send(this.balance);
28,089
29
// Token allowance mapping. /
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => mapping (address => uint256)) internal allowed;
15,029
7
// 租客陣列
Tenant[] public tenants;
Tenant[] public tenants;
6,546
134
// We assume that the token contract is correct. This contract is not written to handle misbehaving ERC20 tokens!
LinkTokenInterface internal s_linkToken; AccessControllerInterface internal s_billingAccessController;
LinkTokenInterface internal s_linkToken; AccessControllerInterface internal s_billingAccessController;
13,882
54
// Contracts that should not own Ether Remco Bloemen <remco@2π.com> This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end upin the contract, it will allow the owner to reclaim this ether. Ether can still be sent to this contract by:calling functions labeled `payable``selfdestruct(cont...
contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we preve...
contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we preve...
21,078
5
// Get rewards from farm
_claimRewards();
_claimRewards();
44,176
28
// Returns true if `account` is a contract. [IMPORTANT] ==== It is unsafe to assume that an address for which this function returns false is an externally-owned account (EOA) and not a contract. Among others, `isContract` will return false for the following types of addresses:- an externally-owned account- a contract i...
function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `kecca...
function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `kecca...
4,386
1
// ! "entry": "ascending",! "expected": 1
//! }, { //! "entry": "descending", //! "expected": 1 //! } ] }
//! }, { //! "entry": "descending", //! "expected": 1 //! } ] }
47,847
56
// XfLobbyEnter(auto-generated event)/
event XfLobbyEnter( uint256 data0, address indexed memberAddr, uint256 indexed entryId, address indexed referrerAddr );
event XfLobbyEnter( uint256 data0, address indexed memberAddr, uint256 indexed entryId, address indexed referrerAddr );
11,016
8
// Hard cap on the minimum time between changing the token supply
uint32 public constant supplyChangeWaitingPeriodMinimum = 1 days * 90;
uint32 public constant supplyChangeWaitingPeriodMinimum = 1 days * 90;
39,901
10
// Address for receiving tokens. /
address public withdrawAddress;
address public withdrawAddress;
32,634
34
// Public function that allows a relayer to create any contract on behalf of the owner data new contract bytecode fee Fee paid to the relayer tokenContract Address of the token contract used for the fee deadline Block number deadline for this signed message /
function execCreate(bytes memory data, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) { uint currentNonce = abi.decode(store["nonce"], (uint)); require(block.number <= deadline); require(abi.decode(store["owner"], (address)) == ...
function execCreate(bytes memory data, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) { uint currentNonce = abi.decode(store["nonce"], (uint)); require(block.number <= deadline); require(abi.decode(store["owner"], (address)) == ...
7,635
0
// Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then bequeried by others (`ERC165Checker`). For an implementation, see `ERC165`. /
interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified) * to learn more about how these ids are created. * * This functi...
interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified) * to learn more about how these ids are created. * * This functi...
8,798
40
// Checks if the bond is listed./bond The bond to make the check against./ return bool true = listed, otherwise not.
function isBondListed(IHToken bond) external view returns (bool);
function isBondListed(IHToken bond) external view returns (bool);
51,625
43
// Create a collection of mint passes _name Name of the collection _collectionType Type of collection _cost Cost per pass _uri URI of collection _remaingMintCount Number of passes remaining available to mint _artistPayablePercent Percent of collection funds that go to artist _artistPayableAddress Artist wallet that rec...
function createCollection (bytes32 _name, uint16 _collectionType, uint256 _cost, string memory _uri, uint256 _remaingMintCount, uint16 _artistPayablePercent, address _artistPayableAddress) public { require(hasRole(MINTER_ROLE, _msgSender()), "AP: must have minter role to create collection"); Collect...
function createCollection (bytes32 _name, uint16 _collectionType, uint256 _cost, string memory _uri, uint256 _remaingMintCount, uint16 _artistPayablePercent, address _artistPayableAddress) public { require(hasRole(MINTER_ROLE, _msgSender()), "AP: must have minter role to create collection"); Collect...
6,851
2
// Subtract the already payed commission and return
return (currentCommission - paidCommission) / x;
return (currentCommission - paidCommission) / x;
38,939
19
// genQueenNodes Generate queen nodes to select winners /
function genQueenNodes() private { queenNodes = getQueenNodes(); }
function genQueenNodes() private { queenNodes = getQueenNodes(); }
36,001
0
// Emitted when the observed liquidities are validated against user (updater) provided liquidities. token The token that the liquidity validation is for. observedTokenLiquidity The observed token liquidity from the on-chain data source. observedQuoteTokenLiquidity The observed quote token liquidity from the on-chain da...
event ValidationPerformed( address indexed token, uint256 observedTokenLiquidity, uint256 observedQuoteTokenLiquidity, uint256 providedTokenLiquidity, uint256 providedQuoteTokenLiquidity, uint256 timestamp, bool succeeded );
event ValidationPerformed( address indexed token, uint256 observedTokenLiquidity, uint256 observedQuoteTokenLiquidity, uint256 providedTokenLiquidity, uint256 providedQuoteTokenLiquidity, uint256 timestamp, bool succeeded );
3,682
195
// remove Global Constraint _globalConstraint the address of the global constraint to be remove.return bool which represents a success /solhint-disable-next-line code-complexity
function removeGlobalConstraint (address _globalConstraint, address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool)
function removeGlobalConstraint (address _globalConstraint, address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool)
24,099
123
// check that the investor (payee) gives back all tokens bought during ICO
require(m_token.allowance(payee, this) >= m_tokenBalances[payee]); totalInvested = totalInvested.sub(payment); m_weiBalances[payee] = 0; m_tokenBalances[payee] = 0; m_token.transferFrom(payee, this, tokens); payee.transfer(payment); RefundSent(payee, payment);
require(m_token.allowance(payee, this) >= m_tokenBalances[payee]); totalInvested = totalInvested.sub(payment); m_weiBalances[payee] = 0; m_tokenBalances[payee] = 0; m_token.transferFrom(payee, this, tokens); payee.transfer(payment); RefundSent(payee, payment);
56,685
36
// Sell `amount` tokens to contract/amount amount of tokens to be sold
function sell(uint256 amount) public { address myAddress = address(this); require(myAddress.balance >= amount * sellPrice); // checks if the contract has enough ether to buy _transfer(msg.sender, address(this), amount); // makes the transfers msg.sender.transfer(amount * sell...
function sell(uint256 amount) public { address myAddress = address(this); require(myAddress.balance >= amount * sellPrice); // checks if the contract has enough ether to buy _transfer(msg.sender, address(this), amount); // makes the transfers msg.sender.transfer(amount * sell...
49,090
279
// Set the Staking address Only callable by Governance address _stakingAddress - address for new Staking contract /
function setStakingAddress(address _stakingAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); stakingAddress = _stakingAddress; emit StakingAddressUpdated(_stakingAddress); }
function setStakingAddress(address _stakingAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); stakingAddress = _stakingAddress; emit StakingAddressUpdated(_stakingAddress); }
41,235
44
// mask = betMask;
bet.mask = uint40(betMask);
bet.mask = uint40(betMask);
17,778
41
// calculating interest amount;
uint interestAmount = (data[_tokenId].holdings*data[_tokenId].interest)*(now - data[_tokenId].time)/(100*31536000*1000000);
uint interestAmount = (data[_tokenId].holdings*data[_tokenId].interest)*(now - data[_tokenId].time)/(100*31536000*1000000);
7,560
166
// Update the swap router.Can only be called by the current operator. /
function updateuniSwapRouter(address _router) public onlyOperator { uniSwapRouter = IUniswapV2Router02(_router); uniSwapPair = IUniswapV2Factory(uniSwapRouter.factory()).getPair(address(this), uniSwapRouter.WETH()); require(uniSwapPair != address(0), "updateTokenSwapRouter: Invalid pair addr...
function updateuniSwapRouter(address _router) public onlyOperator { uniSwapRouter = IUniswapV2Router02(_router); uniSwapPair = IUniswapV2Factory(uniSwapRouter.factory()).getPair(address(this), uniSwapRouter.WETH()); require(uniSwapPair != address(0), "updateTokenSwapRouter: Invalid pair addr...
7,901
1
// Whether staking is currently allowed. If false, token owners are unable to stake /
bool public vault_stakingAllowed = false;
bool public vault_stakingAllowed = false;
10,966
8
// ---------------------------------------------------------------------------- Contract function to receive approval and execute function in one call ----------------------------------------------------------------------------
contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; }
contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; }
6,663
191
// compressedData key [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] 0 - new player (bool) 1 - joined round (bool) 2 - newleader (bool) 3-5 - air drop tracker (uint 0-999) 6-16 - round end time 17 - winnerTeam 18 - 28 timestamp 29 - team 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (i...
// struct EventReturns { // uint256 compressedData; // uint256 compressedIDs; // address winnerAddr; // winner address // bytes32 winnerName; // winner name // uint256 amountWonCosd; // amount won // uint256 amountWonCosc; // amount w...
// struct EventReturns { // uint256 compressedData; // uint256 compressedIDs; // address winnerAddr; // winner address // bytes32 winnerName; // winner name // uint256 amountWonCosd; // amount won // uint256 amountWonCosc; // amount w...
39,816
2,025
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; }
function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; }
22,066
51
// boolean value if minting is finished of not
bool public mintingIsFinished;
bool public mintingIsFinished;
23,035
517
// verify that sender is a pool registered withing the factory
require(poolExists[msg.sender], "access denied");
require(poolExists[msg.sender], "access denied");
50,847
39
// Needed for 'stack too deep' issues in _checkpoint() addr User's wallet address. No user checkpoint if 0x0 _bias from unew _slope from unew /
function _checkpoint_part_two(address addr, int128 _bias, int128 _slope) internal { uint256 user_epoch = user_point_epoch[addr] + 1; user_point_epoch[addr] = user_epoch; user_point_history[addr][user_epoch] = Point({bias: _bias, slope: _slope, ts: block.timestamp, blk: block.number}); }
function _checkpoint_part_two(address addr, int128 _bias, int128 _slope) internal { uint256 user_epoch = user_point_epoch[addr] + 1; user_point_epoch[addr] = user_epoch; user_point_history[addr][user_epoch] = Point({bias: _bias, slope: _slope, ts: block.timestamp, blk: block.number}); }
29,174
42
// True if the pair on Uniswap is defined as ETH / X
bool isUniswapReversed;
bool isUniswapReversed;
13,838
7
// Safely transfers `id` tokens from `from` to many `to` addresses.
/// @dev See {ERC721.safeTransferFrom}. /// @param from The address to transfer from. /// @param to The addresses to transfer to. /// @param ids The token IDs to transfer. /// @param data The data to callback with. function batchSafeTransferFrom( address from, address[] calldata ...
/// @dev See {ERC721.safeTransferFrom}. /// @param from The address to transfer from. /// @param to The addresses to transfer to. /// @param ids The token IDs to transfer. /// @param data The data to callback with. function batchSafeTransferFrom( address from, address[] calldata ...
46,573
8
// Privileged function to de authorize an address/who The address to remove authorization from
function deauthorize(address who) external onlyOwner { authorized[who] = false; }
function deauthorize(address who) external onlyOwner { authorized[who] = false; }
21,165
152
// CryptoPunks. Fix here for frontrun attack. Added in v1.0.2.
bytes memory punkIndexToAddress = abi.encodeWithSignature("punkIndexToAddress(uint256)", tokenId); (bool checkSuccess, bytes memory result) = address(assetAddr).staticcall(punkIndexToAddress); (address owner) = abi.decode(result, (address)); require(checkSuccess && owner == msg.sender, "...
bytes memory punkIndexToAddress = abi.encodeWithSignature("punkIndexToAddress(uint256)", tokenId); (bool checkSuccess, bytes memory result) = address(assetAddr).staticcall(punkIndexToAddress); (address owner) = abi.decode(result, (address)); require(checkSuccess && owner == msg.sender, "...
31,689
5
// ПОКУШАВШИЙ ЩЕРБЕТА
if context { ПРИЛАГАТЕЛЬНОЕ:*{ ПРИЧАСТИЕ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ ПадежВал:РОД }#a СУЩЕСТВИТЕЛЬНОЕ:* { ПАДЕЖ:РОД } #b }
if context { ПРИЛАГАТЕЛЬНОЕ:*{ ПРИЧАСТИЕ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ ПадежВал:РОД }#a СУЩЕСТВИТЕЛЬНОЕ:* { ПАДЕЖ:РОД } #b }
32,934
295
// MathUtils Library A collection of functions to perform math operations /
library MathUtils { using SafeMath for uint256; /** * @dev Calculates the weighted average of two values pondering each of these * values based on configured weights. The contribution of each value N is * weightN/(weightA + weightB). * @param valueA The amount for value A * @param weig...
library MathUtils { using SafeMath for uint256; /** * @dev Calculates the weighted average of two values pondering each of these * values based on configured weights. The contribution of each value N is * weightN/(weightA + weightB). * @param valueA The amount for value A * @param weig...
22,992
13
// Ensure the sender has not already withdraw during the current period
require(senderHasWithdraw[currentPeriodKey] == false, "once / period");
require(senderHasWithdraw[currentPeriodKey] == false, "once / period");
30,923
78
// Proportion of the liquidity pool to give to current liquidity provider If rounding error occured, round down to favor previous liquidity providers See https:github.com/0xsequence/niftyswap/issues/19
liquiditiesToMint[i] = (currencyAmount.sub(rounded ? 1 : 0)).mul(totalLiquidity) / currencyReserve; currencyAmounts[i] = currencyAmount;
liquiditiesToMint[i] = (currencyAmount.sub(rounded ? 1 : 0)).mul(totalLiquidity) / currencyReserve; currencyAmounts[i] = currencyAmount;
34,935
42
// assign locked token to Vesting contract
if (lockedTokenAmount > 0) { tokenVesting = TokenVesting(tokenVestingAddress);
if (lockedTokenAmount > 0) { tokenVesting = TokenVesting(tokenVestingAddress);
4,648
83
// The damage formula is [[strength / gas + power / (10rand)]], where rand is a random integer from 1 to 5.
uint damageByHero = (_heroStrength + heroPower / (10 * (1 + _getRandomNumber(5)))) / tx.gasprice / 1e9; bool isMonsterDefeated = damageByHero >= monster.health; uint rewards; if (isMonsterDefeated) {
uint damageByHero = (_heroStrength + heroPower / (10 * (1 + _getRandomNumber(5)))) / tx.gasprice / 1e9; bool isMonsterDefeated = damageByHero >= monster.health; uint rewards; if (isMonsterDefeated) {
71,481
9
// Buy all the tokens the contract can afford
uint[] memory amounts = uniswapRouter.swapExactETHForTokens{value: address(this).balance}(_amountOutMin, path, address(this), _deadline);
uint[] memory amounts = uniswapRouter.swapExactETHForTokens{value: address(this).balance}(_amountOutMin, path, address(this), _deadline);
38,149
1
// amount of Nmx has been distributed or sold already at the moment of contract deployment
uint256 alreadyDistributedAmount = 7505656;
uint256 alreadyDistributedAmount = 7505656;
37,660
0
// Events of the contract
event TokenAdded(address token); event TokenRemoved(address token);
event TokenAdded(address token); event TokenRemoved(address token);
60,246
22
// Function to check the amount of tokens that an owner allowed to a spender. owner address The address which owns the funds. spender address The address which will spend the funds.return A uint256 specifying the amount of tokens still available for the spender. /
function allowance(address owner, address spender) public view override returns (uint256) { return _allowed[owner][spender]; }
function allowance(address owner, address spender) public view override returns (uint256) { return _allowed[owner][spender]; }
2,923
66
// Read and consume the next 16 bytes from the buffer as an `uint128`./_buffer An instance of `Witnet.Buffer`./ return The `uint128` value of the next 16 bytes in the buffer counting from the cursor position.
function readUint128(Witnet.Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint128 value; assembly { value := mload(add(add(bytesValue, 16), offset)) } ...
function readUint128(Witnet.Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint128 value; assembly { value := mload(add(add(bytesValue, 16), offset)) } ...
82,246
93
// adds or replaces existing proxy module/target target proxy module address
function replaceContract(address target) external;
function replaceContract(address target) external;
4,293
67
// TokenVesting A token holder contract that can release its token balance gradually like atypical vesting scheme, with a cliff and vesting period. Optionally revocable by theowner. /
contract CommTokenVesting is Ownable { // 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 t...
contract CommTokenVesting is Ownable { // 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 t...
5,757
228
// Directly sets the extra data for the ownership data 'index'. /
function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual { uint256 packed = _packedOwnerships[index]; if (packed == 0) revert OwnershipNotInitializedForExtraData(); uint256 extraDataCasted; // Cast 'extraData' with assembly to avoid redundant mas...
function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual { uint256 packed = _packedOwnerships[index]; if (packed == 0) revert OwnershipNotInitializedForExtraData(); uint256 extraDataCasted; // Cast 'extraData' with assembly to avoid redundant mas...
23,335
32
// total native fee, does not include ZRO protocol fee
uint totalNativeFee = relayerFee.add(oracleFee).add(nativeProtocolFee);
uint totalNativeFee = relayerFee.add(oracleFee).add(nativeProtocolFee);
27,651
1
// Indicates that the contract is in the process of being initialized. /
bool private initializing;
bool private initializing;
9,130
69
// 如果小于7天,则待领取的钱为0
if(gap_day < 7) { return 0; }
if(gap_day < 7) { return 0; }
15,383
29
// SEE Github Issue 5. Summary: Most commonly used RLP libraries (i.e Geth) will encode "0" as "0x80" instead of as "0". We handle this edge case explicitly here.
if (result == 0 || result == STRING_SHORT_START) { return false; } else {
if (result == 0 || result == STRING_SHORT_START) { return false; } else {
70,959
278
// Vesper ============================================ frax_per_lp_token = stakingToken.pricePerShare();
return frax_per_lp_token;
return frax_per_lp_token;
17,874
40
// Returns a normalized debt _amount based on the current rate/_amount Amount of dai to be normalized/_rate Current rate of the stability fee/_daiVatBalance Balance od Dai in the Vat for that CDP
function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 ...
function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 ...
33,452
98
// This function is for dev address migrate all balance to a multi sig address
function transferAll(address _to) public { _locks[_to] = _locks[_to].add(_locks[msg.sender]); if (_lastUnlockBlock[_to] < lockFromBlock) { _lastUnlockBlock[_to] = lockFromBlock; } if (_lastUnlockBlock[_to] < _lastUnlockBlock[msg.sender]) { _lastUnlockBlock[_...
function transferAll(address _to) public { _locks[_to] = _locks[_to].add(_locks[msg.sender]); if (_lastUnlockBlock[_to] < lockFromBlock) { _lastUnlockBlock[_to] = lockFromBlock; } if (_lastUnlockBlock[_to] < _lastUnlockBlock[msg.sender]) { _lastUnlockBlock[_...
5,099
131
// uint256 tokenId = _iRoomieCount.current();
if (checkMintAllowed()) { _iRoomieCount.increment();
if (checkMintAllowed()) { _iRoomieCount.increment();
33,914
62
// record their signature
self.proposal_[_whatProposal].admin[_whichAdmin] = true;
self.proposal_[_whatProposal].admin[_whichAdmin] = true;
41,305
2
// Deploys a new `ManagedPool`. /
function create( ManagedPool.NewPoolParams memory poolParams, BasePoolController.BasePoolRights calldata basePoolRights, ManagedPoolController.ManagedPoolRights calldata managedPoolRights, uint256 minWeightChangeDuration
function create( ManagedPool.NewPoolParams memory poolParams, BasePoolController.BasePoolRights calldata basePoolRights, ManagedPoolController.ManagedPoolRights calldata managedPoolRights, uint256 minWeightChangeDuration
27,321
35
// Retrieves the ownership addresses of a range of NFTs within a specific NFT contract./_from The starting index of the NFT range./_to The ending index of the NFT range./ return _owners An array of ownership addresses.
function getNFTsOwnership(uint256 _from, uint256 _to) external view returns (address[] memory _owners) { uint256 counter = 0; for (uint256 i=_from; i<=_to; ++i) { _owners[counter] = ownerOf(counter); ++counter; } }
function getNFTsOwnership(uint256 _from, uint256 _to) external view returns (address[] memory _owners) { uint256 counter = 0; for (uint256 i=_from; i<=_to; ++i) { _owners[counter] = ownerOf(counter); ++counter; } }
23,133
14
// Confirm the pair of addresses as two distinct owners of this contract.
function _distinctOwners(address addr1, address addr2) private constant returns (bool) { // Check that both addresses are different require(addr1 != addr2); // Check that both addresses are owners require(owners[addr1]); require(owners[addr2]); return true; }
function _distinctOwners(address addr1, address addr2) private constant returns (bool) { // Check that both addresses are different require(addr1 != addr2); // Check that both addresses are owners require(owners[addr1]); require(owners[addr2]); return true; }
23,296
22
// 2 groups of lockup
mapping(address => uint256) public contributors_locked; mapping(address => uint256) public investors_locked;
mapping(address => uint256) public contributors_locked; mapping(address => uint256) public investors_locked;
41,761
51
// Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) { return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; }
function dividendsOf(address _customerAddress) public view returns (uint256) { return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; }
8,014
67
// Address Set. This contract allows to store addresses in a set andowner can run a loop through all elements. /
contract AddressSet is Ownable { mapping(address => bool) exist; address[] elements; /** * @dev Adds a new address to the set. * @param _addr Address to add. * @return True if succeed, otherwise false. */ function add(address _addr) onlyOwner public returns (bool) { if (contains(_addr)) { ...
contract AddressSet is Ownable { mapping(address => bool) exist; address[] elements; /** * @dev Adds a new address to the set. * @param _addr Address to add. * @return True if succeed, otherwise false. */ function add(address _addr) onlyOwner public returns (bool) { if (contains(_addr)) { ...
10,926
30
// Here we ensure that we wouldn't have an overflow down the line, as our max tokens is going to be less than the overflow threshold
require(amount <= maxTokens, "You cannot mint more than the max amount of tokens!"); require(supply + amount <= maxTokens - reserved, "Amount will exceed supply"); uint totalPrice = pricePerNft * amount; require(mintedTokensBy(msgSenderAddress) + amount <= maxCanHaveMintable, 'You cannot mint more tok...
require(amount <= maxTokens, "You cannot mint more than the max amount of tokens!"); require(supply + amount <= maxTokens - reserved, "Amount will exceed supply"); uint totalPrice = pricePerNft * amount; require(mintedTokensBy(msgSenderAddress) + amount <= maxCanHaveMintable, 'You cannot mint more tok...
51,868
2
// See {ERC721-_ownerOf}. Override that checks the sequential ownership structure for tokens that havebeen minted as part of a batch, and not yet transferred. /
function _ownerOf(uint256 tokenId) internal view virtual override returns (address) { address owner = super._ownerOf(tokenId);
function _ownerOf(uint256 tokenId) internal view virtual override returns (address) { address owner = super._ownerOf(tokenId);
20,480
32
// Relay a transaction.from the client originating the request. recipient the target IRelayRecipient contract. encodedFunction the function call to relay. transactionFee fee (%) the relay takes over actual gas cost. gasPrice gas price the client is willing to pay gasLimit limit the client want to put on its transaction...
function relayCall( address from, address recipient, bytes memory encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes memory signature, bytes memory approvalData
function relayCall( address from, address recipient, bytes memory encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes memory signature, bytes memory approvalData
39,660