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
37
// Allows the owner to change the name of the contract /
function changeName(bytes32 newName) onlyOwner() public { name = newName; }
function changeName(bytes32 newName) onlyOwner() public { name = newName; }
74,285
18
// Fire when the end of a rewards regime has been updated endTimestamp New end time for a pool rewardscurrencyId Reward currency - 1 = ETH, 2 = PRIME
event EndTimestampUpdated(uint256 endTimestamp, uint256 indexed currencyID);
event EndTimestampUpdated(uint256 endTimestamp, uint256 indexed currencyID);
21,135
1
// OtokenFactory key
bytes32 private constant OTOKEN_FACTORY = keccak256("OTOKEN_FACTORY");
bytes32 private constant OTOKEN_FACTORY = keccak256("OTOKEN_FACTORY");
27,542
116
// Adds new project `_projectName` by `_artistAddress`. _projectName Project name. _artistAddress Artist's address. token price now stored on minter /
function addProject( string memory _projectName, address payable _artistAddress
function addProject( string memory _projectName, address payable _artistAddress
13,063
233
// ... all the way to uint8(i_bytes[31])
string[5] memory part; string memory colorEye = string(abi.encodePacked(Strings.toString(attribute_a), ",", Strings.toString(attribute_b), ",", Strings.toString(attribute_c))); string memory colorBody = string(abi.encodePacked(Strings.toString(attribute_b), ",", Strings.toString(attribute_c), ...
string[5] memory part; string memory colorEye = string(abi.encodePacked(Strings.toString(attribute_a), ",", Strings.toString(attribute_b), ",", Strings.toString(attribute_c))); string memory colorBody = string(abi.encodePacked(Strings.toString(attribute_b), ",", Strings.toString(attribute_c), ...
14,758
15
// this means that we have an index variable called funderIndex and its going ot start from 0, this loop is going to finish whenever funder index is greater than or equal to the length of the funders and every time a loop is finished 1 will be added to the funder indexalso, and every time a peice of code in this for lo...
for (uint256 funderIndex=0; funderIndex < funders.length; funderIndex++){ address funder = funders[funderIndex]; addressToAmountFunded[funder]=0; }
for (uint256 funderIndex=0; funderIndex < funders.length; funderIndex++){ address funder = funders[funderIndex]; addressToAmountFunded[funder]=0; }
18,923
112
// Creates `amount` tokens of token type `id`, and assigns them to `account`. Should be callable only by MintableERC1155PredicateMake sure minting is done only by this function account user address for whom token is being minted id token which is being minted amount amount of token being minted data extra byte data to ...
function mint(address account, uint256 id, uint256 amount, bytes calldata data) external;
function mint(address account, uint256 id, uint256 amount, bytes calldata data) external;
16,523
54
// this is a guard that can be checked by resolution transactions as a Green signal
res.status = ResStatus.Executing; for(uint8 index=0; index < uint8(res.transaction_counter); index += 1) { require( this.call(res.transactions[index]) ); }
res.status = ResStatus.Executing; for(uint8 index=0; index < uint8(res.transaction_counter); index += 1) { require( this.call(res.transactions[index]) ); }
27,557
3
// Half-life of 12h. 12h = 720 min(1/2) = d^720 => d = (1/2)^(1/720) /
uint constant public MINUTE_DECAY_FACTOR = 999037758833783000; uint constant public REDEMPTION_FEE_FLOOR = DECIMAL_PRECISION / 1000 * 5; // 0.5% uint constant public MAX_BORROWING_FEE = DECIMAL_PRECISION / 100 * 5; // 5%
uint constant public MINUTE_DECAY_FACTOR = 999037758833783000; uint constant public REDEMPTION_FEE_FLOOR = DECIMAL_PRECISION / 1000 * 5; // 0.5% uint constant public MAX_BORROWING_FEE = DECIMAL_PRECISION / 100 * 5; // 5%
9,080
222
// The funding cycle structure represents a project stewarded by an address, and accounts for which addresses have helped sustain the project.
struct FundingCycle { // A unique number that's incremented for each new funding cycle, starting with 1. uint256 id; // The ID of the project contract that this funding cycle belongs to. uint256 projectId; // The number of this funding cycle for the project. uint256 number; // The ID of a pr...
struct FundingCycle { // A unique number that's incremented for each new funding cycle, starting with 1. uint256 id; // The ID of the project contract that this funding cycle belongs to. uint256 projectId; // The number of this funding cycle for the project. uint256 number; // The ID of a pr...
79,943
793
// Removes a LendingPoolAddressesProvider from the list of registered addresses provider provider The LendingPoolAddressesProvider address /
function unregisterAddressesProvider(address provider) external override onlyOwner { require(_addressesProviders[provider] > 0, Errors.LPAPR_PROVIDER_NOT_REGISTERED); _addressesProviders[provider] = 0; emit AddressesProviderUnregistered(provider); }
function unregisterAddressesProvider(address provider) external override onlyOwner { require(_addressesProviders[provider] > 0, Errors.LPAPR_PROVIDER_NOT_REGISTERED); _addressesProviders[provider] = 0; emit AddressesProviderUnregistered(provider); }
47,779
71
// Do not allow if gasprice is bigger than the maximum This is for fair-chance for all contributors, so no one can set a too-high transaction price and be able to buy earlier
require(tx.gasprice <= maxTxGas);
require(tx.gasprice <= maxTxGas);
42,814
4
// blind box token uri
string public blindBoxTokenURI;
string public blindBoxTokenURI;
40,432
46
// Returns whether or not there's a duplicate. Runs in O(n^2).A Array to search return Returns true if duplicate, false otherwise/
function hasDuplicate(address[] memory A) internal pure returns (bool) { if (A.length == 0) { return false; } for (uint256 i = 0; i < A.length - 1; i++) { for (uint256 j = i + 1; j < A.length; j++) { if (A[i] == A[j]) { return true;...
function hasDuplicate(address[] memory A) internal pure returns (bool) { if (A.length == 0) { return false; } for (uint256 i = 0; i < A.length - 1; i++) { for (uint256 j = i + 1; j < A.length; j++) { if (A[i] == A[j]) { return true;...
12,874
584
// 3 month tokens and fCash tokens settle at maturity
if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity; uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1);
if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity; uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1);
11,021
8
// returns the address of the staticAToken's lending pool / solhint-disable-next-line func-name-mixedcase
function LENDING_POOL() external view returns (ILendingPool);
function LENDING_POOL() external view returns (ILendingPool);
67,742
46
// allows token owner to list a token for lending. emits the Lending event. Requirements: ‼ contract should not be paused. ‼ caller must be the owner of the the token `tokenId + serialNo`. ‼ token with `tokenId + serialNo` must not be already listed for auction or fixed price. ‼ token with `tokenId + serialNo` must not...
function listForLending( uint256 tokenId, uint256 serialNo, uint32 lendingPeriod, uint104 amount
function listForLending( uint256 tokenId, uint256 serialNo, uint32 lendingPeriod, uint104 amount
9,744
179
// Function to change DHV staking pool in case of emergency./Caution! all actions for migration of the pool should be performed before this call./_stakingDHV Address of the DHV staking pool MasterChief./_pid DHV staking pool id.
function setStakingDHV(address _stakingDHV, uint256 _pid) external onlyRole(DEFAULT_ADMIN_ROLE) { stakingDHV = _stakingDHV; dhvPID = _pid; }
function setStakingDHV(address _stakingDHV, uint256 _pid) external onlyRole(DEFAULT_ADMIN_ROLE) { stakingDHV = _stakingDHV; dhvPID = _pid; }
34,574
62
// Function to set the protocol fee percentage.Only can be called by the pool factory. newFee Value of the new protocol fee. /
function setFee(uint256 newFee) external override { onlyFactory(); _setFee(newFee); }
function setFee(uint256 newFee) external override { onlyFactory(); _setFee(newFee); }
31,359
24
// Unwraps the contract's WETH9 balance and sends it to recipient as ETH./The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users./amountMinimum The minimum amount of WETH9 to unwrap/recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable
16,288
2
// INTERFACES /
IHomeFi public homeFi; IEvents public eventsInstance;
IHomeFi public homeFi; IEvents public eventsInstance;
29,563
0
// Event to log the main NFT token IDs used for a burn
event MainNFTUsedForBurn(address indexed user, uint256 indexed mainNFTId); event BurnWithoutMainNFT(address indexed user); constructor( address _defaultAdmin, string memory _name, string memory _symbol, address _royaltyRecipient, uint128 _royaltyBps, address ...
event MainNFTUsedForBurn(address indexed user, uint256 indexed mainNFTId); event BurnWithoutMainNFT(address indexed user); constructor( address _defaultAdmin, string memory _name, string memory _symbol, address _royaltyRecipient, uint128 _royaltyBps, address ...
4,482
141
// Abstract base contract for token sales. Handle- start and end dates- accepting investments- minimum funding goal and refund- various statistics during the crowdfund- different pricing strategies- different investment policies (require server side customer id, allow only whitelisted addresses)/
contract CrowdsaleExt is Allocatable, Haltable { /* Max investment count when we are still allowed to change the multisig address */ uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; using SafeMathLibExt for uint; /* The token we are selling */ FractionalERC20Ext public token; /* How w...
contract CrowdsaleExt is Allocatable, Haltable { /* Max investment count when we are still allowed to change the multisig address */ uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; using SafeMathLibExt for uint; /* The token we are selling */ FractionalERC20Ext public token; /* How w...
36,480
74
// Refund ether to the investors (invoke from only token)
function refund(address _to) public refundAllowed { require(msg.sender == tokenContractAddress); uint256 valueToReturn = balances[_to]; // update states balances[_to] = 0; weiRaised = weiRaised.sub(valueToReturn); _to.transfer(valueToReturn); }
function refund(address _to) public refundAllowed { require(msg.sender == tokenContractAddress); uint256 valueToReturn = balances[_to]; // update states balances[_to] = 0; weiRaised = weiRaised.sub(valueToReturn); _to.transfer(valueToReturn); }
25,859
7
// string memory kudoJSON = '{"who":' + tempKudos.who + '}'; string memory kudoJSONString = string(abi.encodePacked('{"giver":"',string(abi.encodePacked(tempKudos.giver)),'"}'));
string memory kudoSvgString = string(abi.encodePacked('{"image": "data:image/svg+xml;base64,',Base64.encode(bytes(imageSVG)),'"}'));
string memory kudoSvgString = string(abi.encodePacked('{"image": "data:image/svg+xml;base64,',Base64.encode(bytes(imageSVG)),'"}'));
16,858
81
// Executes a specified dispute's ruling./_disputeID The ID of the dispute.
function executeRuling(uint256 _disputeID) external { Dispute storage dispute = disputes[_disputeID]; if (dispute.period != Period.execution) revert NotExecutionPeriod(); if (dispute.ruled) revert RulingAlreadyExecuted(); (uint256 winningChoice, , ) = currentRuling(_disputeID); ...
function executeRuling(uint256 _disputeID) external { Dispute storage dispute = disputes[_disputeID]; if (dispute.period != Period.execution) revert NotExecutionPeriod(); if (dispute.ruled) revert RulingAlreadyExecuted(); (uint256 winningChoice, , ) = currentRuling(_disputeID); ...
20,453
253
// Get sender tokensHeld and amountOwed underlying from the cToken // Fail if the sender has a borrow balance // Fail if the sender is not permitted to redeem all of their tokens // Return true if the sender is not already ‘in’ the market // Set cToken account membership to false // Delete cToken from the account’s lis...
CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; }
CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; }
7,479
48
// Approve a trade (if the tokens involved in the trade are controlled) This function can only be called by a token controller of one of the tokens involved in the trade. Indeed, when a token smart contract is controlled by an owner, the owner can decide to open thesecondary market by: - Whitelisting the DVP smart cont...
function approveTrade(uint256 index, bool approved) external { Trade storage trade = _trades[index]; require(trade.state == State.Pending, "Trade is not pending"); (address tokenAddress1,,,,,) = abi.decode(trade.tokenData1, (address, uint256, bytes32, string, bool, bool)); (address ...
function approveTrade(uint256 index, bool approved) external { Trade storage trade = _trades[index]; require(trade.state == State.Pending, "Trade is not pending"); (address tokenAddress1,,,,,) = abi.decode(trade.tokenData1, (address, uint256, bytes32, string, bool, bool)); (address ...
29,322
659
// voting quorum not met -> close proposal without execution.
else if (_quorumMet(proposals[_proposalId], Staking(stakingAddress)) == false) { outcome = Outcome.QuorumNotMet; }
else if (_quorumMet(proposals[_proposalId], Staking(stakingAddress)) == false) { outcome = Outcome.QuorumNotMet; }
3,435
57
// When voting stage is over, any citizen can call this function to end the election and start a new mandate./
function End_Election()external override { require(In_election_stage, "Not in Election time"); uint num_mandate = Actual_Mandate; //uint new_num_mandate = num_mandate.add(1); In_election_stage=false; Actual_Mandate = num_mandate + 1; emit New_Mandate()...
function End_Election()external override { require(In_election_stage, "Not in Election time"); uint num_mandate = Actual_Mandate; //uint new_num_mandate = num_mandate.add(1); In_election_stage=false; Actual_Mandate = num_mandate + 1; emit New_Mandate()...
44,467
15
// fetch post
Post memory _post = posts[_id];
Post memory _post = posts[_id];
40,409
7
// Controla que solo se permita ejecución desde el Creador
modifier soloCreador{ require(msg.sender == creador, "Solo el creador de la tienda puede utilizar esta funcion"); _; }
modifier soloCreador{ require(msg.sender == creador, "Solo el creador de la tienda puede utilizar esta funcion"); _; }
17,275
3,582
// 1792
entry "bloodyminded" : ENG_ADJECTIVE
entry "bloodyminded" : ENG_ADJECTIVE
18,404
71
// After calling this function the {_defaultSecondaryTradingLimit}/ will apply to addresses from array `_accountsToReset`/ instead of there {individualTransactionCountLimit} (if they had it)/Allowed only for ComplianceOfficer./Function blocked when contract is paused./Function just changes flag {hasOwnTransactionCountL...
function resetTransactionCountLimitToDefault( address[] memory _accountsToReset ) external whenNotPaused onlyRole(COMPLIANCE_OFFICER_ROLE) { for (uint256 i = 0; i < _accountsToReset.length; i++) { userData[_accountsToReset[i]].hasOwnTransactionCountLimit = false; }
function resetTransactionCountLimitToDefault( address[] memory _accountsToReset ) external whenNotPaused onlyRole(COMPLIANCE_OFFICER_ROLE) { for (uint256 i = 0; i < _accountsToReset.length; i++) { userData[_accountsToReset[i]].hasOwnTransactionCountLimit = false; }
26,887
355
// just in case, role could be dropped after claims for immutability
function setClaimInterval(uint256 _startTime, uint256 _endTime) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); claimStart = _startTime; claimEnd = _endTime; }
function setClaimInterval(uint256 _startTime, uint256 _endTime) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); claimStart = _startTime; claimEnd = _endTime; }
24,030
6
// initialization function/ _totalAllocatedAmount total allocated amount/ _totalClaims total available claim count/ _startTime start time / _periodTimesPerClaim period time per claim
function initialize( uint256 _totalAllocatedAmount, uint256 _totalClaims, uint256 _startTime, uint256 _periodTimesPerClaim
function initialize( uint256 _totalAllocatedAmount, uint256 _totalClaims, uint256 _startTime, uint256 _periodTimesPerClaim
12,597
6
// TODO define a mapping to store unique solutions submitted
mapping (bytes32 => Solutions) unisolutions;
mapping (bytes32 => Solutions) unisolutions;
48,934
48
// Used to get the most recent vault for the token using the registry.return An instance of a VaultAPI /
function bestVault() public view virtual returns (VaultAPI) { return baseRouter.bestVault(address(token)); }
function bestVault() public view virtual returns (VaultAPI) { return baseRouter.bestVault(address(token)); }
29,037
16
// --- Administration ---/Modify uint256 parametersparameter Name of the parameter to modifydata New parameter value/
function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized { if (parameter == "validityFlag") { require(either(data == 1, data == 0), "ConverterFeed/invalid-data"); validityFlag = data; } else if (parameter == "scalingFactor") { require(data > 0, "...
function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized { if (parameter == "validityFlag") { require(either(data == 1, data == 0), "ConverterFeed/invalid-data"); validityFlag = data; } else if (parameter == "scalingFactor") { require(data > 0, "...
26,401
168
// Removes a value from a set. O(1). Returns true if the key was removed from the map, that is if it was present. /
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); }
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); }
696
8
// donationsCount: the total number of donations received by the campaign
uint256 public donationsCount;
uint256 public donationsCount;
44,681
67
// Yields the excess beyond the floor of x for positive numbers and the part of the number to the right/ of the radix point for negative numbers./Based on the odd function definition. https:en.wikipedia.org/wiki/Fractional_part/x The signed 59.18-decimal fixed-point number to get the fractional part of./result The frac...
function frac(int256 x) internal pure returns (int256 result) { unchecked { result = x % SCALE; } }
function frac(int256 x) internal pure returns (int256 result) { unchecked { result = x % SCALE; } }
8,431
45
// Get stored items of player for NFT
function getStorageItemIds( IERC721 _tokenAddress
function getStorageItemIds( IERC721 _tokenAddress
30,725
22
// Queue grant role transaction _target Address of contract or account to call _value Amount of ETH to send _data ABI encoded data send. _timestamp Timestamp after which the transaction can be executed. Requirements:- the caller must have the `DEFAULT_ADMIN_ROLE`. /
function queueGrantRoleTransaction(address _target, uint _value, bytes memory _data, uint256 _timestamp) public virtual onlyAdmin{ // Create tx id bytes32 txId = keccak256( abi.encode(_target, _value, _data, _timestamp) ); // Check transaction exists require(!gr...
function queueGrantRoleTransaction(address _target, uint _value, bytes memory _data, uint256 _timestamp) public virtual onlyAdmin{ // Create tx id bytes32 txId = keccak256( abi.encode(_target, _value, _data, _timestamp) ); // Check transaction exists require(!gr...
33,149
322
// be specified by overriding the virtual {_implementation} function. Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to adifferent contract through the {_delegate} function. The success and return data of the delegated call will be returned back to the call...
abstract contract Proxy {
abstract contract Proxy {
4,508
6
// POT refers to Powers of Tau
uint256 internal constant MAX_POT_DEGREE = (2 ** 28); uint256 internal constant POT_TREE_HEIGHT = 28;
uint256 internal constant MAX_POT_DEGREE = (2 ** 28); uint256 internal constant POT_TREE_HEIGHT = 28;
38,720
23
// Send fauna army to conquer certain field fieldID ID of the field attackerID ID of the fauna attacker minion/
function faunaConquer(uint fieldID, uint attackerID) external preCheck(fieldID) { require( !faunaOnField[attackerID], "Battlefield: the fauna minion already on field"); require( faunaArmy.ownerOf(attackerID) == msg.sender, "Battlefield: not the command...
function faunaConquer(uint fieldID, uint attackerID) external preCheck(fieldID) { require( !faunaOnField[attackerID], "Battlefield: the fauna minion already on field"); require( faunaArmy.ownerOf(attackerID) == msg.sender, "Battlefield: not the command...
2,054
37
// Calculates the account liquidity given a modified collateral, collateral amount, bond and debt amount,/ using the current prices provided by the oracle.//Works by summing up each collateral amount multiplied by the USD value of each unit and divided by its/ respective collateral ratio, then dividing the sum by the t...
function getHypotheticalAccountLiquidity( address account, IErc20 collateralModify, uint256 collateralAmountModify, IHToken bondModify, uint256 debtAmountModify ) external view returns (uint256 excessLiquidity, uint256 shortfallLiquidity);
function getHypotheticalAccountLiquidity( address account, IErc20 collateralModify, uint256 collateralAmountModify, IHToken bondModify, uint256 debtAmountModify ) external view returns (uint256 excessLiquidity, uint256 shortfallLiquidity);
5,693
296
// Return any remaining ether after the buy
uint256 remaining = msg.value.sub(price); if (remaining > 0) { (bool success, ) = msg.sender.call{value: remaining}("");
uint256 remaining = msg.value.sub(price); if (remaining > 0) { (bool success, ) = msg.sender.call{value: remaining}("");
30,400
203
// Set the oracle smart contract address./_oracle The new oracle smart contract address.
function setOracle(IOracle _oracle) external onlyGov { require(address(_oracle) != address(0), 'cannot set zero address oracle'); oracle = _oracle; emit SetOracle(address(_oracle)); }
function setOracle(IOracle _oracle) external onlyGov { require(address(_oracle) != address(0), 'cannot set zero address oracle'); oracle = _oracle; emit SetOracle(address(_oracle)); }
15,192
117
// allow unlocked transfers to special account
bool public returnsLocked;
bool public returnsLocked;
22,473
243
// DEPOSIT function
function deposit( address dfWallet, uint256 amountDAI, uint256 amountUSDC, uint256 amountWBTC, uint256 flashloanDAI, uint256 flashloanUSDC, FlashloanProvider flashloanType, address flashloanFromAddress
function deposit( address dfWallet, uint256 amountDAI, uint256 amountUSDC, uint256 amountWBTC, uint256 flashloanDAI, uint256 flashloanUSDC, FlashloanProvider flashloanType, address flashloanFromAddress
30,355
23
// if there is no authority, that means that contract doesn't have permission
if (currAuthority == address(0)) { return; }
if (currAuthority == address(0)) { return; }
12,407
5
// Set a flag if this is an NFI.
if (isNF) { type_ = type_ | TYPE_NF_BIT; }
if (isNF) { type_ = type_ | TYPE_NF_BIT; }
34,526
52
// return any unused funds balance
uint driver_balance_refund_due = driver_balance; driver_balance = 0; msg.sender.transfer(driver_balance_refund_due); agreement_state = LeaseAgreementStates.Ended; emit AgreementDriverFinalized(the_car, the_driver);
uint driver_balance_refund_due = driver_balance; driver_balance = 0; msg.sender.transfer(driver_balance_refund_due); agreement_state = LeaseAgreementStates.Ended; emit AgreementDriverFinalized(the_car, the_driver);
37,745
74
// require(_poolFee == 3000 || _poolFee == 500 || _poolFee == 10000, "Wrong poolFee!");
address poolAddress = computeAddress(_poolFee); poolMap[poolAddress] = true;
address poolAddress = computeAddress(_poolFee); poolMap[poolAddress] = true;
21,507
135
// Returns last active schain of a node. /
function getActiveSchain(uint nodeIndex) external view returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes3...
function getActiveSchain(uint nodeIndex) external view returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes3...
83,509
26
// return locking status userAddress address of to checkreturn locking status in true or false /
function getLockingStatus(address userAddress) external view returns(bool){ if (now < time[userAddress]){ return true; } else{ return false; } }
function getLockingStatus(address userAddress) external view returns(bool){ if (now < time[userAddress]){ return true; } else{ return false; } }
4,436
99
// If buyer or seller sets status fields and transfers either the premium or underlying /
function accept(uint optionUID) public { Option memory option = options[optionUID]; bool isSeller = option.seller == msg.sender || option.seller == address(0); bool isBuyer = option.buyer == msg.sender || option.buyer == address(0); require(isSeller || isBuyer, "accept(): Must either buyer or seller")...
function accept(uint optionUID) public { Option memory option = options[optionUID]; bool isSeller = option.seller == msg.sender || option.seller == address(0); bool isBuyer = option.buyer == msg.sender || option.buyer == address(0); require(isSeller || isBuyer, "accept(): Must either buyer or seller")...
36,099
165
// 更新利息
function accrueInterest() public onlyRestricted { uint256 currentBlockNumber = getBlockNumber(); uint256 accrualBlockNumberPrior = accrualBlockNumber; // 太短 零利息 if (accrualBlockNumberPrior == currentBlockNumber) { return; } uint256 cashPrior = controller...
function accrueInterest() public onlyRestricted { uint256 currentBlockNumber = getBlockNumber(); uint256 accrualBlockNumberPrior = accrualBlockNumber; // 太短 零利息 if (accrualBlockNumberPrior == currentBlockNumber) { return; } uint256 cashPrior = controller...
13,477
26
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned for accounts without code, i.e. `keccak256('')`
bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
2,305
7
// Bag left peaks one-by-one
for(uint i = numLeftPeaks; i > 0; i--) { bagger = keccak256(abi.encodePacked(bagger, proofItems[i-1])); }
for(uint i = numLeftPeaks; i > 0; i--) { bagger = keccak256(abi.encodePacked(bagger, proofItems[i-1])); }
47,113
173
// Removes a key-value pair from a map. O(1). Returns true if the key was removed from the map, that is if it was present. /
function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To dele...
function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To dele...
2,184
79
// low level token purchase function /
function buyTokens() public payable whenNotPaused { // Do not allow if gasprice is bigger than the maximum // This is for fair-chance for all contributors, so no one can // set a too-high transaction price and be able to buy earlier require(tx.gasprice <= maxTxGas); // valid ...
function buyTokens() public payable whenNotPaused { // Do not allow if gasprice is bigger than the maximum // This is for fair-chance for all contributors, so no one can // set a too-high transaction price and be able to buy earlier require(tx.gasprice <= maxTxGas); // valid ...
16,217
365
// Vote ended?
if (_isVoteOpen(vote_)) { return false; }
if (_isVoteOpen(vote_)) { return false; }
62,655
14
// buy Land with DAI using the merkle proof associated with it buyer address that perform the payment to address that will own the purchased Land reserved the reserved address (if any) x x coordinate of the Land y y coordinate of the Land size size of the pack of Land to purchase priceInSand price in SAND to purchase t...
function buyLandWithDAI( address buyer, address to, address reserved, uint256 x, uint256 y, uint256 size, uint256 priceInSand, bytes32 salt, uint256[] calldata assetIds,
function buyLandWithDAI( address buyer, address to, address reserved, uint256 x, uint256 y, uint256 size, uint256 priceInSand, bytes32 salt, uint256[] calldata assetIds,
30,617
3
// Airdrop /
contract Airdrop is Pausable { using SafeMath for uint256; GenbbyToken public token; uint256 public tokens_sold; uint256 public constant decimals = 18; uint256 public constant factor = 10 ** decimals; uint256 public constant total_tokens = 500000 * factor; // 1% 5 % hard cap event Drop(a...
contract Airdrop is Pausable { using SafeMath for uint256; GenbbyToken public token; uint256 public tokens_sold; uint256 public constant decimals = 18; uint256 public constant factor = 10 ** decimals; uint256 public constant total_tokens = 500000 * factor; // 1% 5 % hard cap event Drop(a...
47,290
15
// Store NFT info
mapping(address => NftInfo) internal _nftInfo;
mapping(address => NftInfo) internal _nftInfo;
41,351
16
// Set the owner of this Smart Walletslot for owner = bytes32(uint256(keccak256('eip1967.proxy.owner')) - 1) = a7b53796fd2d99cb1f5ae019b54f9e024446c3d12b483f733ccc62ed04eb126a
bytes32 ownerCell = keccak256(abi.encodePacked(owner)); assembly { sstore( 0xa7b53796fd2d99cb1f5ae019b54f9e024446c3d12b483f733ccc62ed04eb126a, ownerCell ) }
bytes32 ownerCell = keccak256(abi.encodePacked(owner)); assembly { sstore( 0xa7b53796fd2d99cb1f5ae019b54f9e024446c3d12b483f733ccc62ed04eb126a, ownerCell ) }
24,964
41
// Restore
mstore(pos1, temp1) mstore(pos2, temp2) mstore(pos3, temp3)
mstore(pos1, temp1) mstore(pos2, temp2) mstore(pos3, temp3)
8,674
87
// Getter for the terminated state of the futurereturn true if this vault is terminated /
function isTerminated() public view returns (bool) { return terminated; }
function isTerminated() public view returns (bool) { return terminated; }
61,134
0
// help variables
address internal lastPlayed; uint internal turnsTaken; bool public gameOver; address payable internal winner;
address internal lastPlayed; uint internal turnsTaken; bool public gameOver; address payable internal winner;
51,079
12
// Claim RGT/set timestamp for initial transfer of RDPT to `account`
if (balanceOf(account) > 0) rariGovernanceTokenDistributor.distributeRgt(account, IRariGovernanceTokenDistributor.RariPool.Stable); else rariGovernanceTokenDistributor.beforeFirstPoolTokenTransferIn(account, IRariGovernanceTokenDistributor.RariPool.Stable);
if (balanceOf(account) > 0) rariGovernanceTokenDistributor.distributeRgt(account, IRariGovernanceTokenDistributor.RariPool.Stable); else rariGovernanceTokenDistributor.beforeFirstPoolTokenTransferIn(account, IRariGovernanceTokenDistributor.RariPool.Stable);
13,291
310
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
set._values[toDeleteIndex] = lastvalue;
359
37
// function addAttributes ( tuple[] _attributes ) external;
function addContractToWhitelist(address _contract) external; function addMinterRole(address _address) external; function addToPreSaleList(address[] memory entries) external;
function addContractToWhitelist(address _contract) external; function addMinterRole(address _address) external; function addToPreSaleList(address[] memory entries) external;
34,666
175
// ToDaMoon with Governance.
contract ToDaMoon is BEP20('Moon Token', 'MOON') { /// @dev Creates `_amount` token to `_to`. Must only be called by the owner (BullFarm). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function...
contract ToDaMoon is BEP20('Moon Token', 'MOON') { /// @dev Creates `_amount` token to `_to`. Must only be called by the owner (BullFarm). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function...
11,442
91
// Removes a NFT from owner.Use and override this function with caution. Wrong usage can have serious consequences._from Address from wich we want to remove the NFT._tokenId Which NFT we want to remove./
function _removeNFToken( address _from, uint256 _tokenId ) internal virtual { require(idToOwner[_tokenId] == _from); ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from] - 1; delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTok...
function _removeNFToken( address _from, uint256 _tokenId ) internal virtual { require(idToOwner[_tokenId] == _from); ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from] - 1; delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTok...
651
319
// Gets the amount1 delta between two prices/Calculates liquidity(sqrt(upper) - sqrt(lower))/sqrtRatioAX96 A sqrt price/sqrtRatioBX96 Another sqrt price/liquidity The amount of usable liquidity/roundUp Whether to round the amount up, or down/ return amount1 Amount of token1 required to cover a position of size liquidit...
function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp
function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp
3,900
0
// 用于标记余额存储的情况
mapping(address => bool) private isIncluded; address[] private included;
mapping(address => bool) private isIncluded; address[] private included;
8,502
271
// voteInfo returns the vote and the amount of reputation of the user committed to this proposal _proposalId the ID of the proposal _voter the address of the voterreturn uint256 vote - the voters vote uint256 reputation - amount of reputation committed by _voter to _proposalId /
function voteInfo(bytes32 _proposalId, address _voter) external view returns(uint, uint) { Voter memory voter = proposals[_proposalId].voters[_voter]; return (voter.vote, voter.reputation); }
function voteInfo(bytes32 _proposalId, address _voter) external view returns(uint, uint) { Voter memory voter = proposals[_proposalId].voters[_voter]; return (voter.vote, voter.reputation); }
11,173
96
// move v to r position
mstore(add(_signature, 0x20), v) result := and( and(
mstore(add(_signature, 0x20), v) result := and( and(
31,753
80
// Timestamps when token started to sell
uint256 public openTime = block.timestamp;
uint256 public openTime = block.timestamp;
25,646
317
// cumulate the balance of the sender
(, uint256 fromBalance, uint256 fromBalanceIncrease, uint256 fromIndex ) = cumulateBalanceInternal(_from);
(, uint256 fromBalance, uint256 fromBalanceIncrease, uint256 fromIndex ) = cumulateBalanceInternal(_from);
51,477
11
// _name = "Yearn Finance Insurance";_symbol = "YFIn";
_name = "Yearn Finance Insurance"; _symbol = "YFIn"; _decimals = 18; _totalSupply = 30000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply);
_name = "Yearn Finance Insurance"; _symbol = "YFIn"; _decimals = 18; _totalSupply = 30000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply);
10,047
0
// A generic resolver interface which includes all the functions including the ones deprecated /
interface Resolver{ event AddrChanged(bytes32 indexed node, address a); event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 ...
interface Resolver{ event AddrChanged(bytes32 indexed node, address a); event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 ...
26,380
11
// we first set the allowance to the uniswap router
if (Token(params.tokenIn).allowance(address(this), UNISWAP_V3_SWAP_ROUTER_ADDRESS) < params.amountIn) { safeApproveInternal(params.tokenIn, UNISWAP_V3_SWAP_ROUTER_ADDRESS, type(uint).max); }
if (Token(params.tokenIn).allowance(address(this), UNISWAP_V3_SWAP_ROUTER_ADDRESS) < params.amountIn) { safeApproveInternal(params.tokenIn, UNISWAP_V3_SWAP_ROUTER_ADDRESS, type(uint).max); }
1,374
81
// Allow to spend foundation tokens only after 48 weeks after minting is finished
return now < mintingStopDate + 48 weeks;
return now < mintingStopDate + 48 weeks;
14,089
2
// Get this contract reward's from rewarderpool.
uint256 contractReward = TheRewarderPool(target).rewardToken().balanceOf(address(this));
uint256 contractReward = TheRewarderPool(target).rewardToken().balanceOf(address(this));
42,958
122
// Liquidate up to `_amountNeeded` of `want` of this strategy's positions,irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.This function should return the amount of `want` tokens made available by theliquidation. If there is a difference between them, `_loss` indicates whether thediffere...
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
1,488
58
// Constructor //Constructs the `EnhancedAppealableArbitrator` contract. _arbitrationPrice The amount to be paid for arbitration. _arbitrator The back up arbitrator. _arbitratorExtraData Not used by this contract. _timeOut The time out for the appeal period./
constructor( uint _arbitrationPrice, Arbitrator _arbitrator, bytes memory _arbitratorExtraData, uint _timeOut
constructor( uint _arbitrationPrice, Arbitrator _arbitrator, bytes memory _arbitratorExtraData, uint _timeOut
15,584
33
// This function returns whether or not a given user is allowed to trade a given amount and removing the staked amount from their balance if they are staked_user address of user_amount to check if the user can spend return true if they are allowed to spend the amount being checked/
function allowedToTrade(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _amount) public view returns (bool) { if (self.stakerDetails[_user].currentStatus != 0 && self.stakerDetails[_user].currentStatus < 5) { //Subtracts the stakeAmount from balance if the _user is staked...
function allowedToTrade(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _amount) public view returns (bool) { if (self.stakerDetails[_user].currentStatus != 0 && self.stakerDetails[_user].currentStatus < 5) { //Subtracts the stakeAmount from balance if the _user is staked...
25,441
55
// returns the number of whitelisted pools return number of whitelisted pools/
function whitelistedPoolCount() external view returns (uint256) { return poolWhitelist.length; }
function whitelistedPoolCount() external view returns (uint256) { return poolWhitelist.length; }
23,137
9
// Fallback function for balancer flashloan. Fallback function for balancer flashloan. _amounts list of amounts for the corresponding assets or amount of ether to borrow as collateral for flashloan. _fees list of fees for the corresponding addresses for flashloan. _data extra data passed(includes route info aswell)./
function receiveFlashLoan( IERC20[] memory, uint256[] memory _amounts, uint256[] memory _fees, bytes memory _data
function receiveFlashLoan( IERC20[] memory, uint256[] memory _amounts, uint256[] memory _fees, bytes memory _data
41,726
220
// Override isApprovedForAll to allowlist user's OpenSea proxy accounts to enable gas-less listings. /
function isApprovedForAll(address owner, address operator) public view override returns (bool)
function isApprovedForAll(address owner, address operator) public view override returns (bool)
4,568
396
// Set the state of the OpenSea operator filter value Flag indicating if the operator filter should be applied to transfers and approvals /
function setOperatorFilteringEnabled(bool value)
function setOperatorFilteringEnabled(bool value)
8,973
5
// Ensure sending is to valid address! 0x0 address cane be used to burn()
require(_to != address(0)); balanceOf[_from] = balanceOf[_from] - (_value); balanceOf[_to] = balanceOf[_to] + (_value); emit Transfer(_from, _to, _value);
require(_to != address(0)); balanceOf[_from] = balanceOf[_from] - (_value); balanceOf[_to] = balanceOf[_to] + (_value); emit Transfer(_from, _to, _value);
44,453
10
// Sets the Dev contract /
event NewDev(address oldDev, address newDev);
event NewDev(address oldDev, address newDev);
10,170
110
// Get minimum amount of loan asset get after swapping collateral asset.
uint256 minAmount = Util.calcMinAmount(globals, address(collateralAsset), liquidityAsset, liquidationAmt);
uint256 minAmount = Util.calcMinAmount(globals, address(collateralAsset), liquidityAsset, liquidationAmt);
1,555
10
// FinaLounge is the coolest lounge in the office. You come in with some Fina, and leave with more! The longer you stay, the more Fina you get. This contract handles swapping to and from xFina, FinaSwap's staking token.
contract FinaLounge is ERC20("FinaLounge", "xFNA"){ using SafeMath for uint256; IERC20 public fina; // Define the Fina token contract constructor(IERC20 _fina) public { fina = _fina; } // Enter the lounge. Pay some FNAs. Earn some shares. // Locks Fina and mints xFina function ...
contract FinaLounge is ERC20("FinaLounge", "xFNA"){ using SafeMath for uint256; IERC20 public fina; // Define the Fina token contract constructor(IERC20 _fina) public { fina = _fina; } // Enter the lounge. Pay some FNAs. Earn some shares. // Locks Fina and mints xFina function ...
11,923
0
// JUST FOR TESTING - ITS OKAY TO REMOVE ALL OF THESE VARS
address public lastTokenBorrow; uint public lastAmount; address public lastTokenPay; uint public lastamountToRepay; bytes public lastUserData;
address public lastTokenBorrow; uint public lastAmount; address public lastTokenPay; uint public lastamountToRepay; bytes public lastUserData;
46,804