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
30
// Claim all unclaimed tokens + stake them Given a merkle proof of (index, account, totalEarned), claim allunclaimed tokens. Unclaimed tokens are the difference between the totalearned tokens (provided in the merkle tree) and those that have beeneither claimed or slashed. If no tokens are claimable, this function will revert. index Claim index account Account for claim totalEarned Total lifetime amount of tokens earned by account merkleProof Merkle proof /
function claimAndStake(uint256 index, address account, uint256 totalEarned, bytes32[] calldata merkleProof) external override { require(msg.sender == account, "MerkleDistributorSEV: Cannot collect rewards"); require(token.allowance(address(this), address(edenNetwork)) == 0, "MerkleDistributorSEV: allowance > 0"); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(index, account, totalEarned)); require(MerkleProof.verify(merkleProof, merkleRoot, node), "MerkleDistributorSEV: Invalid proof"); // Calculate the claimable balance uint256 alreadyDistributed = accountState[account].totalClaimed + accountState[account].totalSlashed; require(totalEarned > alreadyDistributed, "MerkleDistributorSEV: Nothing claimable"); uint256 claimable = totalEarned - alreadyDistributed; emit Claimed(index, totalEarned, account, claimable); // Apply account changes and stake unclaimed tokens _increaseAccount(account, claimable, 0); token.approve(address(edenNetwork), claimable); edenNetwork.stakeFor(msg.sender, uint128(claimable)); }
function claimAndStake(uint256 index, address account, uint256 totalEarned, bytes32[] calldata merkleProof) external override { require(msg.sender == account, "MerkleDistributorSEV: Cannot collect rewards"); require(token.allowance(address(this), address(edenNetwork)) == 0, "MerkleDistributorSEV: allowance > 0"); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(index, account, totalEarned)); require(MerkleProof.verify(merkleProof, merkleRoot, node), "MerkleDistributorSEV: Invalid proof"); // Calculate the claimable balance uint256 alreadyDistributed = accountState[account].totalClaimed + accountState[account].totalSlashed; require(totalEarned > alreadyDistributed, "MerkleDistributorSEV: Nothing claimable"); uint256 claimable = totalEarned - alreadyDistributed; emit Claimed(index, totalEarned, account, claimable); // Apply account changes and stake unclaimed tokens _increaseAccount(account, claimable, 0); token.approve(address(edenNetwork), claimable); edenNetwork.stakeFor(msg.sender, uint128(claimable)); }
50,803
6
// initialise state numberOfMotions = 0;
changeOrganisationName(_organisationName);
changeOrganisationName(_organisationName);
4,308
84
// return Whether or not a flag is set for a given proposal proposalId The proposal to check against flag flag The flag to check in the proposal /
function getProposalFlag(bytes32 proposalId, ProposalFlag flag) public view returns (bool)
function getProposalFlag(bytes32 proposalId, ProposalFlag flag) public view returns (bool)
63,442
46
// Prefix the calldata with a struct offset, which points to just one word over.
mstore(add(encodedStructArgs, 32), 32)
mstore(add(encodedStructArgs, 32), 32)
54,616
57
// Generate offsets into symbol table for each length for sorting
offs[1] = 0; for (len = 1; len < MAXBITS; len++) { offs[len + 1] = offs[len] + h.counts[len]; }
offs[1] = 0; for (len = 1; len < MAXBITS; len++) { offs[len + 1] = offs[len] + h.counts[len]; }
1,943
8
// Yearn Vault
function pricePerShare() external view returns (uint256);
function pricePerShare() external view returns (uint256);
26,689
246
// ClosePositionDelegator dYdX Interface that smart contracts must implement in order to let other addresses close a positionowned by the smart contract, allowing more complex logic to control positions. NOTE: Any contract implementing this interface should also use OnlyMargin to control accessto these functions /
interface ClosePositionDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call closePosition(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that (at-most) the specified amount of the position * was successfully closed. * * @param closer Address of the caller of the closePosition() function * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param positionId Unique ID of the position * @param requestedAmount Requested principal amount of the position to close * @return 1) This address to accept, a different address to ask that contract * 2) The maximum amount that this contract is allowing */ function closeOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external /* onlyMargin */ returns (address, uint256); }
interface ClosePositionDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call closePosition(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that (at-most) the specified amount of the position * was successfully closed. * * @param closer Address of the caller of the closePosition() function * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param positionId Unique ID of the position * @param requestedAmount Requested principal amount of the position to close * @return 1) This address to accept, a different address to ask that contract * 2) The maximum amount that this contract is allowing */ function closeOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external /* onlyMargin */ returns (address, uint256); }
72,284
233
// Dev fund has xx% locked during the starting bonus period. After which locked funds drip out linearly each block over 3 years.
if (block.number <= FINISH_BONUS_AT_BLOCK) { Poll.lock(address(devaddr), PollForDev.mul(75).div(100)); }
if (block.number <= FINISH_BONUS_AT_BLOCK) { Poll.lock(address(devaddr), PollForDev.mul(75).div(100)); }
15,946
27
// Revert: default plugin exists for function; use updatePlugin instead.
try IPluginMap(pluginMap).getPluginForFunction(_plugin.functionSelector) returns (address) { revert("Router: default plugin exists for function."); } catch {
try IPluginMap(pluginMap).getPluginForFunction(_plugin.functionSelector) returns (address) { revert("Router: default plugin exists for function."); } catch {
6,200
19
// Returns the TTL of a node, and any records associated with it. node The specified node.return ttl of the node. /
function ttl(bytes32 node) public override view returns (uint64) { return records[node].ttl; }
function ttl(bytes32 node) public override view returns (uint64) { return records[node].ttl; }
13,998
4
// ako je balans korisnika koji je pozvao ovu funkciju jednak nuli, zaustavlja se izvrsavanje
require(hasDeposit[msg.sender] == true);
require(hasDeposit[msg.sender] == true);
35,070
1
// Add OKRAdd an OKR for the signer /
function addOKR(
function addOKR(
17,127
9
// GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract./Stefan George - <stefan@gnosis.io>/Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy { // masterCopy always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated. // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt` address internal masterCopy; /// @dev Constructor function sets address of master copy contract. /// @param _masterCopy Master copy address. constructor(address _masterCopy) public { require(_masterCopy != address(0), "Invalid master copy address provided"); masterCopy = _masterCopy; } /// @dev Fallback function forwards all transactions and returns all received return data. function () external payable { // solium-disable-next-line security/no-inline-assembly assembly { let masterCopy := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff) // 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) { mstore(0, masterCopy) return(0, 0x20) } calldatacopy(0, 0, calldatasize()) let success := delegatecall(gas, masterCopy, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) if eq(success, 0) { revert(0, returndatasize()) } return(0, returndatasize()) } } }
contract GnosisSafeProxy { // masterCopy always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated. // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt` address internal masterCopy; /// @dev Constructor function sets address of master copy contract. /// @param _masterCopy Master copy address. constructor(address _masterCopy) public { require(_masterCopy != address(0), "Invalid master copy address provided"); masterCopy = _masterCopy; } /// @dev Fallback function forwards all transactions and returns all received return data. function () external payable { // solium-disable-next-line security/no-inline-assembly assembly { let masterCopy := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff) // 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) { mstore(0, masterCopy) return(0, 0x20) } calldatacopy(0, 0, calldatasize()) let success := delegatecall(gas, masterCopy, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) if eq(success, 0) { revert(0, returndatasize()) } return(0, returndatasize()) } } }
7,186
4
// SafeMath Unsigned math operations with safety checks that revert on error. /
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } }
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } }
20,530
13
// Execution part 2/2
_transferNonFungibleToken(makerAsk.collection, makerAsk.signer, takerBid.taker, tokenId, amount); emit TakerBid( askHash, makerAsk.nonce, takerBid.taker, makerAsk.signer, makerAsk.strategy, makerAsk.currency, makerAsk.collection,
_transferNonFungibleToken(makerAsk.collection, makerAsk.signer, takerBid.taker, tokenId, amount); emit TakerBid( askHash, makerAsk.nonce, takerBid.taker, makerAsk.signer, makerAsk.strategy, makerAsk.currency, makerAsk.collection,
31,285
114
// Send equal ERC20 tokens amount to multiple contracts//_token The token to send/_addresses Array of addresses to send to/_amount Tokens amount to send to each address
function multiTransferTokenEqual_71p( address _token, address[] calldata _addresses, uint256 _amount ) payable external whenNotPaused
function multiTransferTokenEqual_71p( address _token, address[] calldata _addresses, uint256 _amount ) payable external whenNotPaused
27,171
357
// Increase witness memory position
mpush(Stack_Witnesses, safeAdd(mstack(Stack_Witnesses), WitnessSize))
mpush(Stack_Witnesses, safeAdd(mstack(Stack_Witnesses), WitnessSize))
21,637
14
// given a token supply, connector balance, weight and a deposit amount (in the connector token), calculates the return for a given conversion (in the main token) Formula:Return = _supply((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1)_supplytoken total supply _connectorBalancetotal connector balance _connectorWeight connector weight, represented in ppm, 1-1000000 _depositAmount deposit amount, in connector tokenreturn purchase return amount /
function calculatePurchaseReturn( uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount ) public view returns (uint256)
function calculatePurchaseReturn( uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount ) public view returns (uint256)
23,227
3
// return next reward halve block number /
function getNextRewardChangeBlock() external returns (uint256);
function getNextRewardChangeBlock() external returns (uint256);
13,947
64
// this event is emitted when an Identity has been updatedthe event is emitted by the 'updateIdentity' function`oldIdentity` is the old Identity contract's address to update`newIdentity` is the new Identity contract's/
event IdentityModified(IIdentity indexed oldIdentity, IIdentity indexed newIdentity);
event IdentityModified(IIdentity indexed oldIdentity, IIdentity indexed newIdentity);
15,131
50
// reward who Draw Code 0.01 ether
_addr.transfer(COMMON_REWARD_AMOUNT); emit onReward(_addr, Mildatasets.RewardType.DRAW, COMMON_REWARD_AMOUNT);
_addr.transfer(COMMON_REWARD_AMOUNT); emit onReward(_addr, Mildatasets.RewardType.DRAW, COMMON_REWARD_AMOUNT);
21,248
85
// User redeems mTokens in exchange for the underlying asset Assumes interest has already been accrued up to the current block redeemer The address of the account which is redeeming the tokens redeemTokensIn The number of mTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) redeemAmountIn The number of underlying tokens to receive from redeeming mTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "redeemFresh_missing_zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = moartroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REDEEM_MOARTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } /* Fail if user tries to redeem more than he has locked with c-op*/ // TODO: update error codes uint newTokensAmount = div_(mul_(vars.accountTokensNew, vars.exchangeRateMantissa), 1e18); if (newTokensAmount < moartroller.getUserLockedAmount(this, redeemer)) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ moartroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); }
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "redeemFresh_missing_zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = moartroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REDEEM_MOARTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } /* Fail if user tries to redeem more than he has locked with c-op*/ // TODO: update error codes uint newTokensAmount = div_(mul_(vars.accountTokensNew, vars.exchangeRateMantissa), 1e18); if (newTokensAmount < moartroller.getUserLockedAmount(this, redeemer)) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ moartroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); }
32,615
31
// FOK (fill or kill) ask. Must have a matching bid for the total amonut to succed. /
function fokAskRecursion(uint _eth, uint _unitPrice) internal { require(msg.value > 0 && _unitPrice > 0, "ETH and unitPrice must be more than zero!"); uint e = _eth; uint t = e.mul(_unitPrice); uint l = bidDict.length; address o; for (uint i=0; i<l; i++) { if (_unitPrice == bids[i].unitPrice) { o = bids[i].owner; if (e >= bids[i].eth) { e = bids[i].eth; t = e.mul(_unitPrice); bids[i].eth = 0; bids[i].unitPrice = 0; bids[i].owner = 0; bidDict[i] = 0; } else { bids[i].eth = bids[i].eth.sub(e); } balances[msg.sender] = balances[msg.sender].add(t); o.transfer(e); if (e < _eth) { fokAskRecursion(_eth.sub(e), _unitPrice); } return; } } revert("No matching bids!"); }
function fokAskRecursion(uint _eth, uint _unitPrice) internal { require(msg.value > 0 && _unitPrice > 0, "ETH and unitPrice must be more than zero!"); uint e = _eth; uint t = e.mul(_unitPrice); uint l = bidDict.length; address o; for (uint i=0; i<l; i++) { if (_unitPrice == bids[i].unitPrice) { o = bids[i].owner; if (e >= bids[i].eth) { e = bids[i].eth; t = e.mul(_unitPrice); bids[i].eth = 0; bids[i].unitPrice = 0; bids[i].owner = 0; bidDict[i] = 0; } else { bids[i].eth = bids[i].eth.sub(e); } balances[msg.sender] = balances[msg.sender].add(t); o.transfer(e); if (e < _eth) { fokAskRecursion(_eth.sub(e), _unitPrice); } return; } } revert("No matching bids!"); }
15,243
14
// Cancel one order (off chain as well)
function cancelOrder(uint256 _orderId) external;
function cancelOrder(uint256 _orderId) external;
10,626
235
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
_eventData_.compressedData += 10000000000000000000000000000000;
59,057
0
// enables the creator of the contract to desctroy it /
function destroy() public isOwner { selfdestruct(owner); }
function destroy() public isOwner { selfdestruct(owner); }
22,716
103
// _currentRate The current exchange rate, an 18 decimal fixed point number. _targetRate The current target rate, an 18 decimal fixed point number.return If the rate is within the deviation threshold from the target rate, returns true.Otherwise, returns false. /
function withinDeviationThreshold(uint256 _currentRate, uint256 _targetRate) internal view returns (bool)
function withinDeviationThreshold(uint256 _currentRate, uint256 _targetRate) internal view returns (bool)
78,753
56
// CRITICAL TO SETUP /
modifier requireContractsSet() { require( address(raw) != address(0) && address(pirateNFT) != address(0) && address(colonistNFT) != address(0) && address(pytheas) != address(0) && address(orbital) != address(0) && address(imperialGuild) != address(0), "Contracts not set" ); _; }
modifier requireContractsSet() { require( address(raw) != address(0) && address(pirateNFT) != address(0) && address(colonistNFT) != address(0) && address(pytheas) != address(0) && address(orbital) != address(0) && address(imperialGuild) != address(0), "Contracts not set" ); _; }
49,280
134
// Check when this NFT is allowed to be withdrawn. If 0, set it.
uint256 withdrawalTime = pendingWithdrawals[_nftId]; if (withdrawalTime == 0) { require(nftOwners[_nftId] == msg.sender, "Sender does not own this NFT."); (/*coverId*/, uint8 coverStatus, uint256 sumAssured, /*uint16 coverPeriod*/, /*uint256 validUntil*/, address scAddress,
uint256 withdrawalTime = pendingWithdrawals[_nftId]; if (withdrawalTime == 0) { require(nftOwners[_nftId] == msg.sender, "Sender does not own this NFT."); (/*coverId*/, uint8 coverStatus, uint256 sumAssured, /*uint16 coverPeriod*/, /*uint256 validUntil*/, address scAddress,
51,021
84
// iOVM_ChainStorageContainer /
interface iOVM_ChainStorageContainer { /******************** * Public Functions * ********************/ /** * Sets the container's global metadata field. We're using `bytes27` here because we use five * bytes to maintain the length of the underlying data structure, meaning we have an extra * 27 bytes to store arbitrary data. * @param _globalMetadata New global metadata to set. */ function setGlobalMetadata( bytes27 _globalMetadata ) external; /** * Retrieves the container's global metadata field. * @return Container global metadata field. */ function getGlobalMetadata() external view returns ( bytes27 ); /** * Retrieves the number of objects stored in the container. * @return Number of objects in the container. */ function length() external view returns ( uint256 ); /** * Pushes an object into the container. * @param _object A 32 byte value to insert into the container. */ function push( bytes32 _object ) external; /** * Pushes an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _object A 32 byte value to insert into the container. * @param _globalMetadata New global metadata for the container. */ function push( bytes32 _object, bytes27 _globalMetadata ) external; /** * Retrieves an object from the container. * @param _index Index of the particular object to access. * @return 32 byte object value. */ function get( uint256 _index ) external view returns ( bytes32 ); /** * Removes all objects after and including a given index. * @param _index Object index to delete from. */ function deleteElementsAfterInclusive( uint256 _index ) external; /** * Removes all objects after and including a given index. Also allows setting the global * metadata field. * @param _index Object index to delete from. * @param _globalMetadata New global metadata for the container. */ function deleteElementsAfterInclusive( uint256 _index, bytes27 _globalMetadata ) external; }
interface iOVM_ChainStorageContainer { /******************** * Public Functions * ********************/ /** * Sets the container's global metadata field. We're using `bytes27` here because we use five * bytes to maintain the length of the underlying data structure, meaning we have an extra * 27 bytes to store arbitrary data. * @param _globalMetadata New global metadata to set. */ function setGlobalMetadata( bytes27 _globalMetadata ) external; /** * Retrieves the container's global metadata field. * @return Container global metadata field. */ function getGlobalMetadata() external view returns ( bytes27 ); /** * Retrieves the number of objects stored in the container. * @return Number of objects in the container. */ function length() external view returns ( uint256 ); /** * Pushes an object into the container. * @param _object A 32 byte value to insert into the container. */ function push( bytes32 _object ) external; /** * Pushes an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _object A 32 byte value to insert into the container. * @param _globalMetadata New global metadata for the container. */ function push( bytes32 _object, bytes27 _globalMetadata ) external; /** * Retrieves an object from the container. * @param _index Index of the particular object to access. * @return 32 byte object value. */ function get( uint256 _index ) external view returns ( bytes32 ); /** * Removes all objects after and including a given index. * @param _index Object index to delete from. */ function deleteElementsAfterInclusive( uint256 _index ) external; /** * Removes all objects after and including a given index. Also allows setting the global * metadata field. * @param _index Object index to delete from. * @param _globalMetadata New global metadata for the container. */ function deleteElementsAfterInclusive( uint256 _index, bytes27 _globalMetadata ) external; }
63,291
254
// use default if not set
payloadSizeLimit = DEFAULT_PAYLOAD_SIZE_LIMIT;
payloadSizeLimit = DEFAULT_PAYLOAD_SIZE_LIMIT;
16,780
66
// The RequestFactory which produces requests for this scheduler.
address public factoryAddress;
address public factoryAddress;
10,843
207
// Retrieves the implementation contract address, mirrored token image.return impl token image address. /
function implementation() public view override returns (address impl) { assembly { impl := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) } }
function implementation() public view override returns (address impl) { assembly { impl := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) } }
8,962
74
// Get identity wallet
function getIdentityWallet(address _id) public view returns (address) { return identities[_id].wallet; }
function getIdentityWallet(address _id) public view returns (address) { return identities[_id].wallet; }
33,296
9
// Locks the `amount` to be spent by `spender`.This `amount` does not override previous amount, it adds on top of it. This action ensures that allowed spender can fully spend the allowed fundsand that the owner cannot use these funds to send them somewhere else.
* Emits a {LockedFunds} event. * * @param owner - Account from where the funds are locked * @param spender - Account who locked the funds for spending * @param amount - The amount that will be locked */ function lockAmountFrom( address owner, address spender, uint256 amount ) external virtual { require(spender == _msgSender(), "ERC20LockedFunds: only spender can request lock"); require( allowance(owner, spender) >= amount + _lockedAccountBalanceMap[owner][spender], "ERC20LockedFunds: lock amount exceeds allowance" ); _lockAmount(owner, spender, amount); }
* Emits a {LockedFunds} event. * * @param owner - Account from where the funds are locked * @param spender - Account who locked the funds for spending * @param amount - The amount that will be locked */ function lockAmountFrom( address owner, address spender, uint256 amount ) external virtual { require(spender == _msgSender(), "ERC20LockedFunds: only spender can request lock"); require( allowance(owner, spender) >= amount + _lockedAccountBalanceMap[owner][spender], "ERC20LockedFunds: lock amount exceeds allowance" ); _lockAmount(owner, spender, amount); }
23,236
211
// NOTE: BADGER is emitted through the tree
if (token == BADGER){ _sendBadgerToTree(); } else {
if (token == BADGER){ _sendBadgerToTree(); } else {
25,905
298
// Add the address for Gianky tokens
address public whitelistAddress_alpha; address private constant WBNB_ADDRESS = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c; IERC20 public wbnbToken;
address public whitelistAddress_alpha; address private constant WBNB_ADDRESS = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c; IERC20 public wbnbToken;
26,639
11
// Otherwise, use the previously stored number from the matrix.
offset = tokenMatrix[random];
offset = tokenMatrix[random];
20,309
10
// Contract address of RealAssetNFT contract (v1)
address public parentContractAddress;
address public parentContractAddress;
2,575
111
// Returns the amount out received for a given exact input but for a swap of a single pool/tokenIn The token being swapped in/tokenOut The token being swapped out/fee The fee of the token pool to consider for the pair/amountIn The desired input amount/sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap/ return amountOut The amount of `tokenOut` that would be received
function quoteExactInputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountOut);
function quoteExactInputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountOut);
15,415
15
// Computes the L2 block number given a target L2 block timestamp. _l2timestamp The L2 block timestamp of the target block. /
function computeL2BlockNumber(uint256 _l2timestamp) external view returns (uint256) { require( _l2timestamp >= STARTING_BLOCK_TIMESTAMP, "Timestamp prior to startingBlockTimestamp" ); // For the first block recorded (ie. _l2timestamp = STARTING_BLOCK_TIMESTAMP), the // L2BlockNumber should be HISTORICAL_TOTAL_BLOCKS + 1. unchecked { return HISTORICAL_TOTAL_BLOCKS + 1 + ((_l2timestamp - STARTING_BLOCK_TIMESTAMP) / L2_BLOCK_TIME); } }
function computeL2BlockNumber(uint256 _l2timestamp) external view returns (uint256) { require( _l2timestamp >= STARTING_BLOCK_TIMESTAMP, "Timestamp prior to startingBlockTimestamp" ); // For the first block recorded (ie. _l2timestamp = STARTING_BLOCK_TIMESTAMP), the // L2BlockNumber should be HISTORICAL_TOTAL_BLOCKS + 1. unchecked { return HISTORICAL_TOTAL_BLOCKS + 1 + ((_l2timestamp - STARTING_BLOCK_TIMESTAMP) / L2_BLOCK_TIME); } }
40,479
60
// Calculates a EIP712 domain separator. name The EIP712 domain name. version The EIP712 domain version. verifyingContract The EIP712 verifying contract.return result EIP712 domain separator. /
function hashDomainSeperator( string memory name, string memory version, address verifyingContract
function hashDomainSeperator( string memory name, string memory version, address verifyingContract
41,515
12
// Transfer the token.
token.safeTransferFrom(from, to, tokenId); return true;
token.safeTransferFrom(from, to, tokenId); return true;
26,092
111
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp );
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp );
69,332
173
// Creates and begins a new sale./_tokenId - ID of token to sale, sender must be owner./_price - Price of item (in wei)/_seller - Seller, if not the message sender
function createSale( uint256 _tokenId, uint256 _price, address _seller ) external whenNotPaused
function createSale( uint256 _tokenId, uint256 _price, address _seller ) external whenNotPaused
8,149
8
// Is the art and metadata revealed?
bool private _isRevealed = false;
bool private _isRevealed = false;
40,389
91
// Divides x between y, assuming they are both fixed point with 18 digits.
function divd(uint256 x, uint256 y) internal pure returns (uint256) { return divd(x, y, 18); }
function divd(uint256 x, uint256 y) internal pure returns (uint256) { return divd(x, y, 18); }
2,439
68
// Deposits ETH into jackpot, for testing and increase final rewards, owner only. /
function depositJackpot() external payable { jackpot = jackpot.add(msg.value); }
function depositJackpot() external payable { jackpot = jackpot.add(msg.value); }
31,378
23
// Register the new timelockID as the current protected timelockID.
_protectedTimelockIDs[functionSelector][modifiedFunction] = timelockID;
_protectedTimelockIDs[functionSelector][modifiedFunction] = timelockID;
43,776
137
// squaring via mul is cheaper than via pow
int128 inputSquared64x64 = input64x64.mul(input64x64); int128 value64x64 = (-inputSquared64x64 >> 1).exp().div( CDF_CONST_0.add(CDF_CONST_1.mul(input64x64.abs())).add( CDF_CONST_2.mul(inputSquared64x64.add(THREE_64x64).sqrt()) ) ); return input64x64 > 0 ? ONE_64x64.sub(value64x64) : value64x64;
int128 inputSquared64x64 = input64x64.mul(input64x64); int128 value64x64 = (-inputSquared64x64 >> 1).exp().div( CDF_CONST_0.add(CDF_CONST_1.mul(input64x64.abs())).add( CDF_CONST_2.mul(inputSquared64x64.add(THREE_64x64).sqrt()) ) ); return input64x64 > 0 ? ONE_64x64.sub(value64x64) : value64x64;
51,311
23
// Get profits _market The market namereturn int /
function getProfits(bytes6 _market) public view returns(int) { return profits[_market]; }
function getProfits(bytes6 _market) public view returns(int) { return profits[_market]; }
76,952
45
// calculate token amount to be sent
uint256 token = msg.value.mul(exchangeRate); //weiamount * exchangeRate uint256 finalTokens = token.add(calculatePurchaseBonus(token)); //add bonus if available tokensSold = tokensSold.add(finalTokens); _transfer(this, msg.sender, finalTokens); //makes the transfers forwardEherToOwner(); //send Ether to owner
uint256 token = msg.value.mul(exchangeRate); //weiamount * exchangeRate uint256 finalTokens = token.add(calculatePurchaseBonus(token)); //add bonus if available tokensSold = tokensSold.add(finalTokens); _transfer(this, msg.sender, finalTokens); //makes the transfers forwardEherToOwner(); //send Ether to owner
53,270
4
// msg.sender the one who invokes the contract read: transfer balance to msg.sender
payable(msg.sender).transfer(getBalance());
payable(msg.sender).transfer(getBalance());
77
151
// address of the reward token
address public override _rewardTokenAddress;
address public override _rewardTokenAddress;
24,958
15
// Events
event NewListing( address indexed seller, IERC721 indexed nftAddress, uint256 indexed nftID, uint256 price ); event ListingPriceChange( address indexed seller, IERC721 indexed nftAddress, uint256 indexed nftID,
event NewListing( address indexed seller, IERC721 indexed nftAddress, uint256 indexed nftID, uint256 price ); event ListingPriceChange( address indexed seller, IERC721 indexed nftAddress, uint256 indexed nftID,
51,086
5
// Adds headers to storage after validating/ We check integrity and consistency of the header chain/ _anchor The header immediately preceeding the new chain/ _headersA tightly-packed list of new 80-byte Bitcoin headers to record/ return True if successfully written, error otherwise
function _addHeaders(bytes29 _anchor, bytes29 _headers, bool _internal) internal returns (bool) { /// Extract basic info bytes32 _previousDigest = _anchor.hash256(); uint256 _anchorHeight = _findHeight(_previousDigest); /* NB: errors if unknown */ uint256 _target = _headers.indexHeaderArray(0).target(); require( _internal || _anchor.target() == _target, "Unexpected retarget on external call" ); /* NB: 1. check that the header has sufficient work 2. check that headers are in a coherent chain (no retargets, hash links good) 3. Store the block connection 4. Store the height */ uint256 _height; bytes32 _currentDigest; for (uint256 i = 0; i < _headers.len() / 80; i += 1) { bytes29 _header = _headers.indexHeaderArray(i); _height = _anchorHeight.add(i + 1); _currentDigest = _header.hash256(); /* NB: if the block is already authenticated, we don't need to a work check Or write anything to state. This saves gas */ if (previousBlock[_currentDigest] == bytes32(0)) { require( TypedMemView.reverseUint256(uint256(_currentDigest)) <= _target, "Header work is insufficient" ); previousBlock[_currentDigest] = _previousDigest; if (_height % HEIGHT_INTERVAL == 0) { /* NB: We store the height only every 4th header to save gas */ blockHeight[_currentDigest] = _height; } } /* NB: we do still need to make chain level checks tho */ require(_header.target() == _target, "Target changed unexpectedly"); require(_header.checkParent(_previousDigest), "Headers do not form a consistent chain"); _previousDigest = _currentDigest; } emit Extension( _anchor.hash256(), _currentDigest); return true; }
function _addHeaders(bytes29 _anchor, bytes29 _headers, bool _internal) internal returns (bool) { /// Extract basic info bytes32 _previousDigest = _anchor.hash256(); uint256 _anchorHeight = _findHeight(_previousDigest); /* NB: errors if unknown */ uint256 _target = _headers.indexHeaderArray(0).target(); require( _internal || _anchor.target() == _target, "Unexpected retarget on external call" ); /* NB: 1. check that the header has sufficient work 2. check that headers are in a coherent chain (no retargets, hash links good) 3. Store the block connection 4. Store the height */ uint256 _height; bytes32 _currentDigest; for (uint256 i = 0; i < _headers.len() / 80; i += 1) { bytes29 _header = _headers.indexHeaderArray(i); _height = _anchorHeight.add(i + 1); _currentDigest = _header.hash256(); /* NB: if the block is already authenticated, we don't need to a work check Or write anything to state. This saves gas */ if (previousBlock[_currentDigest] == bytes32(0)) { require( TypedMemView.reverseUint256(uint256(_currentDigest)) <= _target, "Header work is insufficient" ); previousBlock[_currentDigest] = _previousDigest; if (_height % HEIGHT_INTERVAL == 0) { /* NB: We store the height only every 4th header to save gas */ blockHeight[_currentDigest] = _height; } } /* NB: we do still need to make chain level checks tho */ require(_header.target() == _target, "Target changed unexpectedly"); require(_header.checkParent(_previousDigest), "Headers do not form a consistent chain"); _previousDigest = _currentDigest; } emit Extension( _anchor.hash256(), _currentDigest); return true; }
36,059
8
// the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
uint8 id;
38,155
158
// Set the status and the return data / revert reason from the call.
ok[i] = callResults[i].ok; returnData[i] = callResults[i].returnData;
ok[i] = callResults[i].ok; returnData[i] = callResults[i].returnData;
27,929
36
// Next, compute the cost of the returndatacopy.
let cost := mul(CostPerWord, returnDataWords)
let cost := mul(CostPerWord, returnDataWords)
16,372
58
// Moves tokens `amount` from `sender` to `recipient`. This is internal function is equivalent to `transfer`, and can be used toe.g. implement automatic token fees, slashing mechanisms, etc. Emits a `Transfer` event. Requirements: - `sender` cannot be the zero address.- `recipient` cannot be the zero address.- `sender` must have a balance of at least `amount`. /
function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
17,322
206
// checks to make sure user picked a valid team.if not sets teamto default (sneks) /
function verifyTeam(uint256 _team) private pure returns (uint256)
function verifyTeam(uint256 _team) private pure returns (uint256)
50,335
0
// Proxy implementing EIP173 for ownership management that accept ETH via receive
contract EIP173ProxyWithReceive is EIP173Proxy { constructor( address implementationAddress, address ownerAddress, bytes memory data ) payable EIP173Proxy(implementationAddress, ownerAddress, data) {} receive() external payable override {} }
contract EIP173ProxyWithReceive is EIP173Proxy { constructor( address implementationAddress, address ownerAddress, bytes memory data ) payable EIP173Proxy(implementationAddress, ownerAddress, data) {} receive() external payable override {} }
26,314
62
// Return the allocation by ID. _allocationID Address used as allocation identifierreturn Allocation data /
function getAllocation(address _allocationID) external view override returns (Allocation memory)
function getAllocation(address _allocationID) external view override returns (Allocation memory)
22,831
13
// Accept tranfer owner rights
function acceptOwnership() public onlyOwner { OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); }
function acceptOwnership() public onlyOwner { OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); }
29,559
20
// emit Borrow(msg.sender, token, amount, accountMirror.deposit100 / accountMirror.borrowed100 );
}
}
22,438
123
// |/ Convert uint256 to string _i Unsigned integer to convert to string /
function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 ii = _i; uint256 len; // Get number of bytes while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; // Get each individual ASCII while (ii != 0) { bstr[k--] = byte(uint8(48 + ii % 10)); ii /= 10; } // Convert to string return string(bstr); }
function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 ii = _i; uint256 len; // Get number of bytes while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; // Get each individual ASCII while (ii != 0) { bstr[k--] = byte(uint8(48 + ii % 10)); ii /= 10; } // Convert to string return string(bstr); }
29,293
243
// Update weights in a predetermined way, between startBlock and endBlock,through external calls to pokeWeights Must call pokeWeights at least once past the end for it to do the final update and enable calling this again. It is possible to call updateWeightsGradually during an update in some use cases For instance, setting newWeights to currentWeights to stop the update where it is newWeights - final weights we want to get to. Note that the ORDER (and number) oftokens can change if you have added or removed tokens from the poolIt ensures the counts are correct, but can't help you with the
function updateWeightsGradually( uint[] calldata newWeights, uint startBlock, uint endBlock ) external logs lock onlyOwner needsBPool
function updateWeightsGradually( uint[] calldata newWeights, uint startBlock, uint endBlock ) external logs lock onlyOwner needsBPool
11,679
45
// Constructor - adds the owner of the contract to the list of valid members/
function IPFSProxy(address[] _members,uint _required, uint _persistlimit) Multimember (_members, _required) public { setTotalPersistLimit(_persistlimit); for (uint i = 0; i < _members.length; ++i) { MemberAdded(_members[i]); } addContract(this,block.number); }
function IPFSProxy(address[] _members,uint _required, uint _persistlimit) Multimember (_members, _required) public { setTotalPersistLimit(_persistlimit); for (uint i = 0; i < _members.length; ++i) { MemberAdded(_members[i]); } addContract(this,block.number); }
45,363
18
// We pass through the queue
for(uint i = 0; i < queue.length; i++) { uint idx = currentReceiverIndex + i; // We get the number of the first Deposit in the queue Deposit storage dep = queue[idx]; // We get information about the first Deposit if(money >= dep.expect) { // If we have enough money for the full payment, we pay him everything dep.depositor.transfer(dep.expect); // Send him money money -= dep.expect; // Update the amount of remaining money
for(uint i = 0; i < queue.length; i++) { uint idx = currentReceiverIndex + i; // We get the number of the first Deposit in the queue Deposit storage dep = queue[idx]; // We get information about the first Deposit if(money >= dep.expect) { // If we have enough money for the full payment, we pay him everything dep.depositor.transfer(dep.expect); // Send him money money -= dep.expect; // Update the amount of remaining money
50,145
114
// Helper function to handle both ETH and ERC20 payments
function _safeTokenPayment( address _token, address payable _to, uint256 _amount
function _safeTokenPayment( address _token, address payable _to, uint256 _amount
31,985
155
// Returns the address is excluded from antiWhale or not. /
function isExcludedFromAntiWhale(address _account) public view returns (bool) { return _excludedFromAntiWhale[_account]; }
function isExcludedFromAntiWhale(address _account) public view returns (bool) { return _excludedFromAntiWhale[_account]; }
28,005
199
// return The current administrative nonce
function administrativeNonce() external view returns (uint256);
function administrativeNonce() external view returns (uint256);
19,716
29
// Receipts of ballots for the entire set of voters
mapping (address => Receipt) receipts;
mapping (address => Receipt) receipts;
398
135
// negative or zero interest (i.e. discountRate >= 0)
augmintToken.burn(repaymentAmount);
augmintToken.burn(repaymentAmount);
4,564
18
// Allows the current owner to relinquish control of the contract. Renouncing to ownership will leave the contract without an owner. It will not be possible to call the functions with the `onlyOwner` modifier anymore. /
function renounceOwnership() external onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
function renounceOwnership() external onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
13,661
172
// _fromToken will be either fromToken of toToken of the previous path
IERC20 _fromToken = i > 0 ? IERC20(path[i - 1].to) : IERC20(fromToken); IERC20 _toToken = IERC20(path[i].to); if (i > 0 && address(_fromToken) == Utils.ethAddress()) { _fromAmount = _fromAmount.sub(path[i].totalNetworkFee); }
IERC20 _fromToken = i > 0 ? IERC20(path[i - 1].to) : IERC20(fromToken); IERC20 _toToken = IERC20(path[i].to); if (i > 0 && address(_fromToken) == Utils.ethAddress()) { _fromAmount = _fromAmount.sub(path[i].totalNetworkFee); }
74,783
20
// computes the worth of the total deposit in loan tokens.(loanTokenSent + convert(collateralTokenSent))no actual swap happening here.
uint256 totalDeposit = _totalDeposit( collateralTokenAddress, collateralTokenSent, loanTokenSent ); require(totalDeposit != 0, "12"); address[4] memory sentAddresses; uint256[5] memory sentAmounts;
uint256 totalDeposit = _totalDeposit( collateralTokenAddress, collateralTokenSent, loanTokenSent ); require(totalDeposit != 0, "12"); address[4] memory sentAddresses; uint256[5] memory sentAmounts;
45,025
86
// Withdraw your tokens once the Auction has ended.
function withdrawTokens() public nonReentrant { if( auctionSuccessful() ) { /// @dev Successful auction! Transfer claimed tokens. /// @dev AG: Could be only > min to allow early withdraw uint256 tokensToClaim = tokensClaimable(msg.sender); require(tokensToClaim > 0 ); // No tokens to claim claimed[ msg.sender] = claimed[ msg.sender].add(tokensToClaim); tokenWithdrawn = tokenWithdrawn.add(tokensToClaim); _tokenPayment(auctionToken, msg.sender, tokensToClaim); } else { /// @dev Auction did not meet reserve price. /// @dev Return committed funds back to user. require(block.timestamp > endDate); // Auction not yet finished uint256 fundsCommitted = commitments[ msg.sender]; require(fundsCommitted > 0); // No funds committed commitments[msg.sender] = 0; // Stop multiple withdrawals and free some gas _tokenPayment(paymentCurrency, msg.sender, fundsCommitted); } }
function withdrawTokens() public nonReentrant { if( auctionSuccessful() ) { /// @dev Successful auction! Transfer claimed tokens. /// @dev AG: Could be only > min to allow early withdraw uint256 tokensToClaim = tokensClaimable(msg.sender); require(tokensToClaim > 0 ); // No tokens to claim claimed[ msg.sender] = claimed[ msg.sender].add(tokensToClaim); tokenWithdrawn = tokenWithdrawn.add(tokensToClaim); _tokenPayment(auctionToken, msg.sender, tokensToClaim); } else { /// @dev Auction did not meet reserve price. /// @dev Return committed funds back to user. require(block.timestamp > endDate); // Auction not yet finished uint256 fundsCommitted = commitments[ msg.sender]; require(fundsCommitted > 0); // No funds committed commitments[msg.sender] = 0; // Stop multiple withdrawals and free some gas _tokenPayment(paymentCurrency, msg.sender, fundsCommitted); } }
17,240
12
// Need to unstake to meet the demand
uint256 neededUnderlying = assets - underlyingBalanceInContract; uint256 neededEToken = eToken.convertUnderlyingToBalance(neededUnderlying);
uint256 neededUnderlying = assets - underlyingBalanceInContract; uint256 neededEToken = eToken.convertUnderlyingToBalance(neededUnderlying);
12,734
7
// Adds an account to an identity contract, without approval. Since this method can only be called by the registry who creates the identity contract, we assume that the sender and identity are both owned by the same entity. identity The identity contract address to add the account to sender The account to be added /
function newIdentity(address identity, address sender) public
function newIdentity(address identity, address sender) public
52,727
6
// current round total supply
uint256 _totalSupply;
uint256 _totalSupply;
31,030
9
// The ratio between mantissa precision (1e18) and the underlying precision. /
uint256 public underlyingPrecisionScalar;
uint256 public underlyingPrecisionScalar;
40,489
102
// Transfer LOOKS tokens to this contract
looksRareToken.safeTransferFrom(msg.sender, address(this), amount); uint256 pendingRewards;
looksRareToken.safeTransferFrom(msg.sender, address(this), amount); uint256 pendingRewards;
20,032
203
// check the correct value has been passed
if(MINT_PRICE * mintAmount != msg.value){ revert(string(abi.encodePacked("The amount of Wei sent ", Strings.toString(msg.value)," does not match the required amount ", Strings.toString(MINT_PRICE * mintAmount)))); }
if(MINT_PRICE * mintAmount != msg.value){ revert(string(abi.encodePacked("The amount of Wei sent ", Strings.toString(msg.value)," does not match the required amount ", Strings.toString(MINT_PRICE * mintAmount)))); }
4,858
240
// Asset currency id
uint256 currencyId; uint256 maturity;
uint256 currencyId; uint256 maturity;
6,948
53
// Function to get balance of an address
function balanceOf(address _addr) public view returns (uint256 balance) { return token.balanceOf(_addr); }
function balanceOf(address _addr) public view returns (uint256 balance) { return token.balanceOf(_addr); }
26,781
14
// check whether address `who` is given minter rights./who The address to query./ return whether the address has minter rights.
function isMinter(address who) public view returns (bool) { return _minters[who]; }
function isMinter(address who) public view returns (bool) { return _minters[who]; }
59,175
329
// return the amount of liquidity removed
return reserveAmount;
return reserveAmount;
10,149
52
// Given a seed, construct a base64 encoded SVG image. /
function generateSVGImage(INounsSeeder.Seed memory seed) external view override returns (string memory) { ISVGRenderer.SVGParams memory params = ISVGRenderer.SVGParams({ parts: getPartsForSeed(seed), background: art.backgrounds(seed.background) }); return NFTDescriptorV2.generateSVGImage(renderer, params); }
function generateSVGImage(INounsSeeder.Seed memory seed) external view override returns (string memory) { ISVGRenderer.SVGParams memory params = ISVGRenderer.SVGParams({ parts: getPartsForSeed(seed), background: art.backgrounds(seed.background) }); return NFTDescriptorV2.generateSVGImage(renderer, params); }
13,557
61
// Computes stakers $bBRO rewards/Formula: (((base + xtra_multunstaking_period^210^(-6))staked_bro) / 365)unclaimed_epochs/_totalBroStakedAmount total $BRO staked inside unstaking period or withdrawal for $bBRO rewards/_unstakingPeriod unstaking period for the rewards calculation/_unclaimedEpochs amount of epochs when rewards wasn't claimed/ return computed $bBRO reward
function _computeBBroReward( uint256 _totalBroStakedAmount, uint256 _unstakingPeriod, uint256 _unclaimedEpochs
function _computeBBroReward( uint256 _totalBroStakedAmount, uint256 _unstakingPeriod, uint256 _unclaimedEpochs
10,046
94
// newD should be bigger than or equal to oldD
uint256 mintAmount = newD.sub(oldD); uint256 feeAmount = 0; if (mintFee > 0) { feeAmount = mintAmount.mul(mintFee).div(feeDenominator); mintAmount = mintAmount.sub(feeAmount); }
uint256 mintAmount = newD.sub(oldD); uint256 feeAmount = 0; if (mintFee > 0) { feeAmount = mintAmount.mul(mintFee).div(feeDenominator); mintAmount = mintAmount.sub(feeAmount); }
76,262
17
// 在 O(1) 的时间复杂度内返回 key-value 键值对储存在 Map 中的位置
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32)
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32)
23,447
159
// The values being non-zero value makes deployment a bit more expensive, but in exchange the refund on every call to nonReentrant will be lower in amount. Since refunds are capped to a percentage of the total transaction's gas, it is best to keep them low in cases like this one, to increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; }
uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; }
61,298
322
// And what effect does this percentage change have on the global debt holding of other issuers? The delta specifically needs to not take into account any existing debt as it's already accounted for in the delta from when they issued previously.
delta = SafeDecimalMath.preciseUnit().add(debtPercentage);
delta = SafeDecimalMath.preciseUnit().add(debtPercentage);
62,813
195
// burn option,modify collateral occupied and net worth value, only manager contract can invoke this. from user's address. id user's input option's id. amount user's input burned option's amount. optionPrice current new option's price, calculated by options price contract. /
function burnOptions(address from,uint256 id,uint256 amount,uint256 optionPrice)public onlyManager Smaller(amount) OutLimitation(id){ OptionsInfo memory info = _getOptionsById(id); _burnOptions(from,id,info,amount); uint256 currentPrice = oracleUnderlyingPrice(info.underlying); _burnOptionsCollateral(info,amount,currentPrice); _burnOptionsNetworth(info,amount,currentPrice,optionPrice); }
function burnOptions(address from,uint256 id,uint256 amount,uint256 optionPrice)public onlyManager Smaller(amount) OutLimitation(id){ OptionsInfo memory info = _getOptionsById(id); _burnOptions(from,id,info,amount); uint256 currentPrice = oracleUnderlyingPrice(info.underlying); _burnOptionsCollateral(info,amount,currentPrice); _burnOptionsNetworth(info,amount,currentPrice,optionPrice); }
37,885
84
// Calculate the number of pending bonds
uint256 numBonds = bondCounter; bool[] memory positions = new bool[](numBonds);
uint256 numBonds = bondCounter; bool[] memory positions = new bool[](numBonds);
29,991
13
// Execute a DELEGATECALL from the proxy contractOwner only dest Address to which the call will be sent calldata Calldata to sendreturn Result of the delegatecall (success or failure) /
function delegateProxy(address dest, bytes calldata) public onlyOwner returns (bool result)
function delegateProxy(address dest, bytes calldata) public onlyOwner returns (bool result)
45,669
88
// assuming p1p2 = k, equivalent to uniswap's xy = k
uint directSwapTokenInPrice = allowDirectSwap?tokenOutPoolPrice.mul(tokenInPoolPrice).div(tokenOutPrice):1; tokenInPrice = _getNewPrice(tokenInPoolPrice, tokenInPoolTokenBalance, amountIn, 0, TxType.SELL); tokenInPrice = directSwapTokenInPrice > tokenInPrice?directSwapTokenInPrice:tokenInPrice; amountIn = tradeVcashValue.mul(1e18).div(_getAvgPrice(tokenInPoolPrice, tokenInPrice));
uint directSwapTokenInPrice = allowDirectSwap?tokenOutPoolPrice.mul(tokenInPoolPrice).div(tokenOutPrice):1; tokenInPrice = _getNewPrice(tokenInPoolPrice, tokenInPoolTokenBalance, amountIn, 0, TxType.SELL); tokenInPrice = directSwapTokenInPrice > tokenInPrice?directSwapTokenInPrice:tokenInPrice; amountIn = tradeVcashValue.mul(1e18).div(_getAvgPrice(tokenInPoolPrice, tokenInPrice));
55,855
32
// Determine whether or not a user is authorized to sell SGA. _sender The address of the user.return Authorization status. /
function isAuthorizedToSell(address _sender) external view returns (bool);
function isAuthorizedToSell(address _sender) external view returns (bool);
19,825
155
// Add Governor as pauser of Registry;
reg.addPauser(msg.sender);
reg.addPauser(msg.sender);
43,045