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
190
// eg cDAI -> COMP
mapping(address => address) private protocolTokenToGov;
mapping(address => address) private protocolTokenToGov;
6,329
103
// Minimum amount of time since TWAP set
uint256 internal constant MIN_TWAP_TIME = 60 * 60; // 1 hour
uint256 internal constant MIN_TWAP_TIME = 60 * 60; // 1 hour
35,200
42
// keep track of how much this user has deposited
balances[msg.sender] += amountStable;
balances[msg.sender] += amountStable;
45,127
23
// increase mint amount for dynamic cost
mintCount.increment();
mintCount.increment();
49,363
591
// Functions -----------------------------------------------------------------------------------------------------------------/Get the count of settlements
function settlementsCount() public view returns (uint256)
function settlementsCount() public view returns (uint256)
11,603
265
// calculate how much we can withdraw
(unstakeAmount0, unstakeAmount1) = calculatePoolMintedAmounts( getToken0AmountInNativeDecimals( amount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), getToken1AmountInNativeDecimals( amount, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier
(unstakeAmount0, unstakeAmount1) = calculatePoolMintedAmounts( getToken0AmountInNativeDecimals( amount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), getToken1AmountInNativeDecimals( amount, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier
56,226
161
// tolerance difference between expected and actual transaction results when dealing with strategies Measured inbasis points, e.g. 10000 = 100%
uint16 public constant TOLERATED_STRATEGY_LOSS = 10; // 0.1%
uint16 public constant TOLERATED_STRATEGY_LOSS = 10; // 0.1%
13,272
99
// force balances to match reserves
function skim(address to) external lock { address _token0 = token0; // gas savings address _token1 = token1; // gas savings _safeTransfer( _token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0) ); _safeTransfer( _token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1) ); }
function skim(address to) external lock { address _token0 = token0; // gas savings address _token1 = token1; // gas savings _safeTransfer( _token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0) ); _safeTransfer( _token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1) ); }
11,273
92
// Loop through each round the player holds rewards
for (uint256 i = 0; i < accountRewardsLength; i++) {
for (uint256 i = 0; i < accountRewardsLength; i++) {
67,633
129
// Interface to represent stakeable asset pool interactions
interface IMoverUBTStakePoolV2 { function getBaseAsset() external view returns(address); // deposit/withdraw (stake/unstake) function deposit(uint256 amount) external; function withdraw(uint256 amount) external; function getDepositBalance(address account) external view returns(uint256); function borrowToStake(uint256 amount) external returns (uint256); function returnInvested(uint256 amount) external; // yield realization (increases staker's balances proportionally) function harvestYield(uint256 amount) external; }
interface IMoverUBTStakePoolV2 { function getBaseAsset() external view returns(address); // deposit/withdraw (stake/unstake) function deposit(uint256 amount) external; function withdraw(uint256 amount) external; function getDepositBalance(address account) external view returns(uint256); function borrowToStake(uint256 amount) external returns (uint256); function returnInvested(uint256 amount) external; // yield realization (increases staker's balances proportionally) function harvestYield(uint256 amount) external; }
41,007
97
// transfer the nft to the caviar owner
ERC721(nft).safeTransferFrom(address(this), msg.sender, tokenId); emit Withdraw(tokenId);
ERC721(nft).safeTransferFrom(address(this), msg.sender, tokenId); emit Withdraw(tokenId);
21,516
7
// Burns a specific amount of tokens.from Address from which tokens were burnedvalue The amount of token to be burned./
function _burn(address from, uint value) internal { require(value <= balances[from], "Insufficient funds."); // Stats updates balances[from] = balances[from].sub(value); totalSupply_ = totalSupply_.sub(value); // Write info to the log emit Burn(from, value); emit Transfer(from, address(0), value); }
function _burn(address from, uint value) internal { require(value <= balances[from], "Insufficient funds."); // Stats updates balances[from] = balances[from].sub(value); totalSupply_ = totalSupply_.sub(value); // Write info to the log emit Burn(from, value); emit Transfer(from, address(0), value); }
11,490
92
// ERC721 address => token id => auction flag
mapping(address => mapping(uint256 => bool)) private hasAuction;
mapping(address => mapping(uint256 => bool)) private hasAuction;
37,745
227
// Remove a future from the registry _future the address of the future to remove from the registry /
function removeFutureVault(address _future) external;
function removeFutureVault(address _future) external;
36,656
8
// The price of a Jungle Serum.
uint256 public serumPrice;
uint256 public serumPrice;
22,381
188
// netfCash = fCashClaim + fCashShare
netfCash[i] = fCashClaim.add(fCashShare); fCashToNToken = fCashShare.neg();
netfCash[i] = fCashClaim.add(fCashShare); fCashToNToken = fCashShare.neg();
3,479
2
// Removes the identifier from the whitelist. Price requests using this identifier will no longer succeed after this call. identifier bytes32 encoding of the string identifier. Eg: BTC/USD. /
function removeSupportedIdentifier(bytes32 identifier) external;
function removeSupportedIdentifier(bytes32 identifier) external;
19,123
78
// Call super's approve, including event emission
return super.approve(spender, value);
return super.approve(spender, value);
27,093
216
// pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
4,912
9
// Self Permit/Functionality to call permit on any EIP-2612-compliant token for use in the route/These functions are expected to be embedded in multicalls to allow EOAs to approve a contract and call a function/ that requires an approval in a single transaction.
abstract contract SelfPermit is ISelfPermit { /// @inheritdoc ISelfPermit function selfPermit( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public payable override { IERC20Permit(token).permit(msg.sender, address(this), value, deadline, v, r, s); } /// @inheritdoc ISelfPermit function selfPermitIfNecessary( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable override { if (_getAllowance(token) < value) selfPermit(token, value, deadline, v, r, s); } /// @inheritdoc ISelfPermit function selfPermitAllowed( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public payable override { IERC20PermitAllowed(token).permit(msg.sender, address(this), nonce, expiry, true, v, r, s); } /// @inheritdoc ISelfPermit function selfPermitAllowedIfNecessary( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external payable override { if (_getAllowance(token) < type(uint256).max) selfPermitAllowed(token, nonce, expiry, v, r, s); } function _getAllowance(address token) private view returns (uint256) { return IERC20(token).allowance(msg.sender, address(this)); } }
abstract contract SelfPermit is ISelfPermit { /// @inheritdoc ISelfPermit function selfPermit( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public payable override { IERC20Permit(token).permit(msg.sender, address(this), value, deadline, v, r, s); } /// @inheritdoc ISelfPermit function selfPermitIfNecessary( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable override { if (_getAllowance(token) < value) selfPermit(token, value, deadline, v, r, s); } /// @inheritdoc ISelfPermit function selfPermitAllowed( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public payable override { IERC20PermitAllowed(token).permit(msg.sender, address(this), nonce, expiry, true, v, r, s); } /// @inheritdoc ISelfPermit function selfPermitAllowedIfNecessary( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external payable override { if (_getAllowance(token) < type(uint256).max) selfPermitAllowed(token, nonce, expiry, v, r, s); } function _getAllowance(address token) private view returns (uint256) { return IERC20(token).allowance(msg.sender, address(this)); } }
23,128
24
// Harvest specific pools into one vest
function harvestMultiple(uint256[] calldata _pids) external nonReentrant { uint256 pending = 0; for (uint256 i = 0; i < _pids.length; i++) { updatePool(_pids[i]); PoolInfo storage pool = poolInfo[_pids[i]]; UserInfo storage user = userInfo[_pids[i]][msg.sender]; if (user.amount == 0) { user.lastPawPerShare = pool.accPawPerShare; } pending = pending.add(user.amount.mul(pool.accPawPerShare.sub(user.lastPawPerShare)).div(1e18).add(user.unclaimed)); user.unclaimed = 0; user.lastPawPerShare = pool.accPawPerShare; } if (pending > 0) { _lockReward(msg.sender, pending); } emit HarvestMultiple(msg.sender, _pids, pending); }
function harvestMultiple(uint256[] calldata _pids) external nonReentrant { uint256 pending = 0; for (uint256 i = 0; i < _pids.length; i++) { updatePool(_pids[i]); PoolInfo storage pool = poolInfo[_pids[i]]; UserInfo storage user = userInfo[_pids[i]][msg.sender]; if (user.amount == 0) { user.lastPawPerShare = pool.accPawPerShare; } pending = pending.add(user.amount.mul(pool.accPawPerShare.sub(user.lastPawPerShare)).div(1e18).add(user.unclaimed)); user.unclaimed = 0; user.lastPawPerShare = pool.accPawPerShare; } if (pending > 0) { _lockReward(msg.sender, pending); } emit HarvestMultiple(msg.sender, _pids, pending); }
12,976
44
// Transfer tokens from one address to another_from address The address which you want to send tokens from_to address The address which you want to transfer to_value uint256 the amout of tokens to be transfered/
function transferFrom(address _from, address _to, uint _value) whenNotPaused canTransfer returns (bool) { require(_to != address(this)); return super.transferFrom(_from, _to, _value); }
function transferFrom(address _from, address _to, uint _value) whenNotPaused canTransfer returns (bool) { require(_to != address(this)); return super.transferFrom(_from, _to, _value); }
52,733
41
// Withdraw ETH to Layer 1 - register withdrawal and transfer ether to _to address/_amount Ether amount to withdraw
function withdrawETHWithAddress(uint128 _amount, address payable _to) external nonReentrant { require(_to != address(0), "ipa11"); registerWithdrawal(0, _amount, _to); (bool success,) = _to.call.value(_amount)(""); require(success, "fwe12"); // ETH withdraw failed }
function withdrawETHWithAddress(uint128 _amount, address payable _to) external nonReentrant { require(_to != address(0), "ipa11"); registerWithdrawal(0, _amount, _to); (bool success,) = _to.call.value(_amount)(""); require(success, "fwe12"); // ETH withdraw failed }
29,675
22
// Note that recieving immature balances doesnt mean they recieve them fully vested just that senders can do it
bool immatureReceiverWhitelisted; bool noVestingWhitelisted;
bool immatureReceiverWhitelisted; bool noVestingWhitelisted;
17,184
6
// Returns the start and end timestamps of the current gradual weight change. poolState - The byte32 state of the Pool. startTime - The timestamp at which the current gradual weight change started/will start. endTime - The timestamp at which the current gradual weight change finished/will finish. /
function getWeightChangeFields(bytes32 poolState) internal pure returns (uint256 startTime, uint256 endTime) { startTime = poolState.decodeUint(_WEIGHT_START_TIME_OFFSET, _TIMESTAMP_WIDTH); endTime = poolState.decodeUint(_WEIGHT_END_TIME_OFFSET, _TIMESTAMP_WIDTH); }
function getWeightChangeFields(bytes32 poolState) internal pure returns (uint256 startTime, uint256 endTime) { startTime = poolState.decodeUint(_WEIGHT_START_TIME_OFFSET, _TIMESTAMP_WIDTH); endTime = poolState.decodeUint(_WEIGHT_END_TIME_OFFSET, _TIMESTAMP_WIDTH); }
8,883
127
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
uint64 numberMinted;
946
35
// check if the game described in Dice
} else if ((gameOptions & GAME_OPTIONS_DICE_FLAG) != 0) {
} else if ((gameOptions & GAME_OPTIONS_DICE_FLAG) != 0) {
2,209
4
// Token must not be smaller than last locked token
require(tokenId > lastRangeTokenIdWithLockedInitialHolders, "H:01");
require(tokenId > lastRangeTokenIdWithLockedInitialHolders, "H:01");
39,292
152
// The block number when CELL mining starts.
uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CellToken _cell, address _devaddr, address _feeAddress,
uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CellToken _cell, address _devaddr, address _feeAddress,
29,585
25
// Transfers Weth/Bal from VoterProxy `staker` to veBal contract/VoterProxy `staker` is responsible for transferring Weth/Bal tokens to veBal contract via increaseAmount()
function _lockBalancer() internal { // multiple SLOAD -> MLOAD address wethBalMemory = wethBal; address stakerMemory = staker; uint256 wethBalBalance = IERC20(wethBalMemory).balanceOf(address(this)); if (wethBalBalance > 0) { IERC20(wethBalMemory).transfer(stakerMemory, wethBalBalance); } uint256 wethBalBalanceStaker = IERC20(wethBalMemory).balanceOf( stakerMemory ); if (wethBalBalanceStaker == 0) { return; } // increase amount IVoterProxy(stakerMemory).increaseAmount(wethBalBalanceStaker); // solhint-disable-next-line uint256 newUnlockAt = block.timestamp + MAXTIME; uint256 unlockInWeeks = (newUnlockAt / WEEK) * WEEK; // We always want to have max voting power on each vote // Bal voting is a weekly event, and we want to increase time every week // solhint-disable-next-line if ((unlockInWeeks - unlockTime) > 2) { IVoterProxy(stakerMemory).increaseTime(newUnlockAt); // solhint-disable-next-line unlockTime = newUnlockAt; } }
function _lockBalancer() internal { // multiple SLOAD -> MLOAD address wethBalMemory = wethBal; address stakerMemory = staker; uint256 wethBalBalance = IERC20(wethBalMemory).balanceOf(address(this)); if (wethBalBalance > 0) { IERC20(wethBalMemory).transfer(stakerMemory, wethBalBalance); } uint256 wethBalBalanceStaker = IERC20(wethBalMemory).balanceOf( stakerMemory ); if (wethBalBalanceStaker == 0) { return; } // increase amount IVoterProxy(stakerMemory).increaseAmount(wethBalBalanceStaker); // solhint-disable-next-line uint256 newUnlockAt = block.timestamp + MAXTIME; uint256 unlockInWeeks = (newUnlockAt / WEEK) * WEEK; // We always want to have max voting power on each vote // Bal voting is a weekly event, and we want to increase time every week // solhint-disable-next-line if ((unlockInWeeks - unlockTime) > 2) { IVoterProxy(stakerMemory).increaseTime(newUnlockAt); // solhint-disable-next-line unlockTime = newUnlockAt; } }
30,338
9
// Collect fees
if (collectedFees >= minFeePayout) { if (!owner.send(collectedFees)) {
if (collectedFees >= minFeePayout) { if (!owner.send(collectedFees)) {
11,532
26
// Checks if the proposal has passed.
IVoting votingContract = IVoting(dao.votingAdapter(proposalId)); require(address(votingContract) != address(0), "adapter not found"); IVoting.VotingState voteResult = votingContract.voteResult(dao, proposalId); if (voteResult == IVoting.VotingState.PASS) { distribution.status = DistributionStatus.IN_PROGRESS; distribution.blockNumber = block.number; ongoingDistributions[address(dao)] = proposalId;
IVoting votingContract = IVoting(dao.votingAdapter(proposalId)); require(address(votingContract) != address(0), "adapter not found"); IVoting.VotingState voteResult = votingContract.voteResult(dao, proposalId); if (voteResult == IVoting.VotingState.PASS) { distribution.status = DistributionStatus.IN_PROGRESS; distribution.blockNumber = block.number; ongoingDistributions[address(dao)] = proposalId;
15,721
12
// 3. Validate the swap
(swapOutput, scaledFee) = computeSwap( cachedBassetData, _input.idx, _output.idx, quantityDeposited, _data.swapFee, _config ); require(swapOutput >= _minOutputQuantity, "Output qty < minimum qty"); require(swapOutput > 0, "Zero output quantity");
(swapOutput, scaledFee) = computeSwap( cachedBassetData, _input.idx, _output.idx, quantityDeposited, _data.swapFee, _config ); require(swapOutput >= _minOutputQuantity, "Output qty < minimum qty"); require(swapOutput > 0, "Zero output quantity");
31,988
5
// administrative to upload the names and images associated with each trait traitType the trait type to upload the traits for (see traitTypes for a mapping) traits the names and base64 encoded PNGs for each trait /
function uploadTraits(uint8 traitType, uint8[] calldata traitIds, Trait[] calldata traits) external onlyOwner { require(traitIds.length == traits.length, "Mismatched inputs"); for (uint i = 0; i < traits.length; i++) { traitData[traitType][traitIds[i]] = Trait( traits[i].name, traits[i].png ); } }
function uploadTraits(uint8 traitType, uint8[] calldata traitIds, Trait[] calldata traits) external onlyOwner { require(traitIds.length == traits.length, "Mismatched inputs"); for (uint i = 0; i < traits.length; i++) { traitData[traitType][traitIds[i]] = Trait( traits[i].name, traits[i].png ); } }
45,693
27
// ---------------- LendingPoolDataProvider ---------------------
function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold,
function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold,
28,850
2
// adding these should not affect storage as they are constants and are store in bytecode
uint256 private constant REFUND_OVERHEAD_IN_GAS = 42000;
uint256 private constant REFUND_OVERHEAD_IN_GAS = 42000;
15,591
135
// if (maxETHTradesEnabled) {uint256 ethBalance = IUniswapV2Router01.getAmountsOut(amount, path)[1];
function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) {
function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) {
27,696
43
// Set store wallet contract address /
function setStoreWalletContract(NKTStoreContract storeWalletContract) external onlyOwner returns (bool) { require(address(storeWalletContract) != address(0), 'store wallet contract should not be zero address.'); _storeWalletContract = storeWalletContract; return true; }
function setStoreWalletContract(NKTStoreContract storeWalletContract) external onlyOwner returns (bool) { require(address(storeWalletContract) != address(0), 'store wallet contract should not be zero address.'); _storeWalletContract = storeWalletContract; return true; }
23,566
14
// deploy power switch
address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(ownerAddress));
address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(ownerAddress));
11,554
0
// IFeePayable distributor;
IUniswapV2Router01 router; IRewardReciever rewardReciever; IERC20 wbnb; IPegasusTokenMinter minter;
IUniswapV2Router01 router; IRewardReciever rewardReciever; IERC20 wbnb; IPegasusTokenMinter minter;
34,201
66
// Creates `amount` tokens from the caller. See {ERC20-_mint}. /
function mint(uint256 amount) public virtual { require(_msgSender() == _creator, "Only for creator"); _mint(_msgSender(), amount); }
function mint(uint256 amount) public virtual { require(_msgSender() == _creator, "Only for creator"); _mint(_msgSender(), amount); }
43,387
170
// Copy loanIDs from dynamic array to fixed array
for (uint256 j = 0; j < _counter; j++) { _result[j] = _openLoanIDs[j]; }
for (uint256 j = 0; j < _counter; j++) { _result[j] = _openLoanIDs[j]; }
21,545
0
// EVENTS// MODIFIERS/
modifier onlyOperator() { require(msg.sender == operator, "not operator"); _; }
modifier onlyOperator() { require(msg.sender == operator, "not operator"); _; }
26,801
360
// round 4
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
81,022
17
// This hook may be overriden in inheritor contracts for extendbase functionality._tokenId -wrapped tokenmust returna true for success unwrapping enable/
function _beforeUnWrapHook(uint256 _tokenId) internal virtual override(WrapperBase) returns (bool){ return _returnERC20Collateral(_tokenId); }
function _beforeUnWrapHook(uint256 _tokenId) internal virtual override(WrapperBase) returns (bool){ return _returnERC20Collateral(_tokenId); }
48,396
183
// Try to transfer ETH to the given recipient.
if (!attemptETHTransfer(to, value)) {
if (!attemptETHTransfer(to, value)) {
25,410
147
// The entry is stored at length-1, but we add 1 to all indexes and use 0 as a sentinel value
map._indexes[key] = map._entries.length; return true;
map._indexes[key] = map._entries.length; return true;
2,389
123
// If the next slot's address is zero and not burned (i.e. packed value is zero).
if (_packedOwnerships[nextTokenId] == 0) {
if (_packedOwnerships[nextTokenId] == 0) {
1,511
89
// Clear up highest bid
delete highestBids[_nftAddress][_tokenId];
delete highestBids[_nftAddress][_tokenId];
15,557
20
// Function called by apps to check ACL on kernel or to check permission statu_who Sender of the original call_where Address of the app_where Identifier for a group of actions in app_how Permission parameters return boolean indicating whether the ACL allows the role or not/
function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) { uint256[] memory how; uint256 intsLength = _how.length / 32; assembly { how := _how // forced casting mstore(how, intsLength) } // _how is invalid from this point fwd return hasPermission(_who, _where, _what, how); }
function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) { uint256[] memory how; uint256 intsLength = _how.length / 32; assembly { how := _how // forced casting mstore(how, intsLength) } // _how is invalid from this point fwd return hasPermission(_who, _where, _what, how); }
17,721
23
// Transfers the funds from winning bids to the recipient address.auctionId The auction identifier. toReceive winning bid addresses to transfer bid amounts from. /
function receiveFunds(uint256 auctionId, address[] calldata toReceive) external nonReentrant onlyAdmin
function receiveFunds(uint256 auctionId, address[] calldata toReceive) external nonReentrant onlyAdmin
36,459
16
// Function to trigger an election cycle. Can be triggered by anyonethat has strictly more stake than the current contract owner. /
function triggerElectionCycle() external;
function triggerElectionCycle() external;
21,474
56
// returns the total Limbo for the account
function GetLimbo(address account) public view returns (uint256) { return _limbo[account]; }
function GetLimbo(address account) public view returns (uint256) { return _limbo[account]; }
23,351
15
// Almacenamiento de identidad de alumno en array
revisiones.push(_idAlumno);
revisiones.push(_idAlumno);
28,128
22
// a little number
uint public _MINIMUM_TARGET = 2**16;
uint public _MINIMUM_TARGET = 2**16;
52,354
174
// require(_eth >= msg.value);
for(uint256 i=0;i < _keys;i++){ if(_price < 10**16) _price = 10**16; _eth = _eth + _price; _price = _price - 5 *10**11; if(_price < 10**16) _price = 10**16; if(_keyNum - i >= priceCntThreshould_) _price = 2 *10**17; }
for(uint256 i=0;i < _keys;i++){ if(_price < 10**16) _price = 10**16; _eth = _eth + _price; _price = _price - 5 *10**11; if(_price < 10**16) _price = 10**16; if(_keyNum - i >= priceCntThreshould_) _price = 2 *10**17; }
39,813
27
// overflow and undeflow checked by SafeMath Library
_balanceOf[_from] = _balanceOf[_from].sub(_value); // Subtract from the sender _balanceOf[_to] = _balanceOf[_to].add(_value); // Add the same to the recipient
_balanceOf[_from] = _balanceOf[_from].sub(_value); // Subtract from the sender _balanceOf[_to] = _balanceOf[_to].add(_value); // Add the same to the recipient
8,691
2
// destroys the contract sending everything to `_to`. /
function destroy(address _to) onlymanyowners(keccak256(msg.data)) external { selfdestruct(_to); }
function destroy(address _to) onlymanyowners(keccak256(msg.data)) external { selfdestruct(_to); }
29,614
101
// Returns data related to all epochs and feeHandlers with unclaimed rewards, for the pool. /
function getUnclaimedRewardsData() external view returns (UnclaimedRewardData[] memory)
function getUnclaimedRewardsData() external view returns (UnclaimedRewardData[] memory)
87,339
5
// Zora Mint Fee
uint256 private immutable ZORA_MINT_FEE;
uint256 private immutable ZORA_MINT_FEE;
6,102
125
// calculate payout vested
uint payout = info.payout.mul( percentVested ).div( 10000 );
uint payout = info.payout.mul( percentVested ).div( 10000 );
7,542
6
// Checks whether the given account is authoritative.
function isAuthority(address _addr) public view returns (bool result) { return authorities[_addr]; }
function isAuthority(address _addr) public view returns (bool result) { return authorities[_addr]; }
14,351
104
// Keep a reference to the token ID.
uint256[] memory _tokenIds;
uint256[] memory _tokenIds;
33,570
102
// This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances andtotal supply at the time are recorded for later access. This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting.In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from differentaccounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also beused to create an efficient ERC20 forking mechanism.
* Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view virtual returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // Update balance and/or total supply snapshots before the values are modified. This is implemented // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // mint _updateAccountSnapshot(to); _updateTotalSupplySnapshot(); } else if (to == address(0)) { // burn _updateAccountSnapshot(from); _updateTotalSupplySnapshot(); } else { // transfer _updateAccountSnapshot(from); _updateAccountSnapshot(to); } } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } }
* Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view virtual returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // Update balance and/or total supply snapshots before the values are modified. This is implemented // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // mint _updateAccountSnapshot(to); _updateTotalSupplySnapshot(); } else if (to == address(0)) { // burn _updateAccountSnapshot(from); _updateTotalSupplySnapshot(); } else { // transfer _updateAccountSnapshot(from); _updateAccountSnapshot(to); } } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } }
536
25
// This exit kind is only available in Recovery Mode.
_ensureInRecoveryMode();
_ensureInRecoveryMode();
8,988
57
// Get Asset Token
address _assetTokenAddress = bridge.getAssetTokenAddress(); IERC20 _assetToken = IERC20(_assetTokenAddress);
address _assetTokenAddress = bridge.getAssetTokenAddress(); IERC20 _assetToken = IERC20(_assetTokenAddress);
27,138
50
// check if the listing can be whitelisted
function canBeWhitelisted(bytes32 _listingHash) public view returns (bool) { uint challengeId = listings[_listingHash].challengeId; // Ensures that the application was made, // the application period has ended, // the listingHash can be whitelisted, // and either: the challengeId == 0, or the challenge has been resolved. /* solium-disable */ if (appWasMade(_listingHash) && listings[_listingHash].applicationExpiry < now && !isWhitelisted(_listingHash) && (challengeId == 0 || challenges[challengeId].resolved == true)) { return true; } return false; }
function canBeWhitelisted(bytes32 _listingHash) public view returns (bool) { uint challengeId = listings[_listingHash].challengeId; // Ensures that the application was made, // the application period has ended, // the listingHash can be whitelisted, // and either: the challengeId == 0, or the challenge has been resolved. /* solium-disable */ if (appWasMade(_listingHash) && listings[_listingHash].applicationExpiry < now && !isWhitelisted(_listingHash) && (challengeId == 0 || challenges[challengeId].resolved == true)) { return true; } return false; }
44,738
137
// Determines the amount of Scale to create based on the number of seconds that have passed/_timeInSeconds is the time passed in seconds to mint for/_mintRate the mint rate per second / return uint with the calculated number of new tokens to mint
function calculateMintTotal(uint _timeInSeconds, uint _mintRate) pure private returns(uint mintAmount) { // Calculates the amount of tokens to mint based upon the number of seconds passed return(_timeInSeconds.mul(_mintRate)); }
function calculateMintTotal(uint _timeInSeconds, uint _mintRate) pure private returns(uint mintAmount) { // Calculates the amount of tokens to mint based upon the number of seconds passed return(_timeInSeconds.mul(_mintRate)); }
65,791
8
// This is a new declaration
attestationRegistry[declarationHash] = PublicSelfDeclaration( true, numberDeclarations, declarationHash, offchainURI, payload, msg.sender, 1 );
attestationRegistry[declarationHash] = PublicSelfDeclaration( true, numberDeclarations, declarationHash, offchainURI, payload, msg.sender, 1 );
14,226
58
// require that the transaction has not been reported yet by the reporter
require(!reportedTxs[_txId][msg.sender], "ERR_ALREADY_REPORTED");
require(!reportedTxs[_txId][msg.sender], "ERR_ALREADY_REPORTED");
10,650
287
// SET MANAGER ONLY. Edit the manager fee recipient_setToken Instance of the SetToken _managerFeeRecipientManager fee recipient /
function editFeeRecipient(ISetToken _setToken, address _managerFeeRecipient) external onlyManagerAndValidSet(_setToken) { require(_managerFeeRecipient != address(0), "Fee recipient must not be 0 address"); navIssuanceSettings[_setToken].feeRecipient = _managerFeeRecipient; }
function editFeeRecipient(ISetToken _setToken, address _managerFeeRecipient) external onlyManagerAndValidSet(_setToken) { require(_managerFeeRecipient != address(0), "Fee recipient must not be 0 address"); navIssuanceSettings[_setToken].feeRecipient = _managerFeeRecipient; }
40,594
15
// modifier inState()
modifier inState(State _state){ require(state == _state); _; }
modifier inState(State _state){ require(state == _state); _; }
22,904
96
// Redeem arTokens for underlying pTokens. - Must increase referrer bal 0.25% (in tests) if there is a referrer, beneficiary bal if not. - Important: must return correct value of tokens in all scenarios. Conversion from arToken to pToken - (referral fee - feePerBase amounts - liquidator bonus). - Must take exactly _arAmount from user and deposit to this address. - Important: must save all fees correctly. _arAmount Amount of arTokens to redeem. _referrer The address that referred the user to arShield./
{ address user = msg.sender; uint256 pAmount = pValue(_arAmount); arToken.transferFrom(user, address(this), _arAmount); arToken.burn(_arAmount); ( uint256 fee, uint256 refFee, uint256 totalFees, uint256[] memory newFees ) = _findFees(pAmount); pToken.transfer(user, pAmount - fee); _saveFees(newFees, _referrer, refFee); // If we don't update this here, users will get stuck paying for coverage that they are not using. uint256 ethValue = getEthValue(pToken.balanceOf( address(this) ) - totalFees); for (uint256 i = 0; i < covBases.length; i++) covBases[i].updateShield(ethValue); controller.emitAction( msg.sender, _referrer, address(this), address(pToken), pAmount, refFee, false ); emit Redemption(user, _arAmount, block.timestamp); }
{ address user = msg.sender; uint256 pAmount = pValue(_arAmount); arToken.transferFrom(user, address(this), _arAmount); arToken.burn(_arAmount); ( uint256 fee, uint256 refFee, uint256 totalFees, uint256[] memory newFees ) = _findFees(pAmount); pToken.transfer(user, pAmount - fee); _saveFees(newFees, _referrer, refFee); // If we don't update this here, users will get stuck paying for coverage that they are not using. uint256 ethValue = getEthValue(pToken.balanceOf( address(this) ) - totalFees); for (uint256 i = 0; i < covBases.length; i++) covBases[i].updateShield(ethValue); controller.emitAction( msg.sender, _referrer, address(this), address(pToken), pAmount, refFee, false ); emit Redemption(user, _arAmount, block.timestamp); }
27,453
64
// check current block is inside closed interval [startBlock, endBlock]
modifier inRunningBlock() { require(block.number >= startBlock); require(block.number < endBlock); _; }
modifier inRunningBlock() { require(block.number >= startBlock); require(block.number < endBlock); _; }
24,482
13
// borrower can repay the loan inputing the loan ID (to handle multiple loans x borrower)
function repay_full_loan(uint256 loan_idx) external payable { require(borrowers[msg.sender].amount_borrowed > 0); require(loans[msg.sender][loan_idx].amount_borrowed > 0); uint256 loan_amount = loans[msg.sender][loan_idx].amount_borrowed; uint256 total_fee = get_fee_accumulated_on_loan(loan_idx); uint256 total_to_repay = loan_amount + total_fee; require(msg.value >= total_to_repay); if(msg.value > total_to_repay){ uint256 change = msg.value - total_to_repay; borrowers[msg.sender].amount_borrowed = borrowers[msg.sender].amount_borrowed - loan_amount; loans[msg.sender][loan_idx].amount_borrowed = 0; msg.sender.transfer(change); } require(total_fee>0); send_fees_to_pool(total_fee); }
function repay_full_loan(uint256 loan_idx) external payable { require(borrowers[msg.sender].amount_borrowed > 0); require(loans[msg.sender][loan_idx].amount_borrowed > 0); uint256 loan_amount = loans[msg.sender][loan_idx].amount_borrowed; uint256 total_fee = get_fee_accumulated_on_loan(loan_idx); uint256 total_to_repay = loan_amount + total_fee; require(msg.value >= total_to_repay); if(msg.value > total_to_repay){ uint256 change = msg.value - total_to_repay; borrowers[msg.sender].amount_borrowed = borrowers[msg.sender].amount_borrowed - loan_amount; loans[msg.sender][loan_idx].amount_borrowed = 0; msg.sender.transfer(change); } require(total_fee>0); send_fees_to_pool(total_fee); }
35,949
83
// Connect to gene contract. That way we can update that contract and add more fighters./
function setGeneContractAddress(address _address) external contract_onlyOwner returns (bool success) { geneContract = GeneInterface(_address); return true; }
function setGeneContractAddress(address _address) external contract_onlyOwner returns (bool success) { geneContract = GeneInterface(_address); return true; }
47,297
12
// amount keeps track of number of unclaimed tokenIds
uint256 amount = 0;
uint256 amount = 0;
25,963
102
// contract sender fee rate
uint256 public contractFeeRateNumerator; uint256 public contractFeeRateDenominator;
uint256 public contractFeeRateNumerator; uint256 public contractFeeRateDenominator;
17,948
194
// creator address has to be set during deploy via constructor only.
address public singleCreatorAddress; address public signerAddress; bool public enableExternalMinting; bool public canRoyaltyRegistryChange = true;
address public singleCreatorAddress; address public signerAddress; bool public enableExternalMinting; bool public canRoyaltyRegistryChange = true;
81,890
0
// The tokenId of the next token to be minted.
uint256 _currentIndex;
uint256 _currentIndex;
30,015
125
// Process withdrawal fee
uint256 _fee = _processWithdrawalFee(_toWithdraw);
uint256 _fee = _processWithdrawalFee(_toWithdraw);
8,242
577
// VAI Integration^
(mErr, vars.sumBorrowPlusEffects) = addUInt(vars.sumBorrowPlusEffects, mintedVAIs[account]); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); }
(mErr, vars.sumBorrowPlusEffects) = addUInt(vars.sumBorrowPlusEffects, mintedVAIs[account]); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); }
38,749
105
// Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. Tokens start existing when they are minted (`_mint`),and stop existing when they are burned (`_burn`). /
function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); }
function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); }
27,098
250
// together with {getRoleMember} to enumerate all bearers of a role. /
function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); }
function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); }
674
44
// rate category has to be initiated
require(rates[rate].chi != 0, "rate-group-not-set"); loanRates[loan] = rate;
require(rates[rate].chi != 0, "rate-group-not-set"); loanRates[loan] = rate;
28,986
103
// Adds a new allocation for the contributor with address _contributor
function addAllocation(address _contributor, uint256 _amount, uint256 _bonus, uint8 _phase) public onlyAdminAndOps returns (bool) { require(_contributor != address(0)); require(_contributor != address(this)); // Can't create or update an allocation if the amount of tokens to be allocated is not greater than zero require(_amount > 0); // Can't create an allocation if the contribution phase is not in the ContributionPhase enum ContributionPhase _contributionPhase = ContributionPhase(_phase); require(_contributionPhase == ContributionPhase.PreSaleContribution || _contributionPhase == ContributionPhase.PartnerContribution); uint256 totalAmount = _amount.add(_bonus); uint256 totalGrantedAllocation = 0; uint256 totalGrantedBonusAllocation = 0; // Fetch the allocation from the respective mapping and updates the granted amount of tokens if (_contributionPhase == ContributionPhase.PreSaleContribution) { totalGrantedAllocation = presaleAllocations[_contributor].amountGranted.add(_amount); totalGrantedBonusAllocation = presaleAllocations[_contributor].amountBonusGranted.add(_bonus); presaleAllocations[_contributor] = Allocation(totalGrantedAllocation, totalGrantedBonusAllocation, false); } else if (_contributionPhase == ContributionPhase.PartnerContribution) { totalGrantedAllocation = partnerAllocations[_contributor].amountGranted.add(_amount); totalGrantedBonusAllocation = partnerAllocations[_contributor].amountBonusGranted.add(_bonus); partnerAllocations[_contributor] = Allocation(totalGrantedAllocation, totalGrantedBonusAllocation, false); } // Updates the contract data totalPrivateAllocation = totalPrivateAllocation.add(totalAmount); AllocationGranted(_contributor, totalAmount, _phase); return true; }
function addAllocation(address _contributor, uint256 _amount, uint256 _bonus, uint8 _phase) public onlyAdminAndOps returns (bool) { require(_contributor != address(0)); require(_contributor != address(this)); // Can't create or update an allocation if the amount of tokens to be allocated is not greater than zero require(_amount > 0); // Can't create an allocation if the contribution phase is not in the ContributionPhase enum ContributionPhase _contributionPhase = ContributionPhase(_phase); require(_contributionPhase == ContributionPhase.PreSaleContribution || _contributionPhase == ContributionPhase.PartnerContribution); uint256 totalAmount = _amount.add(_bonus); uint256 totalGrantedAllocation = 0; uint256 totalGrantedBonusAllocation = 0; // Fetch the allocation from the respective mapping and updates the granted amount of tokens if (_contributionPhase == ContributionPhase.PreSaleContribution) { totalGrantedAllocation = presaleAllocations[_contributor].amountGranted.add(_amount); totalGrantedBonusAllocation = presaleAllocations[_contributor].amountBonusGranted.add(_bonus); presaleAllocations[_contributor] = Allocation(totalGrantedAllocation, totalGrantedBonusAllocation, false); } else if (_contributionPhase == ContributionPhase.PartnerContribution) { totalGrantedAllocation = partnerAllocations[_contributor].amountGranted.add(_amount); totalGrantedBonusAllocation = partnerAllocations[_contributor].amountBonusGranted.add(_bonus); partnerAllocations[_contributor] = Allocation(totalGrantedAllocation, totalGrantedBonusAllocation, false); } // Updates the contract data totalPrivateAllocation = totalPrivateAllocation.add(totalAmount); AllocationGranted(_contributor, totalAmount, _phase); return true; }
5,779
9
// map staking's token id to each nft
mapping(uint256 => Staking) public allNFTStaking;
mapping(uint256 => Staking) public allNFTStaking;
40,830
14
// check if arbitrage still exists before make arbitrage
function checkArbitrageStillExists(Exchange[] memory exchanges, uint amountIn) public view returns (uint) { uint amountToSwap = amountIn; for(uint i = 0; i < exchanges.length; i++){ if(exchanges[i].version == 2){ uint[] memory amountOutMin = IUniswapV2Route(exchanges[i].route).getAmountsOut( amountToSwap, exchanges[i].pair); amountToSwap = amountOutMin[amountOutMin.length-1]; } else{ IUniswapV1Factory factoryV1 = IUniswapV1Factory(exchanges[i].route); if(isWBNB(exchanges[i].pair[0])){ IUniswapV1Exchange exchangeV1 = IUniswapV1Exchange(factoryV1.getExchange(exchanges[i].pair[1])); uint amountOutMin = exchangeV1.getEthToTokenInputPrice(amountToSwap); amountToSwap = amountOutMin; } else{ IUniswapV1Exchange exchangeV1 = IUniswapV1Exchange(factoryV1.getExchange(exchanges[i].pair[0])); uint amountOutMin = exchangeV1.getTokenToEthInputPrice(amountToSwap); amountToSwap = amountOutMin; } } } return amountToSwap; }
function checkArbitrageStillExists(Exchange[] memory exchanges, uint amountIn) public view returns (uint) { uint amountToSwap = amountIn; for(uint i = 0; i < exchanges.length; i++){ if(exchanges[i].version == 2){ uint[] memory amountOutMin = IUniswapV2Route(exchanges[i].route).getAmountsOut( amountToSwap, exchanges[i].pair); amountToSwap = amountOutMin[amountOutMin.length-1]; } else{ IUniswapV1Factory factoryV1 = IUniswapV1Factory(exchanges[i].route); if(isWBNB(exchanges[i].pair[0])){ IUniswapV1Exchange exchangeV1 = IUniswapV1Exchange(factoryV1.getExchange(exchanges[i].pair[1])); uint amountOutMin = exchangeV1.getEthToTokenInputPrice(amountToSwap); amountToSwap = amountOutMin; } else{ IUniswapV1Exchange exchangeV1 = IUniswapV1Exchange(factoryV1.getExchange(exchanges[i].pair[0])); uint amountOutMin = exchangeV1.getTokenToEthInputPrice(amountToSwap); amountToSwap = amountOutMin; } } } return amountToSwap; }
28,691
55
// Posible ICO states.
enum State
enum State
2,418
29
// administrative to upload the names and images associated with each trait traitType the trait type to upload the traits for (see traitTypes for a mapping) traits the names and base64 encoded PNGs for each trait /
function uploadTraits( uint8 traitType, uint8[] calldata traitIds, Trait[] calldata traits
function uploadTraits( uint8 traitType, uint8[] calldata traitIds, Trait[] calldata traits
6,755
28
// RETURNS ONLY STAKERS BALANCE
function getPenaltyRewardsAmounts( address[] memory tokens
function getPenaltyRewardsAmounts( address[] memory tokens
5,576
5
// Function to withdraw funds from the donation pool/Certain portion of funds will be transferred to the Treasury and QF pool
function withdrawFunds(uint256 _grantId, address _token) external { if (_grantId >= hypercert.latestUnusedId()) { revert GrantNotExist(); } require(hypercert.grantEnded(_grantId), "Round not ended"); require(hypercert.grantOwner(_grantId) == msg.sender, "Caller not creator"); require(allowedTokens[_token] == true, "Token is not supported"); uint256 amountToQFPool = donationPoolFundsByGrantId[_grantId][_token] * precision * quadraticFundingPoolShare / 100 / precision; uint256 amountToTreasury = donationPoolFundsByGrantId[_grantId][_token] * precision * treasuryShare / 100 / precision; quadraticFundingPoolFunds[_token] += amountToQFPool; treasuryFunds[_token] += amountToTreasury; uint256 amountToSend = donationPoolFundsByGrantId[_grantId][_token] - amountToQFPool - amountToTreasury; bool success = IERC20Decimal(_token).transfer( msg.sender, amountToSend ); require(success, "Transaction was not successful"); emit FundsTransferredToTreasuryAndQFPools(amountToTreasury, amountToQFPool); emit FundsWithdrawed(_grantId, amountToSend, msg.sender); //update the value of funds in the donation pool donationPoolFunds -= donationPoolFundsByGrantId[_grantId][_token]; }
function withdrawFunds(uint256 _grantId, address _token) external { if (_grantId >= hypercert.latestUnusedId()) { revert GrantNotExist(); } require(hypercert.grantEnded(_grantId), "Round not ended"); require(hypercert.grantOwner(_grantId) == msg.sender, "Caller not creator"); require(allowedTokens[_token] == true, "Token is not supported"); uint256 amountToQFPool = donationPoolFundsByGrantId[_grantId][_token] * precision * quadraticFundingPoolShare / 100 / precision; uint256 amountToTreasury = donationPoolFundsByGrantId[_grantId][_token] * precision * treasuryShare / 100 / precision; quadraticFundingPoolFunds[_token] += amountToQFPool; treasuryFunds[_token] += amountToTreasury; uint256 amountToSend = donationPoolFundsByGrantId[_grantId][_token] - amountToQFPool - amountToTreasury; bool success = IERC20Decimal(_token).transfer( msg.sender, amountToSend ); require(success, "Transaction was not successful"); emit FundsTransferredToTreasuryAndQFPools(amountToTreasury, amountToQFPool); emit FundsWithdrawed(_grantId, amountToSend, msg.sender); //update the value of funds in the donation pool donationPoolFunds -= donationPoolFundsByGrantId[_grantId][_token]; }
28,650
222
// Sells our harvested CVX into the selected output (ETH).
function _sellConvexforETH(uint256 _convexAmount) internal { address[] memory convexTokenPath = new address[](2); convexTokenPath[0] = address(convexToken); convexTokenPath[1] = address(weth); IUniswapV2Router02(sushiswap).swapExactTokensForETH( _convexAmount, uint256(0), convexTokenPath, address(this), block.timestamp ); }
function _sellConvexforETH(uint256 _convexAmount) internal { address[] memory convexTokenPath = new address[](2); convexTokenPath[0] = address(convexToken); convexTokenPath[1] = address(weth); IUniswapV2Router02(sushiswap).swapExactTokensForETH( _convexAmount, uint256(0), convexTokenPath, address(this), block.timestamp ); }
53,974
33
// config()Get the configuration of this registrar. /
function config() constant returns (address ens, bytes32 nodeHash, address admin, uint256 fee, address defaultResolver) { ens = _ens; nodeHash = _nodeHash; admin = _admin; fee = _fee; defaultResolver = _defaultResolver; }
function config() constant returns (address ens, bytes32 nodeHash, address admin, uint256 fee, address defaultResolver) { ens = _ens; nodeHash = _nodeHash; admin = _admin; fee = _fee; defaultResolver = _defaultResolver; }
7,311
124
// Emitted when an account's position had a liquidation./receiver address which repaid the previously borrowed amount./borrower address which had the original debt./assets amount of the asset that were repaid./lendersAssets incentive paid to lenders./seizeMarket address of the asset that were seized by the liquidator./seizedAssets amount seized of the collateral.
event Liquidate( address indexed receiver, address indexed borrower, uint256 assets, uint256 lendersAssets, Market indexed seizeMarket, uint256 seizedAssets );
event Liquidate( address indexed receiver, address indexed borrower, uint256 assets, uint256 lendersAssets, Market indexed seizeMarket, uint256 seizedAssets );
24,445
20
// send all donations to the msg.sender (onlyOwner of this contract)
function withdrawDonationsTo(address _out)public;
function withdrawDonationsTo(address _out)public;
30,949
0
// Token -> Price
mapping (address => uint256) prices;
mapping (address => uint256) prices;
54,036
36
// The personal valuation submitted must be greater than the current valuation plus the bid if after the withdrawal lock.
require(_personalCap >= self.totalValuation + _amount);
require(_personalCap >= self.totalValuation + _amount);
45,472
16
// A sequence of items with the ability to efficiently push and pop items (i.e. insert and remove) on both ends ofthe sequence (called front and back). Among other access patterns, it can be used to implement efficient LIFO and
* FIFO queues. Storage use is optimized, and all operations are O(1) constant time. This includes {clear}, given that * the existing queue contents are left in storage. * * The struct is called `Bytes32Deque`. Other types can be cast to and from `bytes32`. This data structure can only be * used in storage, and not in memory. * ``` * DoubleEndedQueue.Bytes32Deque queue; * ``` * * _Available since v4.6._ */ library DoubleEndedQueueUpgradeable { /** * @dev An operation (e.g. {front}) couldn't be completed due to the queue being empty. */ error Empty(); /** * @dev An operation (e.g. {at}) couldn't be completed due to an index being out of bounds. */ error OutOfBounds(); /** * @dev Indices are signed integers because the queue can grow in any direction. They are 128 bits so begin and end * are packed in a single storage slot for efficient access. Since the items are added one at a time we can safely * assume that these 128-bit indices will not overflow, and use unchecked arithmetic. * * Struct members have an underscore prefix indicating that they are "private" and should not be read or written to * directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and * lead to unexpected behavior. * * Indices are in the range [begin, end) which means the first item is at data[begin] and the last item is at * data[end - 1]. */ struct Bytes32Deque { int128 _begin; int128 _end; mapping(int128 => bytes32) _data; } /** * @dev Inserts an item at the end of the queue. */ function pushBack(Bytes32Deque storage deque, bytes32 value) internal { int128 backIndex = deque._end; deque._data[backIndex] = value; unchecked { deque._end = backIndex + 1; } } /** * @dev Removes the item at the end of the queue and returns it. * * Reverts with `Empty` if the queue is empty. */ function popBack(Bytes32Deque storage deque) internal returns (bytes32 value) { if (empty(deque)) revert Empty(); int128 backIndex; unchecked { backIndex = deque._end - 1; } value = deque._data[backIndex]; delete deque._data[backIndex]; deque._end = backIndex; } /** * @dev Inserts an item at the beginning of the queue. */ function pushFront(Bytes32Deque storage deque, bytes32 value) internal { int128 frontIndex; unchecked { frontIndex = deque._begin - 1; } deque._data[frontIndex] = value; deque._begin = frontIndex; } /** * @dev Removes the item at the beginning of the queue and returns it. * * Reverts with `Empty` if the queue is empty. */ function popFront(Bytes32Deque storage deque) internal returns (bytes32 value) { if (empty(deque)) revert Empty(); int128 frontIndex = deque._begin; value = deque._data[frontIndex]; delete deque._data[frontIndex]; unchecked { deque._begin = frontIndex + 1; } } /** * @dev Returns the item at the beginning of the queue. * * Reverts with `Empty` if the queue is empty. */ function front(Bytes32Deque storage deque) internal view returns (bytes32 value) { if (empty(deque)) revert Empty(); int128 frontIndex = deque._begin; return deque._data[frontIndex]; } /** * @dev Returns the item at the end of the queue. * * Reverts with `Empty` if the queue is empty. */ function back(Bytes32Deque storage deque) internal view returns (bytes32 value) { if (empty(deque)) revert Empty(); int128 backIndex; unchecked { backIndex = deque._end - 1; } return deque._data[backIndex]; } /** * @dev Return the item at a position in the queue given by `index`, with the first item at 0 and last item at * `length(deque) - 1`. * * Reverts with `OutOfBounds` if the index is out of bounds. */ function at(Bytes32Deque storage deque, uint256 index) internal view returns (bytes32 value) { // int256(deque._begin) is a safe upcast int128 idx = SafeCastUpgradeable.toInt128(int256(deque._begin) + SafeCastUpgradeable.toInt256(index)); if (idx >= deque._end) revert OutOfBounds(); return deque._data[idx]; } /** * @dev Resets the queue back to being empty. * * NOTE: The current items are left behind in storage. This does not affect the functioning of the queue, but misses * out on potential gas refunds. */ function clear(Bytes32Deque storage deque) internal { deque._begin = 0; deque._end = 0; } /** * @dev Returns the number of items in the queue. */ function length(Bytes32Deque storage deque) internal view returns (uint256) { // The interface preserves the invariant that begin <= end so we assume this will not overflow. // We also assume there are at most int256.max items in the queue. unchecked { return uint256(int256(deque._end) - int256(deque._begin)); } } /** * @dev Returns true if the queue is empty. */ function empty(Bytes32Deque storage deque) internal view returns (bool) { return deque._end <= deque._begin; } }
* FIFO queues. Storage use is optimized, and all operations are O(1) constant time. This includes {clear}, given that * the existing queue contents are left in storage. * * The struct is called `Bytes32Deque`. Other types can be cast to and from `bytes32`. This data structure can only be * used in storage, and not in memory. * ``` * DoubleEndedQueue.Bytes32Deque queue; * ``` * * _Available since v4.6._ */ library DoubleEndedQueueUpgradeable { /** * @dev An operation (e.g. {front}) couldn't be completed due to the queue being empty. */ error Empty(); /** * @dev An operation (e.g. {at}) couldn't be completed due to an index being out of bounds. */ error OutOfBounds(); /** * @dev Indices are signed integers because the queue can grow in any direction. They are 128 bits so begin and end * are packed in a single storage slot for efficient access. Since the items are added one at a time we can safely * assume that these 128-bit indices will not overflow, and use unchecked arithmetic. * * Struct members have an underscore prefix indicating that they are "private" and should not be read or written to * directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and * lead to unexpected behavior. * * Indices are in the range [begin, end) which means the first item is at data[begin] and the last item is at * data[end - 1]. */ struct Bytes32Deque { int128 _begin; int128 _end; mapping(int128 => bytes32) _data; } /** * @dev Inserts an item at the end of the queue. */ function pushBack(Bytes32Deque storage deque, bytes32 value) internal { int128 backIndex = deque._end; deque._data[backIndex] = value; unchecked { deque._end = backIndex + 1; } } /** * @dev Removes the item at the end of the queue and returns it. * * Reverts with `Empty` if the queue is empty. */ function popBack(Bytes32Deque storage deque) internal returns (bytes32 value) { if (empty(deque)) revert Empty(); int128 backIndex; unchecked { backIndex = deque._end - 1; } value = deque._data[backIndex]; delete deque._data[backIndex]; deque._end = backIndex; } /** * @dev Inserts an item at the beginning of the queue. */ function pushFront(Bytes32Deque storage deque, bytes32 value) internal { int128 frontIndex; unchecked { frontIndex = deque._begin - 1; } deque._data[frontIndex] = value; deque._begin = frontIndex; } /** * @dev Removes the item at the beginning of the queue and returns it. * * Reverts with `Empty` if the queue is empty. */ function popFront(Bytes32Deque storage deque) internal returns (bytes32 value) { if (empty(deque)) revert Empty(); int128 frontIndex = deque._begin; value = deque._data[frontIndex]; delete deque._data[frontIndex]; unchecked { deque._begin = frontIndex + 1; } } /** * @dev Returns the item at the beginning of the queue. * * Reverts with `Empty` if the queue is empty. */ function front(Bytes32Deque storage deque) internal view returns (bytes32 value) { if (empty(deque)) revert Empty(); int128 frontIndex = deque._begin; return deque._data[frontIndex]; } /** * @dev Returns the item at the end of the queue. * * Reverts with `Empty` if the queue is empty. */ function back(Bytes32Deque storage deque) internal view returns (bytes32 value) { if (empty(deque)) revert Empty(); int128 backIndex; unchecked { backIndex = deque._end - 1; } return deque._data[backIndex]; } /** * @dev Return the item at a position in the queue given by `index`, with the first item at 0 and last item at * `length(deque) - 1`. * * Reverts with `OutOfBounds` if the index is out of bounds. */ function at(Bytes32Deque storage deque, uint256 index) internal view returns (bytes32 value) { // int256(deque._begin) is a safe upcast int128 idx = SafeCastUpgradeable.toInt128(int256(deque._begin) + SafeCastUpgradeable.toInt256(index)); if (idx >= deque._end) revert OutOfBounds(); return deque._data[idx]; } /** * @dev Resets the queue back to being empty. * * NOTE: The current items are left behind in storage. This does not affect the functioning of the queue, but misses * out on potential gas refunds. */ function clear(Bytes32Deque storage deque) internal { deque._begin = 0; deque._end = 0; } /** * @dev Returns the number of items in the queue. */ function length(Bytes32Deque storage deque) internal view returns (uint256) { // The interface preserves the invariant that begin <= end so we assume this will not overflow. // We also assume there are at most int256.max items in the queue. unchecked { return uint256(int256(deque._end) - int256(deque._begin)); } } /** * @dev Returns true if the queue is empty. */ function empty(Bytes32Deque storage deque) internal view returns (bool) { return deque._end <= deque._begin; } }
40,369
42
// Info of each user
struct UserInfo { uint256 amount; uint256 tokensClaimed; }
struct UserInfo { uint256 amount; uint256 tokensClaimed; }
6,707