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
97
// https:docs.synthetix.io/contracts/source/interfaces/ifeepool
interface IFeePool { // Views // solhint-disable-next-line func-name-mixedcase function FEE_ADDRESS() external view returns (address); function feesAvailable(address account) external view returns (uint, uint); function feePeriodDuration() external view returns (uint); function isFeesClaimable(address account) external view returns (bool); function targetThreshold() external view returns (uint); function totalFeesAvailable() external view returns (uint); function totalRewardsAvailable() external view returns (uint); // Mutative Functions function claimFees() external returns (bool); function claimOnBehalf(address claimingForAddress) external returns (bool); function closeCurrentFeePeriod() external; // Restricted: used internally to Synthetix function appendAccountIssuanceRecord( address account, uint lockedAmount, uint debtEntryIndex ) external; function recordFeePaid(uint sUSDAmount) external; function setRewardsToDistribute(uint amount) external; }
interface IFeePool { // Views // solhint-disable-next-line func-name-mixedcase function FEE_ADDRESS() external view returns (address); function feesAvailable(address account) external view returns (uint, uint); function feePeriodDuration() external view returns (uint); function isFeesClaimable(address account) external view returns (bool); function targetThreshold() external view returns (uint); function totalFeesAvailable() external view returns (uint); function totalRewardsAvailable() external view returns (uint); // Mutative Functions function claimFees() external returns (bool); function claimOnBehalf(address claimingForAddress) external returns (bool); function closeCurrentFeePeriod() external; // Restricted: used internally to Synthetix function appendAccountIssuanceRecord( address account, uint lockedAmount, uint debtEntryIndex ) external; function recordFeePaid(uint sUSDAmount) external; function setRewardsToDistribute(uint amount) external; }
13,283
69
// =============================================== Events===============================================
event TokenPurchase( address indexed beneficiary, uint256 weiAmount, uint256 tokenAmount );
event TokenPurchase( address indexed beneficiary, uint256 weiAmount, uint256 tokenAmount );
14,519
5
// initialize index from random seed
uint256 idx = manySeeds[dropCt] % numberExisting + 1;
uint256 idx = manySeeds[dropCt] % numberExisting + 1;
47,896
275
// Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); }
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); }
20,491
44
// can be called by an ETH Address
function withdrawAdminFee () public nonReentrant { require (block.timestamp >= lastPaymentTime.add(paymentPeriod), "90 days have not passed since last withdrawal"); lastPaymentTime = lastPaymentTime.add(paymentPeriod); //set it to the next payment period. //local variables to save gas by reading from storage only 1x uint256 denominator = adminFeeDenominator; address recipient = laoFundAddress; for (uint256 i = 0; i < approvedTokens.length; i++) { address token = approvedTokens[i]; uint256 amount = userTokenBalances[GUILD][token] / denominator; if (amount > 0) { // otherwise skip for efficiency, only tokens with a balance userTokenBalances[GUILD][token] -= amount; userTokenBalances[recipient][token] += amount; } } // Remove Event emit WithdrawAdminFee(laoFundAddress,token, amount); } //end of withdrawAdminFee
function withdrawAdminFee () public nonReentrant { require (block.timestamp >= lastPaymentTime.add(paymentPeriod), "90 days have not passed since last withdrawal"); lastPaymentTime = lastPaymentTime.add(paymentPeriod); //set it to the next payment period. //local variables to save gas by reading from storage only 1x uint256 denominator = adminFeeDenominator; address recipient = laoFundAddress; for (uint256 i = 0; i < approvedTokens.length; i++) { address token = approvedTokens[i]; uint256 amount = userTokenBalances[GUILD][token] / denominator; if (amount > 0) { // otherwise skip for efficiency, only tokens with a balance userTokenBalances[GUILD][token] -= amount; userTokenBalances[recipient][token] += amount; } } // Remove Event emit WithdrawAdminFee(laoFundAddress,token, amount); } //end of withdrawAdminFee
63,880
31
// Events for funds deposited by fund manager during investment
event FundManagerFundsDeposited(address indexed owner, uint256 amount);
event FundManagerFundsDeposited(address indexed owner, uint256 amount);
53,929
105
// redeem effect sumBorrowPlusEffects += tokensToDenomredeemTokens
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); }
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); }
10,529
108
// Attempt to transfer ETH to a recipient Sending ETH is not guaranteed to succeedthis method will return false if it fails.We will limit the gas used in transfers, and handle failure cases. _to recipient of ETH _value amount of ETH /
function _attemptETHTransfer(address _to, uint256 _value) internal returns (bool)
function _attemptETHTransfer(address _to, uint256 _value) internal returns (bool)
38,455
89
// this is safe from overflow because `votingPeriod` and `gracePeriod` are capped so they will not combine with unix time to exceed the max uint256 value
unchecked { if (block.timestamp <= prop.creationTime + votingPeriod + gracePeriod) revert VotingNotEnded(); }
unchecked { if (block.timestamp <= prop.creationTime + votingPeriod + gracePeriod) revert VotingNotEnded(); }
9,252
104
// Sender registers an amount of IBT for the next period _user address to register to the future _amount amount of IBT to be registered called by the controller only /
function register(address _user, uint256 _amount) external;
function register(address _user, uint256 _amount) external;
23,647
11
// Presale minting
function mintPresale(uint256 _amount) public payable { uint256 supply = totalSupply(); require( presaleActive, "Sale isn't active" ); require( _amount > 0 && _amount <= MAX_MINT_PER_TX, "Can only mint between 1 and 20 tokens at once" ); require( supply + _amount <= MAX_PRESALE_SUPPLY, "Can't mint more than max supply" ); require( msg.value == price * _amount, "Wrong amount of ETH sent" ); for(uint256 i; i < _amount; i++){ _safeMint( msg.sender, supply + i ); } }
function mintPresale(uint256 _amount) public payable { uint256 supply = totalSupply(); require( presaleActive, "Sale isn't active" ); require( _amount > 0 && _amount <= MAX_MINT_PER_TX, "Can only mint between 1 and 20 tokens at once" ); require( supply + _amount <= MAX_PRESALE_SUPPLY, "Can't mint more than max supply" ); require( msg.value == price * _amount, "Wrong amount of ETH sent" ); for(uint256 i; i < _amount; i++){ _safeMint( msg.sender, supply + i ); } }
18,237
4
// generate hash
function _generateHash() internal view returns (bytes32) { return keccak256(abi.encodePacked(totalSupply, block.number, block.timestamp, msg.sender)); }
function _generateHash() internal view returns (bytes32) { return keccak256(abi.encodePacked(totalSupply, block.number, block.timestamp, msg.sender)); }
39,213
1
// Configure CCIP addresses on the stablecoin. ccipSend The address on this chain to which CCIP messages will be sent. ccipReceive The address on this chain from which CCIP messages will be received. ccipTokenPool The address where CCIP fees will be sent to when sending and receiving cross chain messages. /
function registerCcip(address ccipSend, address ccipReceive, address ccipTokenPool) external;
function registerCcip(address ccipSend, address ccipReceive, address ccipTokenPool) external;
25,991
15
// Put this event on the blockchain
FullExecution(msg.sender, _ticker, "BUY", now);
FullExecution(msg.sender, _ticker, "BUY", now);
52,573
63
// Mapping owner address to address data. Bits Layout: - [0..63]`balance` - [64..127]`numberMinted` - [128..191] `numberBurned` - [192..255] `aux`
mapping(address => uint256) private _packedAddressData;
mapping(address => uint256) private _packedAddressData;
369
161
// Cancel an auction./_deedId The identifier of the deed for which the auction should be cancelled./auction The auction to cancel.
function _cancelAuction(uint256 _deedId, Auction auction) internal { // Remove the auction _removeAuction(_deedId); // Transfer the deed back to the seller _transfer(auction.seller, _deedId); // Trigger auction cancelled event. AuctionCancelled(_deedId); }
function _cancelAuction(uint256 _deedId, Auction auction) internal { // Remove the auction _removeAuction(_deedId); // Transfer the deed back to the seller _transfer(auction.seller, _deedId); // Trigger auction cancelled event. AuctionCancelled(_deedId); }
29,484
116
// _ald The address of ALD token./_treasury The address of treasury.
constructor(address _ald, address _treasury) { require(_ald != address(0), "DirectBondDepositor: not zero address"); require(_treasury != address(0), "DirectBondDepositor: not zero address"); ald = _ald; treasury = _treasury; _initializer = msg.sender; }
constructor(address _ald, address _treasury) { require(_ald != address(0), "DirectBondDepositor: not zero address"); require(_treasury != address(0), "DirectBondDepositor: not zero address"); ald = _ald; treasury = _treasury; _initializer = msg.sender; }
29,551
14
// Exchanges between ETH and wStETH index 0: ETH index 1: wStETH/
contract LidoBridgeSwapper is ZkSyncBridgeSwapper { // The address of the stEth token address public immutable stEth; // The address of the wrapped stEth token address public immutable wStEth; // The address of the stEth/Eth Curve pool address public immutable stEthPool; // The referral address for Lido address public immutable lidoReferral; constructor( address _zkSync, address _l2Account, address _wStEth, address _stEthPool, address _lidoReferral ) ZkSyncBridgeSwapper(_zkSync, _l2Account) { wStEth = _wStEth; address _stEth = IWstETH(_wStEth).stETH(); require(_stEth == ICurvePool(_stEthPool).coins(1), "stEth mismatch"); stEth = _stEth; stEthPool = _stEthPool; lidoReferral = _lidoReferral; } function exchange(uint256 _indexIn, uint256 _indexOut, uint256 _amountIn) external override returns (uint256 amountOut) { require(_indexIn + _indexOut == 1, "invalid indexes"); if (_indexIn == 0) { transferFromZkSync(ETH_TOKEN); amountOut = swapEthForStEth(_amountIn); transferToZkSync(wStEth, amountOut); emit Swapped(ETH_TOKEN, _amountIn, wStEth, amountOut); } else { transferFromZkSync(wStEth); amountOut = swapStEthForEth(_amountIn); transferToZkSync(ETH_TOKEN, amountOut); emit Swapped(wStEth, _amountIn, ETH_TOKEN, amountOut); } } /** * @dev Swaps ETH for wrapped stETH and deposits the resulting wstETH to the ZkSync bridge. * First withdraws ETH from the bridge if there is a pending balance. * @param _amountIn The amount of ETH to swap. */ function swapEthForStEth(uint256 _amountIn) internal returns (uint256) { // swap Eth for stEth on the Lido contract ILido(stEth).submit{value: _amountIn}(lidoReferral); // approve the wStEth contract to take the stEth IERC20(stEth).approve(wStEth, _amountIn); // wrap to wStEth and return deposited amount return IWstETH(wStEth).wrap(_amountIn); } /** * @dev Swaps wrapped stETH for ETH and deposits the resulting ETH to the ZkSync bridge. * First withdraws wrapped stETH from the bridge if there is a pending balance. * @param _amountIn The amount of wrapped stETH to swap. */ function swapStEthForEth(uint256 _amountIn) internal returns (uint256) { // unwrap to stEth uint256 unwrapped = IWstETH(wStEth).unwrap(_amountIn); // approve pool bool success = IERC20(stEth).approve(stEthPool, unwrapped); require(success, "approve failed"); // swap stEth for ETH on Curve and return deposited amount return ICurvePool(stEthPool).exchange(1, 0, unwrapped, getMinAmountOut(unwrapped)); } }
contract LidoBridgeSwapper is ZkSyncBridgeSwapper { // The address of the stEth token address public immutable stEth; // The address of the wrapped stEth token address public immutable wStEth; // The address of the stEth/Eth Curve pool address public immutable stEthPool; // The referral address for Lido address public immutable lidoReferral; constructor( address _zkSync, address _l2Account, address _wStEth, address _stEthPool, address _lidoReferral ) ZkSyncBridgeSwapper(_zkSync, _l2Account) { wStEth = _wStEth; address _stEth = IWstETH(_wStEth).stETH(); require(_stEth == ICurvePool(_stEthPool).coins(1), "stEth mismatch"); stEth = _stEth; stEthPool = _stEthPool; lidoReferral = _lidoReferral; } function exchange(uint256 _indexIn, uint256 _indexOut, uint256 _amountIn) external override returns (uint256 amountOut) { require(_indexIn + _indexOut == 1, "invalid indexes"); if (_indexIn == 0) { transferFromZkSync(ETH_TOKEN); amountOut = swapEthForStEth(_amountIn); transferToZkSync(wStEth, amountOut); emit Swapped(ETH_TOKEN, _amountIn, wStEth, amountOut); } else { transferFromZkSync(wStEth); amountOut = swapStEthForEth(_amountIn); transferToZkSync(ETH_TOKEN, amountOut); emit Swapped(wStEth, _amountIn, ETH_TOKEN, amountOut); } } /** * @dev Swaps ETH for wrapped stETH and deposits the resulting wstETH to the ZkSync bridge. * First withdraws ETH from the bridge if there is a pending balance. * @param _amountIn The amount of ETH to swap. */ function swapEthForStEth(uint256 _amountIn) internal returns (uint256) { // swap Eth for stEth on the Lido contract ILido(stEth).submit{value: _amountIn}(lidoReferral); // approve the wStEth contract to take the stEth IERC20(stEth).approve(wStEth, _amountIn); // wrap to wStEth and return deposited amount return IWstETH(wStEth).wrap(_amountIn); } /** * @dev Swaps wrapped stETH for ETH and deposits the resulting ETH to the ZkSync bridge. * First withdraws wrapped stETH from the bridge if there is a pending balance. * @param _amountIn The amount of wrapped stETH to swap. */ function swapStEthForEth(uint256 _amountIn) internal returns (uint256) { // unwrap to stEth uint256 unwrapped = IWstETH(wStEth).unwrap(_amountIn); // approve pool bool success = IERC20(stEth).approve(stEthPool, unwrapped); require(success, "approve failed"); // swap stEth for ETH on Curve and return deposited amount return ICurvePool(stEthPool).exchange(1, 0, unwrapped, getMinAmountOut(unwrapped)); } }
43,181
119
// save info so as to refund purchaser after crowdsale&39;s end
remainderPurchaser = msg.sender; remainderAmount = _weiAmount.sub(_weiAmountLocalScope);
remainderPurchaser = msg.sender; remainderAmount = _weiAmount.sub(_weiAmountLocalScope);
51,759
17
// DEPOSIT TOC/
address _token, bytes _extraData) external returns(bool){ TOC TOCCall = TOC(_token); TOCCall.transferFrom(_from,this,_value); return true; }
address _token, bytes _extraData) external returns(bool){ TOC TOCCall = TOC(_token); TOCCall.transferFrom(_from,this,_value); return true; }
10,195
5
// _owner The address of the account owning tokens /_spender The address of the account able to transfer the tokens / return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
11,685
759
// We don't need to multiply by the SCALE here because the xy product had already picked up a factor of SCALE during multiplication. See the comments within the "sqrt" function.
result = PRBMath.sqrt(xy);
result = PRBMath.sqrt(xy);
34,097
13
// Unlocks the amount of collateral by burning option tokens. This mechanism ensures that users can only redeem tokens they'vepreviously lock into this contract. Options can only be burned while the series is NOT expired. amount The amount option tokens to be burned /
function unwind(uint256 amount) external virtual;
function unwind(uint256 amount) external virtual;
8,957
42
// update the state variables recordedCollateral and rewardRatioSnapshot and get all the collateral into the trove /
function _updateCollateral() private returns (uint256) { getLiquidationRewards(); uint256 startRecordedCollateral = recordedCollateral; // make sure all tokens sent to or transferred out of the contract are taken into account IERC20 token_cache = token; uint256 newRecordedCollateral; if (arbitrageParticipation) { uint256 tokenBalance = token_cache.balanceOf(address(this)); if (tokenBalance > 0) arbitrageState.arbitragePool.deposit(address(token_cache), tokenBalance); newRecordedCollateral = arbitrageState.apToken.balanceOf(address(this)); arbitrageState.lastApPrice = arbitrageState.arbitragePool.getAPtokenPrice(address(token_cache)); } else { newRecordedCollateral = token_cache.balanceOf(address(this)); } recordedCollateral = newRecordedCollateral; // getLiquidationRewards updates recordedCollateral if (newRecordedCollateral != startRecordedCollateral) { factory.updateTotalCollateral( address(token_cache), newRecordedCollateral.max(startRecordedCollateral) - newRecordedCollateral.min(startRecordedCollateral), newRecordedCollateral >= startRecordedCollateral ); } return newRecordedCollateral; }
function _updateCollateral() private returns (uint256) { getLiquidationRewards(); uint256 startRecordedCollateral = recordedCollateral; // make sure all tokens sent to or transferred out of the contract are taken into account IERC20 token_cache = token; uint256 newRecordedCollateral; if (arbitrageParticipation) { uint256 tokenBalance = token_cache.balanceOf(address(this)); if (tokenBalance > 0) arbitrageState.arbitragePool.deposit(address(token_cache), tokenBalance); newRecordedCollateral = arbitrageState.apToken.balanceOf(address(this)); arbitrageState.lastApPrice = arbitrageState.arbitragePool.getAPtokenPrice(address(token_cache)); } else { newRecordedCollateral = token_cache.balanceOf(address(this)); } recordedCollateral = newRecordedCollateral; // getLiquidationRewards updates recordedCollateral if (newRecordedCollateral != startRecordedCollateral) { factory.updateTotalCollateral( address(token_cache), newRecordedCollateral.max(startRecordedCollateral) - newRecordedCollateral.min(startRecordedCollateral), newRecordedCollateral >= startRecordedCollateral ); } return newRecordedCollateral; }
10,718
2
// Storage slot with the admin of the contract.This is the keccak-256 hash of "cvc.proxy.admin", and is validated in the constructor. /
bytes32 private constant ADMIN_SLOT = 0x2bbac3e52eee27be250d682577104e2abe776c40160cd3167b24633933100433;
bytes32 private constant ADMIN_SLOT = 0x2bbac3e52eee27be250d682577104e2abe776c40160cd3167b24633933100433;
19,128
20
// Guarantees at least a level 1 yield bonus for the early adopters
if (purchaseOrder < 11100 && bonuses == 1) { bonuses = 3; }
if (purchaseOrder < 11100 && bonuses == 1) { bonuses = 3; }
25,743
38
// construction.
* @dev Sets the values for {name} and {symbol}. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; }
* @dev Sets the values for {name} and {symbol}. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; }
6,560
240
// Constructs the FeePayer contract. Called by child contracts. _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. _finderAddress UMA protocol Finder used to discover other protocol contracts. _timerAddress Contract that stores the current time in a testing environment.Must be set to 0x0 for production environments that use live time. /
constructor( address _collateralAddress, address _finderAddress, address _timerAddress
constructor( address _collateralAddress, address _finderAddress, address _timerAddress
5,645
13
// Sends a new message to a given friend
function sendMessage(address friend_key, string calldata _msg) external { require(checkUserExists(msg.sender), "Create an account first!"); require(checkUserExists(friend_key), "User is not registered!"); require(checkAlreadyFriends(msg.sender,friend_key), "You are not friends with the given user"); bytes32 chatCode = _getChatCode(msg.sender, friend_key); message memory newMsg = message(msg.sender, block.timestamp, _msg); allMessages[chatCode].push(newMsg); }
function sendMessage(address friend_key, string calldata _msg) external { require(checkUserExists(msg.sender), "Create an account first!"); require(checkUserExists(friend_key), "User is not registered!"); require(checkAlreadyFriends(msg.sender,friend_key), "You are not friends with the given user"); bytes32 chatCode = _getChatCode(msg.sender, friend_key); message memory newMsg = message(msg.sender, block.timestamp, _msg); allMessages[chatCode].push(newMsg); }
29,656
21
// Emits a {DisableRedeemAddress} event. Requirements: - `_account` should be a registered as user. /
function disableRedeemAddress(address _account) public onlyOwner { require(_isUser(_account), "not a user"); setAttribute(getRedeemAddress(_account), CAN_BURN, 0); emit DisableRedeemAddress(_account); }
function disableRedeemAddress(address _account) public onlyOwner { require(_isUser(_account), "not a user"); setAttribute(getRedeemAddress(_account), CAN_BURN, 0); emit DisableRedeemAddress(_account); }
54,717
19
// Iterates until the max size of the bracket winner array for the current round Compares player balances in each match and assign the winner to the bracketWinner array
for ( uint256 bracketIndex = 0; bracketIndex < currentBracketSize; bracketIndex++ ) {
for ( uint256 bracketIndex = 0; bracketIndex < currentBracketSize; bracketIndex++ ) {
61,418
97
// sub is safe because we know balanceAfter is gt balanceBefore by at least fee
uint256 paid0 = balance0After - balance0Before; uint256 paid1 = balance1After - balance1Before; if (paid0 > 0) { uint8 feeProtocol0 = slot0.feeProtocol % 16; uint256 fees0 = feeProtocol0 == 0 ? 0 : paid0 / feeProtocol0; if (uint128(fees0) > 0) protocolFees.token0 += uint128(fees0); feeGrowthGlobal0X128 += FullMath.mulDiv(paid0 - fees0, FixedPoint128.Q128, _liquidity); }
uint256 paid0 = balance0After - balance0Before; uint256 paid1 = balance1After - balance1Before; if (paid0 > 0) { uint8 feeProtocol0 = slot0.feeProtocol % 16; uint256 fees0 = feeProtocol0 == 0 ? 0 : paid0 / feeProtocol0; if (uint128(fees0) > 0) protocolFees.token0 += uint128(fees0); feeGrowthGlobal0X128 += FullMath.mulDiv(paid0 - fees0, FixedPoint128.Q128, _liquidity); }
6,352
3
// staking start timestamp
mapping(address => uint256) public startTime;
mapping(address => uint256) public startTime;
57,730
174
// move the SNX into the deposit escrow
synthetixERC20().transferFrom(msg.sender, synthetixBridgeEscrow(), amount); _depositReward(msg.sender, amount);
synthetixERC20().transferFrom(msg.sender, synthetixBridgeEscrow(), amount); _depositReward(msg.sender, amount);
19,608
134
// Set self-call context to call _executeActionWithAtomicBatchCallsAtomic.
_selfCallContext = this.executeActionWithAtomicBatchCalls.selector;
_selfCallContext = this.executeActionWithAtomicBatchCalls.selector;
34,598
161
// Returns a SignedMath.Int version of the margin in balance. /
function getMargin( P1Types.Balance memory balance ) internal pure returns (SignedMath.Int memory)
function getMargin( P1Types.Balance memory balance ) internal pure returns (SignedMath.Int memory)
14,630
665
// Check and remove liquidation if existingDebt after burning is <= maxIssuableSynths Issuance ratio is fixed so should remove any liquidations
if (existingDebt.sub(amountBurnt) <= maxIssuableSynthsForAccount) { liquidations().removeAccountInLiquidation(from); }
if (existingDebt.sub(amountBurnt) <= maxIssuableSynthsForAccount) { liquidations().removeAccountInLiquidation(from); }
3,828
2
// mapping between blog Id and the amount of support it's generated
mapping (uint=>uint) public support;
mapping (uint=>uint) public support;
27,902
30
// 90-95
uint256 totalTokensBonus = totalLockedPoolTokensFrom(_poolId, 91); bonus = _balance .mul( percentFrom( 60, pools[_poolId].withheldFunds.sub( pools[_poolId].bonusesPaid[0] + pools[_poolId].bonusesPaid[1] ) )
uint256 totalTokensBonus = totalLockedPoolTokensFrom(_poolId, 91); bonus = _balance .mul( percentFrom( 60, pools[_poolId].withheldFunds.sub( pools[_poolId].bonusesPaid[0] + pools[_poolId].bonusesPaid[1] ) )
47,086
258
// IMPORTANT just after creation we must call this method
function bootstrap() external onlyOwner nonReentrant
function bootstrap() external onlyOwner nonReentrant
25,426
15
// Operator can toggle the purchasing mechanism as On / Off for the Sale of Apemo Army
function togglePurchase() external onlyOperator { purchaseState = !purchaseState; }
function togglePurchase() external onlyOperator { purchaseState = !purchaseState; }
37,940
81
// default owner of all minted tokens
address owner;
address owner;
12,460
93
// AllowanceCrowdsale Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale. /
contract AllowanceCrowdsale is Crowdsale { using SafeMath for uint256; using SafeERC20 for IERC20; address private _tokenWallet; /** * @dev Constructor, takes token wallet address. * @param tokenWallet Address holding the tokens, which has approved allowance to the crowdsale. */ constructor (address tokenWallet) public { require(tokenWallet != address(0), "AllowanceCrowdsale: token wallet is the zero address"); _tokenWallet = tokenWallet; } /** * @return the address of the wallet that will hold the tokens. */ function tokenWallet() public view returns (address) { return _tokenWallet; } /** * @dev Checks the amount of tokens left in the allowance. * @return Amount of tokens left in the allowance */ function remainingTokens() public view returns (uint256) { return Math.min(token().balanceOf(_tokenWallet), token().allowance(_tokenWallet, address(this))); } /** * @dev Overrides parent behavior by transferring tokens from wallet. * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount); } }
contract AllowanceCrowdsale is Crowdsale { using SafeMath for uint256; using SafeERC20 for IERC20; address private _tokenWallet; /** * @dev Constructor, takes token wallet address. * @param tokenWallet Address holding the tokens, which has approved allowance to the crowdsale. */ constructor (address tokenWallet) public { require(tokenWallet != address(0), "AllowanceCrowdsale: token wallet is the zero address"); _tokenWallet = tokenWallet; } /** * @return the address of the wallet that will hold the tokens. */ function tokenWallet() public view returns (address) { return _tokenWallet; } /** * @dev Checks the amount of tokens left in the allowance. * @return Amount of tokens left in the allowance */ function remainingTokens() public view returns (uint256) { return Math.min(token().balanceOf(_tokenWallet), token().allowance(_tokenWallet, address(this))); } /** * @dev Overrides parent behavior by transferring tokens from wallet. * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount); } }
7,733
66
// Public type data
string public constant minionType = "SAFE MINION V0"; event SummonMinion( address indexed minion, address indexed moloch, address indexed avatar, string details, string minionType, uint256 minQuorum );
string public constant minionType = "SAFE MINION V0"; event SummonMinion( address indexed minion, address indexed moloch, address indexed avatar, string details, string minionType, uint256 minQuorum );
26,636
182
// BentoBox/BoringCrypto, Keno/The BentoBox is a vault for tokens. The stored tokens can be flash loaned and used in strategies./ Yield from this will go to the token depositors./ Rebasing tokens ARE NOT supported and WILL cause loss of funds./ Any funds transfered directly onto the BentoBox will be lost, use the deposit function instead.
contract BentoBoxV1 is MasterContractManager, BoringBatchable { using BoringMath for uint256; using BoringMath128 for uint128; using BoringERC20 for IERC20; using RebaseLibrary for Rebase; // ************** // // *** EVENTS *** // // ************** // event LogDeposit(IERC20 indexed token, address indexed from, address indexed to, uint256 amount, uint256 share); event LogWithdraw(IERC20 indexed token, address indexed from, address indexed to, uint256 amount, uint256 share); event LogTransfer(IERC20 indexed token, address indexed from, address indexed to, uint256 share); event LogFlashLoan(address indexed borrower, IERC20 indexed token, uint256 amount, uint256 feeAmount, address indexed receiver); event LogStrategyTargetPercentage(IERC20 indexed token, uint256 targetPercentage); event LogStrategyQueued(IERC20 indexed token, IStrategy indexed strategy); event LogStrategySet(IERC20 indexed token, IStrategy indexed strategy); event LogStrategyInvest(IERC20 indexed token, uint256 amount); event LogStrategyDivest(IERC20 indexed token, uint256 amount); event LogStrategyProfit(IERC20 indexed token, uint256 amount); event LogStrategyLoss(IERC20 indexed token, uint256 amount); // *************** // // *** STRUCTS *** // // *************** // struct StrategyData { uint64 strategyStartDate; uint64 targetPercentage; uint128 balance; // the balance of the strategy that BentoBox thinks is in there } // ******************************** // // *** CONSTANTS AND IMMUTABLES *** // // ******************************** // // V2 - Can they be private? // V2: Private to save gas, to verify it's correct, check the constructor arguments IERC20 private immutable wethToken; IERC20 private constant USE_ETHEREUM = IERC20(0); uint256 private constant FLASH_LOAN_FEE = 50; // 0.05% uint256 private constant FLASH_LOAN_FEE_PRECISION = 1e5; uint256 private constant STRATEGY_DELAY = 2 weeks; uint256 private constant MAX_TARGET_PERCENTAGE = 95; // 95% uint256 private constant MINIMUM_SHARE_BALANCE = 1000; // To prevent the ratio going off // ***************** // // *** VARIABLES *** // // ***************** // // Balance per token per address/contract in shares mapping(IERC20 => mapping(address => uint256)) public balanceOf; // Rebase from amount to share mapping(IERC20 => Rebase) public totals; mapping(IERC20 => IStrategy) public strategy; mapping(IERC20 => IStrategy) public pendingStrategy; mapping(IERC20 => StrategyData) public strategyData; // ******************* // // *** CONSTRUCTOR *** // // ******************* // constructor(IERC20 wethToken_) public { wethToken = wethToken_; } // ***************** // // *** MODIFIERS *** // // ***************** // /// Modifier to check if the msg.sender is allowed to use funds belonging to the 'from' address. /// If 'from' is msg.sender, it's allowed. /// If 'from' is the BentoBox itself, it's allowed. Any ETH, token balances (above the known balances) or BentoBox balances /// can be taken by anyone. /// This is to enable skimming, not just for deposits, but also for withdrawals or transfers, enabling better composability. /// If 'from' is a clone of a masterContract AND the 'from' address has approved that masterContract, it's allowed. modifier allowed(address from) { if (from != msg.sender && from != address(this)) { // From is sender or you are skimming address masterContract = masterContractOf[msg.sender]; require(masterContract != address(0), "BentoBox: no masterContract"); require(masterContractApproved[masterContract][from], "BentoBox: Transfer not approved"); } _; } // ************************** // // *** INTERNAL FUNCTIONS *** // // ************************** // /// @dev Returns the total balance of `token` this contracts holds, /// plus the total amount this contract thinks the strategy holds. function _tokenBalanceOf(IERC20 token) internal view returns (uint256 amount) { amount = token.balanceOf(address(this)).add(strategyData[token].balance); } // ************************ // // *** PUBLIC FUNCTIONS *** // // ************************ // /// @dev Helper function to represent an `amount` of `token` in shares. /// @param token The ERC-20 token. /// @param amount The `token` amount. /// @param roundUp If the result `share` should be rounded up. /// @return share The token amount represented in shares. function toShare( IERC20 token, uint256 amount, bool roundUp ) external view returns (uint256 share) { share = totals[token].toBase(amount, roundUp); } /// @dev Helper function represent shares back into the `token` amount. /// @param token The ERC-20 token. /// @param share The amount of shares. /// @param roundUp If the result should be rounded up. /// @return amount The share amount back into native representation. function toAmount( IERC20 token, uint256 share, bool roundUp ) external view returns (uint256 amount) { amount = totals[token].toElastic(share, roundUp); } /// @notice Deposit an amount of `token` represented in either `amount` or `share`. /// @param token_ The ERC-20 token to deposit. /// @param from which account to pull the tokens. /// @param to which account to push the tokens. /// @param amount Token amount in native representation to deposit. /// @param share Token amount represented in shares to deposit. Takes precedence over `amount`. /// @return amountOut The amount deposited. /// @return shareOut The deposited amount repesented in shares. function deposit( IERC20 token_, address from, address to, uint256 amount, uint256 share ) public payable allowed(from) returns (uint256 amountOut, uint256 shareOut) { // Checks require(to != address(0), "BentoBox: to not set"); // To avoid a bad UI from burning funds // Effects IERC20 token = token_ == USE_ETHEREUM ? wethToken : token_; Rebase memory total = totals[token]; // If a new token gets added, the tokenSupply call checks that this is a deployed contract. Needed for security. require(total.elastic != 0 || token.totalSupply() > 0, "BentoBox: No tokens"); if (share == 0) { // value of the share may be lower than the amount due to rounding, that's ok share = total.toBase(amount, false); // Any deposit should lead to at least the minimum share balance, otherwise it's ignored (no amount taken) if (total.base.add(share.to128()) < MINIMUM_SHARE_BALANCE) { return (0, 0); } } else { // amount may be lower than the value of share due to rounding, in that case, add 1 to amount (Always round up) amount = total.toElastic(share, true); } // In case of skimming, check that only the skimmable amount is taken. // For ETH, the full balance is available, so no need to check. // During flashloans the _tokenBalanceOf is lower than 'reality', so skimming deposits will mostly fail during a flashloan. require( from != address(this) || token_ == USE_ETHEREUM || amount <= _tokenBalanceOf(token).sub(total.elastic), "BentoBox: Skim too much" ); balanceOf[token][to] = balanceOf[token][to].add(share); total.base = total.base.add(share.to128()); total.elastic = total.elastic.add(amount.to128()); totals[token] = total; // Interactions // During the first deposit, we check that this token is 'real' if (token_ == USE_ETHEREUM) { // X2 - If there is an error, could it cause a DoS. Like balanceOf causing revert. (SWC-113) // X2: If the WETH implementation is faulty or malicious, it will block adding ETH (but we know the WETH implementation) IWETH(address(wethToken)).deposit{value: amount}(); } else if (from != address(this)) { // X2 - If there is an error, could it cause a DoS. Like balanceOf causing revert. (SWC-113) // X2: If the token implementation is faulty or malicious, it may block adding tokens. Good. token.safeTransferFrom(from, address(this), amount); } emit LogDeposit(token, from, to, amount, share); amountOut = amount; shareOut = share; } /// @notice Withdraws an amount of `token` from a user account. /// @param token_ The ERC-20 token to withdraw. /// @param from which user to pull the tokens. /// @param to which user to push the tokens. /// @param amount of tokens. Either one of `amount` or `share` needs to be supplied. /// @param share Like above, but `share` takes precedence over `amount`. function withdraw( IERC20 token_, address from, address to, uint256 amount, uint256 share ) public allowed(from) returns (uint256 amountOut, uint256 shareOut) { // Checks require(to != address(0), "BentoBox: to not set"); // To avoid a bad UI from burning funds // Effects IERC20 token = token_ == USE_ETHEREUM ? wethToken : token_; Rebase memory total = totals[token]; if (share == 0) { // value of the share paid could be lower than the amount paid due to rounding, in that case, add a share (Always round up) share = total.toBase(amount, true); } else { // amount may be lower than the value of share due to rounding, that's ok amount = total.toElastic(share, false); } balanceOf[token][from] = balanceOf[token][from].sub(share); total.elastic = total.elastic.sub(amount.to128()); total.base = total.base.sub(share.to128()); // There have to be at least 1000 shares left to prevent reseting the share/amount ratio (unless it's fully emptied) require(total.base >= MINIMUM_SHARE_BALANCE || total.base == 0, "BentoBox: cannot empty"); totals[token] = total; // Interactions if (token_ == USE_ETHEREUM) { // X2, X3: A revert or big gas usage in the WETH contract could block withdrawals, but WETH9 is fine. IWETH(address(wethToken)).withdraw(amount); // X2, X3: A revert or big gas usage could block, however, the to address is under control of the caller. (bool success, ) = to.call{value: amount}(""); require(success, "BentoBox: ETH transfer failed"); } else { // X2, X3: A malicious token could block withdrawal of just THAT token. // masterContracts may want to take care not to rely on withdraw always succeeding. token.safeTransfer(to, amount); } emit LogWithdraw(token, from, to, amount, share); amountOut = amount; shareOut = share; } /// @notice Transfer shares from a user account to another one. /// @param token The ERC-20 token to transfer. /// @param from which user to pull the tokens. /// @param to which user to push the tokens. /// @param share The amount of `token` in shares. // Clones of master contracts can transfer from any account that has approved them // F3 - Can it be combined with another similar function? // F3: This isn't combined with transferMultiple for gas optimization function transfer( IERC20 token, address from, address to, uint256 share ) public allowed(from) { // Checks require(to != address(0), "BentoBox: to not set"); // To avoid a bad UI from burning funds // Effects balanceOf[token][from] = balanceOf[token][from].sub(share); balanceOf[token][to] = balanceOf[token][to].add(share); emit LogTransfer(token, from, to, share); } /// @notice Transfer shares from a user account to multiple other ones. /// @param token The ERC-20 token to transfer. /// @param from which user to pull the tokens. /// @param tos The receivers of the tokens. /// @param shares The amount of `token` in shares for each receiver in `tos`. // F3 - Can it be combined with another similar function? // F3: This isn't combined with transfer for gas optimization function transferMultiple( IERC20 token, address from, address[] calldata tos, uint256[] calldata shares ) public allowed(from) { // Checks require(tos[0] != address(0), "BentoBox: to[0] not set"); // To avoid a bad UI from burning funds // Effects uint256 totalAmount; uint256 len = tos.length; for (uint256 i = 0; i < len; i++) { address to = tos[i]; balanceOf[token][to] = balanceOf[token][to].add(shares[i]); totalAmount = totalAmount.add(shares[i]); emit LogTransfer(token, from, to, shares[i]); } balanceOf[token][from] = balanceOf[token][from].sub(totalAmount); } /// @notice Flashloan ability. /// @param borrower The address of the contract that implements and conforms to `IFlashBorrower` and handles the flashloan. /// @param receiver Address of the token receiver. /// @param token The address of the token to receive. /// @param amount of the tokens to receive. /// @param data The calldata to pass to the `borrower` contract. // F5 - Checks-Effects-Interactions pattern followed? (SWC-107) // F5: Not possible to follow this here, reentrancy has been reviewed // F6 - Check for front-running possibilities, such as the approve function (SWC-114) // F6: Slight grieving possible by withdrawing an amount before someone tries to flashloan close to the full amount. function flashLoan( IFlashBorrower borrower, address receiver, IERC20 token, uint256 amount, bytes calldata data ) public { uint256 fee = amount.mul(FLASH_LOAN_FEE) / FLASH_LOAN_FEE_PRECISION; token.safeTransfer(receiver, amount); borrower.onFlashLoan(msg.sender, token, amount, fee, data); require(_tokenBalanceOf(token) >= totals[token].addElastic(fee.to128()), "BentoBox: Wrong amount"); emit LogFlashLoan(address(borrower), token, amount, fee, receiver); } /// @notice Support for batched flashloans. Useful to request multiple different `tokens` in a single transaction. /// @param borrower The address of the contract that implements and conforms to `IBatchFlashBorrower` and handles the flashloan. /// @param receivers An array of the token receivers. A one-to-one mapping with `tokens` and `amounts`. /// @param tokens The addresses of the tokens. /// @param amounts of the tokens for each receiver. /// @param data The calldata to pass to the `borrower` contract. // F5 - Checks-Effects-Interactions pattern followed? (SWC-107) // F5: Not possible to follow this here, reentrancy has been reviewed // F6 - Check for front-running possibilities, such as the approve function (SWC-114) // F6: Slight grieving possible by withdrawing an amount before someone tries to flashloan close to the full amount. function batchFlashLoan( IBatchFlashBorrower borrower, address[] calldata receivers, IERC20[] calldata tokens, uint256[] calldata amounts, bytes calldata data ) public { uint256[] memory fees = new uint256[](tokens.length); uint256 len = tokens.length; for (uint256 i = 0; i < len; i++) { uint256 amount = amounts[i]; fees[i] = amount.mul(FLASH_LOAN_FEE) / FLASH_LOAN_FEE_PRECISION; tokens[i].safeTransfer(receivers[i], amounts[i]); } borrower.onBatchFlashLoan(msg.sender, tokens, amounts, fees, data); for (uint256 i = 0; i < len; i++) { IERC20 token = tokens[i]; require(_tokenBalanceOf(token) >= totals[token].addElastic(fees[i].to128()), "BentoBox: Wrong amount"); emit LogFlashLoan(address(borrower), token, amounts[i], fees[i], receivers[i]); } } /// @notice Sets the target percentage of the strategy for `token`. /// @dev Only the owner of this contract is allowed to change this. /// @param token The address of the token that maps to a strategy to change. /// @param targetPercentage_ The new target in percent. Must be lesser or equal to `MAX_TARGET_PERCENTAGE`. function setStrategyTargetPercentage(IERC20 token, uint64 targetPercentage_) public onlyOwner { // Checks require(targetPercentage_ <= MAX_TARGET_PERCENTAGE, "StrategyManager: Target too high"); // Effects strategyData[token].targetPercentage = targetPercentage_; emit LogStrategyTargetPercentage(token, targetPercentage_); } /// @notice Sets the contract address of a new strategy that conforms to `IStrategy` for `token`. /// Must be called twice with the same arguments. /// A new strategy becomes pending first and can be activated once `STRATEGY_DELAY` is over. /// @dev Only the owner of this contract is allowed to change this. /// @param token The address of the token that maps to a strategy to change. /// @param newStrategy The address of the contract that conforms to `IStrategy`. // F5 - Checks-Effects-Interactions pattern followed? (SWC-107) // F5: Total amount is updated AFTER interaction. But strategy is under our control. // C4 - Use block.timestamp only for long intervals (SWC-116) // C4: block.timestamp is used for a period of 2 weeks, which is long enough function setStrategy(IERC20 token, IStrategy newStrategy) public onlyOwner { StrategyData memory data = strategyData[token]; IStrategy pending = pendingStrategy[token]; if (data.strategyStartDate == 0 || pending != newStrategy) { pendingStrategy[token] = newStrategy; // C1 - All math done through BoringMath (SWC-101) // C1: Our sun will swallow the earth well before this overflows data.strategyStartDate = (block.timestamp + STRATEGY_DELAY).to64(); emit LogStrategyQueued(token, newStrategy); } else { require(data.strategyStartDate != 0 && block.timestamp >= data.strategyStartDate, "StrategyManager: Too early"); if (address(strategy[token]) != address(0)) { int256 balanceChange = strategy[token].exit(data.balance); // Effects if (balanceChange > 0) { uint256 add = uint256(balanceChange); totals[token].addElastic(add); emit LogStrategyProfit(token, add); } else if (balanceChange < 0) { uint256 sub = uint256(-balanceChange); totals[token].subElastic(sub); emit LogStrategyLoss(token, sub); } emit LogStrategyDivest(token, data.balance); } strategy[token] = pending; data.strategyStartDate = 0; data.balance = 0; pendingStrategy[token] = IStrategy(0); emit LogStrategySet(token, newStrategy); } strategyData[token] = data; } /// @notice The actual process of yield farming. Executes the strategy of `token`. /// Optionally does housekeeping if `balance` is true. /// `maxChangeAmount` is relevant for skimming or withdrawing if `balance` is true. /// @param token The address of the token for which a strategy is deployed. /// @param balance True if housekeeping should be done. /// @param maxChangeAmount The maximum amount for either pulling or pushing from/to the `IStrategy` contract. // F5 - Checks-Effects-Interactions pattern followed? (SWC-107) // F5: Total amount is updated AFTER interaction. But strategy is under our control. // F5: Not followed to prevent reentrancy issues with flashloans and BentoBox skims? function harvest( IERC20 token, bool balance, uint256 maxChangeAmount ) public { StrategyData memory data = strategyData[token]; IStrategy _strategy = strategy[token]; int256 balanceChange = _strategy.harvest(data.balance, msg.sender); if (balanceChange == 0 && !balance) { return; } uint256 totalElastic = totals[token].elastic; if (balanceChange > 0) { uint256 add = uint256(balanceChange); totalElastic = totalElastic.add(add); totals[token].elastic = totalElastic.to128(); emit LogStrategyProfit(token, add); } else if (balanceChange < 0) { // C1 - All math done through BoringMath (SWC-101) // C1: balanceChange could overflow if it's max negative int128. // But tokens with balances that large are not supported by the BentoBox. uint256 sub = uint256(-balanceChange); totalElastic = totalElastic.sub(sub); totals[token].elastic = totalElastic.to128(); data.balance = data.balance.sub(sub.to128()); emit LogStrategyLoss(token, sub); } if (balance) { uint256 targetBalance = totalElastic.mul(data.targetPercentage) / 100; // if data.balance == targetBalance there is nothing to update if (data.balance < targetBalance) { uint256 amountOut = targetBalance.sub(data.balance); if (maxChangeAmount != 0 && amountOut > maxChangeAmount) { amountOut = maxChangeAmount; } token.safeTransfer(address(_strategy), amountOut); data.balance = data.balance.add(amountOut.to128()); _strategy.skim(amountOut); emit LogStrategyInvest(token, amountOut); } else if (data.balance > targetBalance) { uint256 amountIn = data.balance.sub(targetBalance.to128()); if (maxChangeAmount != 0 && amountIn > maxChangeAmount) { amountIn = maxChangeAmount; } uint256 actualAmountIn = _strategy.withdraw(amountIn); data.balance = data.balance.sub(actualAmountIn.to128()); emit LogStrategyDivest(token, actualAmountIn); } } strategyData[token] = data; } // Contract should be able to receive ETH deposits to support deposit & skim // solhint-disable-next-line no-empty-blocks receive() external payable {} }
contract BentoBoxV1 is MasterContractManager, BoringBatchable { using BoringMath for uint256; using BoringMath128 for uint128; using BoringERC20 for IERC20; using RebaseLibrary for Rebase; // ************** // // *** EVENTS *** // // ************** // event LogDeposit(IERC20 indexed token, address indexed from, address indexed to, uint256 amount, uint256 share); event LogWithdraw(IERC20 indexed token, address indexed from, address indexed to, uint256 amount, uint256 share); event LogTransfer(IERC20 indexed token, address indexed from, address indexed to, uint256 share); event LogFlashLoan(address indexed borrower, IERC20 indexed token, uint256 amount, uint256 feeAmount, address indexed receiver); event LogStrategyTargetPercentage(IERC20 indexed token, uint256 targetPercentage); event LogStrategyQueued(IERC20 indexed token, IStrategy indexed strategy); event LogStrategySet(IERC20 indexed token, IStrategy indexed strategy); event LogStrategyInvest(IERC20 indexed token, uint256 amount); event LogStrategyDivest(IERC20 indexed token, uint256 amount); event LogStrategyProfit(IERC20 indexed token, uint256 amount); event LogStrategyLoss(IERC20 indexed token, uint256 amount); // *************** // // *** STRUCTS *** // // *************** // struct StrategyData { uint64 strategyStartDate; uint64 targetPercentage; uint128 balance; // the balance of the strategy that BentoBox thinks is in there } // ******************************** // // *** CONSTANTS AND IMMUTABLES *** // // ******************************** // // V2 - Can they be private? // V2: Private to save gas, to verify it's correct, check the constructor arguments IERC20 private immutable wethToken; IERC20 private constant USE_ETHEREUM = IERC20(0); uint256 private constant FLASH_LOAN_FEE = 50; // 0.05% uint256 private constant FLASH_LOAN_FEE_PRECISION = 1e5; uint256 private constant STRATEGY_DELAY = 2 weeks; uint256 private constant MAX_TARGET_PERCENTAGE = 95; // 95% uint256 private constant MINIMUM_SHARE_BALANCE = 1000; // To prevent the ratio going off // ***************** // // *** VARIABLES *** // // ***************** // // Balance per token per address/contract in shares mapping(IERC20 => mapping(address => uint256)) public balanceOf; // Rebase from amount to share mapping(IERC20 => Rebase) public totals; mapping(IERC20 => IStrategy) public strategy; mapping(IERC20 => IStrategy) public pendingStrategy; mapping(IERC20 => StrategyData) public strategyData; // ******************* // // *** CONSTRUCTOR *** // // ******************* // constructor(IERC20 wethToken_) public { wethToken = wethToken_; } // ***************** // // *** MODIFIERS *** // // ***************** // /// Modifier to check if the msg.sender is allowed to use funds belonging to the 'from' address. /// If 'from' is msg.sender, it's allowed. /// If 'from' is the BentoBox itself, it's allowed. Any ETH, token balances (above the known balances) or BentoBox balances /// can be taken by anyone. /// This is to enable skimming, not just for deposits, but also for withdrawals or transfers, enabling better composability. /// If 'from' is a clone of a masterContract AND the 'from' address has approved that masterContract, it's allowed. modifier allowed(address from) { if (from != msg.sender && from != address(this)) { // From is sender or you are skimming address masterContract = masterContractOf[msg.sender]; require(masterContract != address(0), "BentoBox: no masterContract"); require(masterContractApproved[masterContract][from], "BentoBox: Transfer not approved"); } _; } // ************************** // // *** INTERNAL FUNCTIONS *** // // ************************** // /// @dev Returns the total balance of `token` this contracts holds, /// plus the total amount this contract thinks the strategy holds. function _tokenBalanceOf(IERC20 token) internal view returns (uint256 amount) { amount = token.balanceOf(address(this)).add(strategyData[token].balance); } // ************************ // // *** PUBLIC FUNCTIONS *** // // ************************ // /// @dev Helper function to represent an `amount` of `token` in shares. /// @param token The ERC-20 token. /// @param amount The `token` amount. /// @param roundUp If the result `share` should be rounded up. /// @return share The token amount represented in shares. function toShare( IERC20 token, uint256 amount, bool roundUp ) external view returns (uint256 share) { share = totals[token].toBase(amount, roundUp); } /// @dev Helper function represent shares back into the `token` amount. /// @param token The ERC-20 token. /// @param share The amount of shares. /// @param roundUp If the result should be rounded up. /// @return amount The share amount back into native representation. function toAmount( IERC20 token, uint256 share, bool roundUp ) external view returns (uint256 amount) { amount = totals[token].toElastic(share, roundUp); } /// @notice Deposit an amount of `token` represented in either `amount` or `share`. /// @param token_ The ERC-20 token to deposit. /// @param from which account to pull the tokens. /// @param to which account to push the tokens. /// @param amount Token amount in native representation to deposit. /// @param share Token amount represented in shares to deposit. Takes precedence over `amount`. /// @return amountOut The amount deposited. /// @return shareOut The deposited amount repesented in shares. function deposit( IERC20 token_, address from, address to, uint256 amount, uint256 share ) public payable allowed(from) returns (uint256 amountOut, uint256 shareOut) { // Checks require(to != address(0), "BentoBox: to not set"); // To avoid a bad UI from burning funds // Effects IERC20 token = token_ == USE_ETHEREUM ? wethToken : token_; Rebase memory total = totals[token]; // If a new token gets added, the tokenSupply call checks that this is a deployed contract. Needed for security. require(total.elastic != 0 || token.totalSupply() > 0, "BentoBox: No tokens"); if (share == 0) { // value of the share may be lower than the amount due to rounding, that's ok share = total.toBase(amount, false); // Any deposit should lead to at least the minimum share balance, otherwise it's ignored (no amount taken) if (total.base.add(share.to128()) < MINIMUM_SHARE_BALANCE) { return (0, 0); } } else { // amount may be lower than the value of share due to rounding, in that case, add 1 to amount (Always round up) amount = total.toElastic(share, true); } // In case of skimming, check that only the skimmable amount is taken. // For ETH, the full balance is available, so no need to check. // During flashloans the _tokenBalanceOf is lower than 'reality', so skimming deposits will mostly fail during a flashloan. require( from != address(this) || token_ == USE_ETHEREUM || amount <= _tokenBalanceOf(token).sub(total.elastic), "BentoBox: Skim too much" ); balanceOf[token][to] = balanceOf[token][to].add(share); total.base = total.base.add(share.to128()); total.elastic = total.elastic.add(amount.to128()); totals[token] = total; // Interactions // During the first deposit, we check that this token is 'real' if (token_ == USE_ETHEREUM) { // X2 - If there is an error, could it cause a DoS. Like balanceOf causing revert. (SWC-113) // X2: If the WETH implementation is faulty or malicious, it will block adding ETH (but we know the WETH implementation) IWETH(address(wethToken)).deposit{value: amount}(); } else if (from != address(this)) { // X2 - If there is an error, could it cause a DoS. Like balanceOf causing revert. (SWC-113) // X2: If the token implementation is faulty or malicious, it may block adding tokens. Good. token.safeTransferFrom(from, address(this), amount); } emit LogDeposit(token, from, to, amount, share); amountOut = amount; shareOut = share; } /// @notice Withdraws an amount of `token` from a user account. /// @param token_ The ERC-20 token to withdraw. /// @param from which user to pull the tokens. /// @param to which user to push the tokens. /// @param amount of tokens. Either one of `amount` or `share` needs to be supplied. /// @param share Like above, but `share` takes precedence over `amount`. function withdraw( IERC20 token_, address from, address to, uint256 amount, uint256 share ) public allowed(from) returns (uint256 amountOut, uint256 shareOut) { // Checks require(to != address(0), "BentoBox: to not set"); // To avoid a bad UI from burning funds // Effects IERC20 token = token_ == USE_ETHEREUM ? wethToken : token_; Rebase memory total = totals[token]; if (share == 0) { // value of the share paid could be lower than the amount paid due to rounding, in that case, add a share (Always round up) share = total.toBase(amount, true); } else { // amount may be lower than the value of share due to rounding, that's ok amount = total.toElastic(share, false); } balanceOf[token][from] = balanceOf[token][from].sub(share); total.elastic = total.elastic.sub(amount.to128()); total.base = total.base.sub(share.to128()); // There have to be at least 1000 shares left to prevent reseting the share/amount ratio (unless it's fully emptied) require(total.base >= MINIMUM_SHARE_BALANCE || total.base == 0, "BentoBox: cannot empty"); totals[token] = total; // Interactions if (token_ == USE_ETHEREUM) { // X2, X3: A revert or big gas usage in the WETH contract could block withdrawals, but WETH9 is fine. IWETH(address(wethToken)).withdraw(amount); // X2, X3: A revert or big gas usage could block, however, the to address is under control of the caller. (bool success, ) = to.call{value: amount}(""); require(success, "BentoBox: ETH transfer failed"); } else { // X2, X3: A malicious token could block withdrawal of just THAT token. // masterContracts may want to take care not to rely on withdraw always succeeding. token.safeTransfer(to, amount); } emit LogWithdraw(token, from, to, amount, share); amountOut = amount; shareOut = share; } /// @notice Transfer shares from a user account to another one. /// @param token The ERC-20 token to transfer. /// @param from which user to pull the tokens. /// @param to which user to push the tokens. /// @param share The amount of `token` in shares. // Clones of master contracts can transfer from any account that has approved them // F3 - Can it be combined with another similar function? // F3: This isn't combined with transferMultiple for gas optimization function transfer( IERC20 token, address from, address to, uint256 share ) public allowed(from) { // Checks require(to != address(0), "BentoBox: to not set"); // To avoid a bad UI from burning funds // Effects balanceOf[token][from] = balanceOf[token][from].sub(share); balanceOf[token][to] = balanceOf[token][to].add(share); emit LogTransfer(token, from, to, share); } /// @notice Transfer shares from a user account to multiple other ones. /// @param token The ERC-20 token to transfer. /// @param from which user to pull the tokens. /// @param tos The receivers of the tokens. /// @param shares The amount of `token` in shares for each receiver in `tos`. // F3 - Can it be combined with another similar function? // F3: This isn't combined with transfer for gas optimization function transferMultiple( IERC20 token, address from, address[] calldata tos, uint256[] calldata shares ) public allowed(from) { // Checks require(tos[0] != address(0), "BentoBox: to[0] not set"); // To avoid a bad UI from burning funds // Effects uint256 totalAmount; uint256 len = tos.length; for (uint256 i = 0; i < len; i++) { address to = tos[i]; balanceOf[token][to] = balanceOf[token][to].add(shares[i]); totalAmount = totalAmount.add(shares[i]); emit LogTransfer(token, from, to, shares[i]); } balanceOf[token][from] = balanceOf[token][from].sub(totalAmount); } /// @notice Flashloan ability. /// @param borrower The address of the contract that implements and conforms to `IFlashBorrower` and handles the flashloan. /// @param receiver Address of the token receiver. /// @param token The address of the token to receive. /// @param amount of the tokens to receive. /// @param data The calldata to pass to the `borrower` contract. // F5 - Checks-Effects-Interactions pattern followed? (SWC-107) // F5: Not possible to follow this here, reentrancy has been reviewed // F6 - Check for front-running possibilities, such as the approve function (SWC-114) // F6: Slight grieving possible by withdrawing an amount before someone tries to flashloan close to the full amount. function flashLoan( IFlashBorrower borrower, address receiver, IERC20 token, uint256 amount, bytes calldata data ) public { uint256 fee = amount.mul(FLASH_LOAN_FEE) / FLASH_LOAN_FEE_PRECISION; token.safeTransfer(receiver, amount); borrower.onFlashLoan(msg.sender, token, amount, fee, data); require(_tokenBalanceOf(token) >= totals[token].addElastic(fee.to128()), "BentoBox: Wrong amount"); emit LogFlashLoan(address(borrower), token, amount, fee, receiver); } /// @notice Support for batched flashloans. Useful to request multiple different `tokens` in a single transaction. /// @param borrower The address of the contract that implements and conforms to `IBatchFlashBorrower` and handles the flashloan. /// @param receivers An array of the token receivers. A one-to-one mapping with `tokens` and `amounts`. /// @param tokens The addresses of the tokens. /// @param amounts of the tokens for each receiver. /// @param data The calldata to pass to the `borrower` contract. // F5 - Checks-Effects-Interactions pattern followed? (SWC-107) // F5: Not possible to follow this here, reentrancy has been reviewed // F6 - Check for front-running possibilities, such as the approve function (SWC-114) // F6: Slight grieving possible by withdrawing an amount before someone tries to flashloan close to the full amount. function batchFlashLoan( IBatchFlashBorrower borrower, address[] calldata receivers, IERC20[] calldata tokens, uint256[] calldata amounts, bytes calldata data ) public { uint256[] memory fees = new uint256[](tokens.length); uint256 len = tokens.length; for (uint256 i = 0; i < len; i++) { uint256 amount = amounts[i]; fees[i] = amount.mul(FLASH_LOAN_FEE) / FLASH_LOAN_FEE_PRECISION; tokens[i].safeTransfer(receivers[i], amounts[i]); } borrower.onBatchFlashLoan(msg.sender, tokens, amounts, fees, data); for (uint256 i = 0; i < len; i++) { IERC20 token = tokens[i]; require(_tokenBalanceOf(token) >= totals[token].addElastic(fees[i].to128()), "BentoBox: Wrong amount"); emit LogFlashLoan(address(borrower), token, amounts[i], fees[i], receivers[i]); } } /// @notice Sets the target percentage of the strategy for `token`. /// @dev Only the owner of this contract is allowed to change this. /// @param token The address of the token that maps to a strategy to change. /// @param targetPercentage_ The new target in percent. Must be lesser or equal to `MAX_TARGET_PERCENTAGE`. function setStrategyTargetPercentage(IERC20 token, uint64 targetPercentage_) public onlyOwner { // Checks require(targetPercentage_ <= MAX_TARGET_PERCENTAGE, "StrategyManager: Target too high"); // Effects strategyData[token].targetPercentage = targetPercentage_; emit LogStrategyTargetPercentage(token, targetPercentage_); } /// @notice Sets the contract address of a new strategy that conforms to `IStrategy` for `token`. /// Must be called twice with the same arguments. /// A new strategy becomes pending first and can be activated once `STRATEGY_DELAY` is over. /// @dev Only the owner of this contract is allowed to change this. /// @param token The address of the token that maps to a strategy to change. /// @param newStrategy The address of the contract that conforms to `IStrategy`. // F5 - Checks-Effects-Interactions pattern followed? (SWC-107) // F5: Total amount is updated AFTER interaction. But strategy is under our control. // C4 - Use block.timestamp only for long intervals (SWC-116) // C4: block.timestamp is used for a period of 2 weeks, which is long enough function setStrategy(IERC20 token, IStrategy newStrategy) public onlyOwner { StrategyData memory data = strategyData[token]; IStrategy pending = pendingStrategy[token]; if (data.strategyStartDate == 0 || pending != newStrategy) { pendingStrategy[token] = newStrategy; // C1 - All math done through BoringMath (SWC-101) // C1: Our sun will swallow the earth well before this overflows data.strategyStartDate = (block.timestamp + STRATEGY_DELAY).to64(); emit LogStrategyQueued(token, newStrategy); } else { require(data.strategyStartDate != 0 && block.timestamp >= data.strategyStartDate, "StrategyManager: Too early"); if (address(strategy[token]) != address(0)) { int256 balanceChange = strategy[token].exit(data.balance); // Effects if (balanceChange > 0) { uint256 add = uint256(balanceChange); totals[token].addElastic(add); emit LogStrategyProfit(token, add); } else if (balanceChange < 0) { uint256 sub = uint256(-balanceChange); totals[token].subElastic(sub); emit LogStrategyLoss(token, sub); } emit LogStrategyDivest(token, data.balance); } strategy[token] = pending; data.strategyStartDate = 0; data.balance = 0; pendingStrategy[token] = IStrategy(0); emit LogStrategySet(token, newStrategy); } strategyData[token] = data; } /// @notice The actual process of yield farming. Executes the strategy of `token`. /// Optionally does housekeeping if `balance` is true. /// `maxChangeAmount` is relevant for skimming or withdrawing if `balance` is true. /// @param token The address of the token for which a strategy is deployed. /// @param balance True if housekeeping should be done. /// @param maxChangeAmount The maximum amount for either pulling or pushing from/to the `IStrategy` contract. // F5 - Checks-Effects-Interactions pattern followed? (SWC-107) // F5: Total amount is updated AFTER interaction. But strategy is under our control. // F5: Not followed to prevent reentrancy issues with flashloans and BentoBox skims? function harvest( IERC20 token, bool balance, uint256 maxChangeAmount ) public { StrategyData memory data = strategyData[token]; IStrategy _strategy = strategy[token]; int256 balanceChange = _strategy.harvest(data.balance, msg.sender); if (balanceChange == 0 && !balance) { return; } uint256 totalElastic = totals[token].elastic; if (balanceChange > 0) { uint256 add = uint256(balanceChange); totalElastic = totalElastic.add(add); totals[token].elastic = totalElastic.to128(); emit LogStrategyProfit(token, add); } else if (balanceChange < 0) { // C1 - All math done through BoringMath (SWC-101) // C1: balanceChange could overflow if it's max negative int128. // But tokens with balances that large are not supported by the BentoBox. uint256 sub = uint256(-balanceChange); totalElastic = totalElastic.sub(sub); totals[token].elastic = totalElastic.to128(); data.balance = data.balance.sub(sub.to128()); emit LogStrategyLoss(token, sub); } if (balance) { uint256 targetBalance = totalElastic.mul(data.targetPercentage) / 100; // if data.balance == targetBalance there is nothing to update if (data.balance < targetBalance) { uint256 amountOut = targetBalance.sub(data.balance); if (maxChangeAmount != 0 && amountOut > maxChangeAmount) { amountOut = maxChangeAmount; } token.safeTransfer(address(_strategy), amountOut); data.balance = data.balance.add(amountOut.to128()); _strategy.skim(amountOut); emit LogStrategyInvest(token, amountOut); } else if (data.balance > targetBalance) { uint256 amountIn = data.balance.sub(targetBalance.to128()); if (maxChangeAmount != 0 && amountIn > maxChangeAmount) { amountIn = maxChangeAmount; } uint256 actualAmountIn = _strategy.withdraw(amountIn); data.balance = data.balance.sub(actualAmountIn.to128()); emit LogStrategyDivest(token, actualAmountIn); } } strategyData[token] = data; } // Contract should be able to receive ETH deposits to support deposit & skim // solhint-disable-next-line no-empty-blocks receive() external payable {} }
3,543
97
// Returns the vault information of unipilot base & range orders/pool Address of the Uniswap pool/ return LiquidityPosition/ - baseTickLower The lower tick of the base position/ - baseTickUpper The upper tick of the base position/ - baseLiquidity The total liquidity of the base position/ - rangeTickLower The lower tick of the range position/ - rangeTickUpper The upper tick of the range position/ - rangeLiquidity The total liquidity of the range position/ - fees0 Total amount of fees collected by unipilot positions in terms of token0/ - fees1 Total amount of fees collected by unipilot positions in terms of token1/ -
function poolPositions(address pool) external view returns (LiquidityPosition memory);
function poolPositions(address pool) external view returns (LiquidityPosition memory);
53,878
76
// Check that the caller is the owner of the border
require( border.owner == msg.sender, "Only the owner of the border can set the removal fee" );
require( border.owner == msg.sender, "Only the owner of the border can set the removal fee" );
1,513
1
// View keyword is for read only means we cann't change value of state variable and we cann't perform any computation. value = 3; if we are trying to change state varaible but we couldn't this will give us error.
return value;
return value;
38,572
3
// calculate hand left
uint j; uint i; if (!discarded[i]) { finalCards[j] = origDealtCards[i]; j++; }
uint j; uint i; if (!discarded[i]) { finalCards[j] = origDealtCards[i]; j++; }
11,742
158
// Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`./ The `gasStipend` can be set to a low enough value to prevent/ storage writes or gas griefing.// If sending via the normal procedure fails, force sends the ETH by/ creating a temporary contract which uses `SELFDESTRUCT` to force send the ETH.// Reverts if the current contract has insufficient balance.
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal { /// @solidity memory-safe-assembly assembly { // If insufficient balance, revert. if lt(selfbalance(), amount) { // Store the function selector of `ETHTransferFailed()`. mstore(0x00, 0xb12d13eb) // Revert with (offset, size). revert(0x1c, 0x04) } // Transfer the ETH and check if it succeeded or not. if iszero(call(gasStipend, to, amount, 0, 0, 0, 0)) { mstore(0x00, to) // Store the address in scratch space. mstore8(0x0b, 0x73) // Opcode `PUSH20`. mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`. // We can directly use `SELFDESTRUCT` in the contract creation. // Compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758 if iszero(create(amount, 0x0b, 0x16)) { // For better gas estimation. if iszero(gt(gas(), 1000000)) { revert(0, 0) } } } } }
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal { /// @solidity memory-safe-assembly assembly { // If insufficient balance, revert. if lt(selfbalance(), amount) { // Store the function selector of `ETHTransferFailed()`. mstore(0x00, 0xb12d13eb) // Revert with (offset, size). revert(0x1c, 0x04) } // Transfer the ETH and check if it succeeded or not. if iszero(call(gasStipend, to, amount, 0, 0, 0, 0)) { mstore(0x00, to) // Store the address in scratch space. mstore8(0x0b, 0x73) // Opcode `PUSH20`. mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`. // We can directly use `SELFDESTRUCT` in the contract creation. // Compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758 if iszero(create(amount, 0x0b, 0x16)) { // For better gas estimation. if iszero(gt(gas(), 1000000)) { revert(0, 0) } } } } }
28,076
19
// Triggers a transfer to the project of the amount of Ether they are owed, according to their percentage of thetotal shares and their previous withdrawals. /
function releaseProjectETH(uint256 gasLimit_) external;
function releaseProjectETH(uint256 gasLimit_) external;
37,066
74
// Handle flight status as appropriate processFlightStatus(airline, flight, timestamp, statusCode);
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
39,729
1
// Creator of the contract is admin during initialization
admin = msg.sender;
admin = msg.sender;
24,149
5
// Trading
function swapExactETHForTokens( uint amountIn, uint minAmountOut, uint maxPrice, uint deadline ) external returns (uint); function swapExactTokensForETH( uint amountIn, uint minAmountOut,
function swapExactETHForTokens( uint amountIn, uint minAmountOut, uint maxPrice, uint deadline ) external returns (uint); function swapExactTokensForETH( uint amountIn, uint minAmountOut,
82,346
237
// DEPRECATED: Used to mint IdleTokens, given an underlying amount (eg. DAI).Keep for backward compatibility with IdleV2_amount : amount of underlying token to be lended : not used, pass empty arrayreturn mintedTokens : amount of IdleTokens minted /
function mintIdleToken(uint256 _amount, uint256[] calldata) external nonReentrant gasDiscountFrom(address(this))
function mintIdleToken(uint256 _amount, uint256[] calldata) external nonReentrant gasDiscountFrom(address(this))
31,232
47
// Asserts that sender is the implementor. /
modifier onlyImplementor() { require(isImplementor(), "Is not implementor"); _; }
modifier onlyImplementor() { require(isImplementor(), "Is not implementor"); _; }
33,596
0
// model a landlord
struct Landlord{ uint landlordID; string landlordName; uint landlordContact; string landlordAddress; address laddr; bool isValue; }
struct Landlord{ uint landlordID; string landlordName; uint landlordContact; string landlordAddress; address laddr; bool isValue; }
10,677
89
// Queries the balance of `_owner` at a specific `_blockNumber`/_owner The address from which the balance will be retrieved/_blockNumber The block number when the balance is queried/ return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint256 _blockNumber) public view returns (uint256)
function balanceOfAt(address _owner, uint256 _blockNumber) public view returns (uint256)
17,249
40
// Check tiers and cap purchase to allocation
(uint allocation, uint tiersTotal) = getUserAllocation(user); if (block.timestamp < startTime + ALLOCATION_DURATION) { require(userInfo[user].amount + amount <= allocation, "over allocation size"); require(totalAmount + amount <= raisingAmountTiers, "reached phase 1 total cap"); } else {
(uint allocation, uint tiersTotal) = getUserAllocation(user); if (block.timestamp < startTime + ALLOCATION_DURATION) { require(userInfo[user].amount + amount <= allocation, "over allocation size"); require(totalAmount + amount <= raisingAmountTiers, "reached phase 1 total cap"); } else {
36,217
31
// 0x1d1d8b63 is mint ^ burn ^ l1Token
return ERC165Checker.supportsInterface(_token, 0x1d1d8b63);
return ERC165Checker.supportsInterface(_token, 0x1d1d8b63);
39,395
53
// Returns number of declared public offering plans /
function numOfDeclaredPublicOfferingPlans() external constant returns (uint256)
function numOfDeclaredPublicOfferingPlans() external constant returns (uint256)
20,931
176
// nextTokenId is initialized to 1, since starting at 0 leads to higher gas cost for the first minter
_nextTokenId.increment(); setBaseURI(_initBaseURI);
_nextTokenId.increment(); setBaseURI(_initBaseURI);
7,644
133
// Provide a signal to the keeper that `harvest()` should be called. The keeper will provide the estimated gas cost that they would pay to call `harvest()`, and this function should use that estimate to make a determination if calling it is "worth it" for the keeper. This is not the only consideration into issuing this trigger, for example if the position would be negatively affected if `harvest()` is not called shortly, then this can return `true` even if the keeper might be "at a loss" (keepers are always reimbursed by Yearn). `callCost` must be priced in terms of `want`.This call
function harvestTrigger(uint256 callCost) public virtual view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); }
function harvestTrigger(uint256 callCost) public virtual view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); }
16,861
24
// compare user's choice with oracle result
uint256 win = returnedUser.stake * 2;//double the stakes jackpot = SafeMath.sub(jackpot, win);//remove funds from jackpot userBalances[returnedUser.player] = SafeMath.add(userBalances[returnedUser.player], win);
uint256 win = returnedUser.stake * 2;//double the stakes jackpot = SafeMath.sub(jackpot, win);//remove funds from jackpot userBalances[returnedUser.player] = SafeMath.add(userBalances[returnedUser.player], win);
31,114
57
// function for receiving and recording an NFT calls "super" to the OpenZeppelin function inheritedoperatorthe sender of the NFT (I think) fromnot really sure, has generally been the zero address tokenId the tokenId of the NFT dataany additional data sent with the NFT return `IERC721Receiver.onERC721Received.selector` /
function onERC721Received( address operator, address from, uint256 tokenId, bytes memory data
function onERC721Received( address operator, address from, uint256 tokenId, bytes memory data
30,468
43
// Function to include a address in taking fee
function includeAddressInTakingFee(address account) external
function includeAddressInTakingFee(address account) external
32,227
28
// add uint256 'string script_status' or 'bool active' string script_status, bool complete6/9/23, v12.7 prep, changed 'address indexed patient_address' to string
event UpdateScriptQuantityAndDatesEvent( string pharmacy_name, string doctor_name, string doctor_dea, string medication_name, uint256 quantity_prescribed, uint256 quantity_filled, uint256 quantity_filled_today, uint256 quantity_unfilled,
event UpdateScriptQuantityAndDatesEvent( string pharmacy_name, string doctor_name, string doctor_dea, string medication_name, uint256 quantity_prescribed, uint256 quantity_filled, uint256 quantity_filled_today, uint256 quantity_unfilled,
14,632
117
// Withdraws from funds from the Cake Vault _shares: Number of shares to withdraw /
function withdraw(uint256 _shares) public notContract { UserInfo storage user = userInfo[msg.sender]; require(_shares > 0, "Nothing to withdraw"); require(_shares <= user.shares, "Withdraw amount exceeds balance"); uint256 currentAmount = (balanceOf().mul(_shares)).div(totalShares); user.shares = user.shares.sub(_shares); totalShares = totalShares.sub(_shares); uint256 bal = available(); if (bal < currentAmount) { uint256 balWithdraw = currentAmount.sub(bal); IMasterChef(masterchef).leaveStaking(balWithdraw); uint256 balAfter = available(); uint256 diff = balAfter.sub(bal); if (diff < balWithdraw) { currentAmount = bal.add(diff); } } if (block.timestamp < user.lastDepositedTime.add(withdrawFeePeriod)) { uint256 currentWithdrawFee = currentAmount.mul(withdrawFee).div(10000); token.safeTransfer(treasury, currentWithdrawFee); currentAmount = currentAmount.sub(currentWithdrawFee); } if (user.shares > 0) { user.cakeAtLastUserAction = user.shares.mul(balanceOf()).div(totalShares); } else { user.cakeAtLastUserAction = 0; } user.lastUserActionTime = block.timestamp; token.safeTransfer(msg.sender, currentAmount); emit Withdraw(msg.sender, currentAmount, _shares); }
function withdraw(uint256 _shares) public notContract { UserInfo storage user = userInfo[msg.sender]; require(_shares > 0, "Nothing to withdraw"); require(_shares <= user.shares, "Withdraw amount exceeds balance"); uint256 currentAmount = (balanceOf().mul(_shares)).div(totalShares); user.shares = user.shares.sub(_shares); totalShares = totalShares.sub(_shares); uint256 bal = available(); if (bal < currentAmount) { uint256 balWithdraw = currentAmount.sub(bal); IMasterChef(masterchef).leaveStaking(balWithdraw); uint256 balAfter = available(); uint256 diff = balAfter.sub(bal); if (diff < balWithdraw) { currentAmount = bal.add(diff); } } if (block.timestamp < user.lastDepositedTime.add(withdrawFeePeriod)) { uint256 currentWithdrawFee = currentAmount.mul(withdrawFee).div(10000); token.safeTransfer(treasury, currentWithdrawFee); currentAmount = currentAmount.sub(currentWithdrawFee); } if (user.shares > 0) { user.cakeAtLastUserAction = user.shares.mul(balanceOf()).div(totalShares); } else { user.cakeAtLastUserAction = 0; } user.lastUserActionTime = block.timestamp; token.safeTransfer(msg.sender, currentAmount); emit Withdraw(msg.sender, currentAmount, _shares); }
306
189
// Releasing is not started yet, or user is not locked
if (userLockInfo.startTime > block.timestamp || userLockInfo.startTime == 0) { return (userLockInfo.iterations, userLockInfo.totalAmount); }
if (userLockInfo.startTime > block.timestamp || userLockInfo.startTime == 0) { return (userLockInfo.iterations, userLockInfo.totalAmount); }
20,553
6
// If user is developer address, decrease balance by 8 MIL PIZZA If they don't have 8 MIL PIZZA, just set it to zero
if (user == developer) { uint EIGHT_MIL = 8000000 * (10 ** decimals); if (balance >= EIGHT_MIL) { balance -= EIGHT_MIL; } else {
if (user == developer) { uint EIGHT_MIL = 8000000 * (10 ** decimals); if (balance >= EIGHT_MIL) { balance -= EIGHT_MIL; } else {
41,658
401
// Returns the total amount of rewards a given address is able to withdraw. account Address of a reward recipientreturn A uint256 representing the rewards `account` can withdraw /
function withdrawableRewardsOf(address account) external view returns (uint256);
function withdrawableRewardsOf(address account) external view returns (uint256);
29,783
21
// only one bid allowed
require(auctions[auctionId].firstBidTime == 0, "DACOHOB"); uint256 price = LibExchangeAuction.getCurrentPrice(auctions[auctionId]); require(amount >= price, "MSGVGEP"); auctions[auctionId].endingPrice = price; auctions[auctionId].firstBidTime = block.timestamp;
require(auctions[auctionId].firstBidTime == 0, "DACOHOB"); uint256 price = LibExchangeAuction.getCurrentPrice(auctions[auctionId]); require(amount >= price, "MSGVGEP"); auctions[auctionId].endingPrice = price; auctions[auctionId].firstBidTime = block.timestamp;
21,542
215
// process deposit fees and deposit remainder
uint256 feeAmount = _amount.mul(depositFee).div(1e18); holyPool.depositOnBehalf(_beneficiary, _amount.sub(feeAmount)); return;
uint256 feeAmount = _amount.mul(depositFee).div(1e18); holyPool.depositOnBehalf(_beneficiary, _amount.sub(feeAmount)); return;
3,775
55
// Adds a trade executor, enabling it to execute trades./_tradeExecutor The address of _tradeExecutor contract./make sure all funds are withdrawn from executor before removing.
function removeExecutor(address _tradeExecutor) public { onlyGovernance(); isValidAddress(_tradeExecutor); // check if executor attached to vault. isActiveExecutor(_tradeExecutor); (uint256 executorFunds, uint256 blockUpdated) = ITradeExecutor( _tradeExecutor ).totalFunds(); areFundsUpdated(blockUpdated); require(executorFunds < DUST_LIMIT, "FUNDS_TOO_HIGH"); tradeExecutorsList.removeAddress(_tradeExecutor); emit ExecutorRemoved(_tradeExecutor); }
function removeExecutor(address _tradeExecutor) public { onlyGovernance(); isValidAddress(_tradeExecutor); // check if executor attached to vault. isActiveExecutor(_tradeExecutor); (uint256 executorFunds, uint256 blockUpdated) = ITradeExecutor( _tradeExecutor ).totalFunds(); areFundsUpdated(blockUpdated); require(executorFunds < DUST_LIMIT, "FUNDS_TOO_HIGH"); tradeExecutorsList.removeAddress(_tradeExecutor); emit ExecutorRemoved(_tradeExecutor); }
11,866
63
// Uniswap pool must exist
require( ISwapQueryHelper(self.swapHelper).hasPool(erc20token) == true, "NO_UNISWAP_POOL" );
require( ISwapQueryHelper(self.swapHelper).hasPool(erc20token) == true, "NO_UNISWAP_POOL" );
46,832
55
// remove user from whitelist The contract owner is able to remove an address from the whitelist by calling removeWhiteListAddress() passing in the address as the argument.
function removeWhitelistAddress(address _wlAddress) external onlyOwner { require(_wlAddress != address(0), "Address cannot be null."); whitelisted[_wlAddress] = false; }
function removeWhitelistAddress(address _wlAddress) external onlyOwner { require(_wlAddress != address(0), "Address cannot be null."); whitelisted[_wlAddress] = false; }
25,901
149
// Create the auction./_deedId The identifier of the deed to create the auction for./auction The auction to create.
function _createAuction(uint256 _deedId, Auction auction) internal { // Add the auction to the auction mapping. identifierToAuction[_deedId] = auction; // Trigger auction created event. AuctionCreated(auction.seller, _deedId, auction.startPrice, auction.endPrice, auction.duration); }
function _createAuction(uint256 _deedId, Auction auction) internal { // Add the auction to the auction mapping. identifierToAuction[_deedId] = auction; // Trigger auction created event. AuctionCreated(auction.seller, _deedId, auction.startPrice, auction.endPrice, auction.duration); }
29,472
4
// user
function createUser() public { userObj = MediaLib.User({ exists : true, mediaCount : 0, playlistIds : new string[](0) }); userObj.playlistIds.push("Default"); //if playlist is not specified, then "Default" userList[msg.sender] = userObj; }
function createUser() public { userObj = MediaLib.User({ exists : true, mediaCount : 0, playlistIds : new string[](0) }); userObj.playlistIds.push("Default"); //if playlist is not specified, then "Default" userList[msg.sender] = userObj; }
23,922
160
// Returns domain name of a given node.Requirements:- Node must exist. /
function getNodeDomainName(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (string memory)
function getNodeDomainName(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (string memory)
52,749
505
// sumBorrowPlusEffects += oraclePriceborrowBalance
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); }
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); }
32,245
6
// buying function. User input is the price they pay
function buy(uint256 tokenID) external payable { Listing memory oldListing = listings[tokenID]; listings[tokenID]= Listing({ owner: address(0), buyoutPrice: 0 }); require (msg.value == oldListing.buyoutPrice, "wrong value"); DFTokens.transferFrom(address(this), msg.sender, tokenID); sendValue(payable(oldListing.owner), oldListing.buyoutPrice); }
function buy(uint256 tokenID) external payable { Listing memory oldListing = listings[tokenID]; listings[tokenID]= Listing({ owner: address(0), buyoutPrice: 0 }); require (msg.value == oldListing.buyoutPrice, "wrong value"); DFTokens.transferFrom(address(this), msg.sender, tokenID); sendValue(payable(oldListing.owner), oldListing.buyoutPrice); }
12,840
32
// Transfer given amount of tokens from sender to another user ERC20/
function transfer(address to_addr, uint tokens) public onlyValidTokenAmount(tokens) returns (bool success) { require(to_addr != msg.sender, "You cannot transfer tokens to yourself"); // apply fee (uint fee_tokens, uint taxed_tokens) = fee_transfer.split(tokens); require(fee_tokens != 0, "Insufficient tokens to do that"); // calculate amount of funds and change price (uint funds, uint _price) = tokensToFunds(fee_tokens); require(funds != 0, "Insufficient tokens to do that"); price = _price; // burn and mint tokens excluding fee burnTokens(msg.sender, tokens); mintTokens(to_addr, taxed_tokens); // increase shared profit shared_profit = shared_profit.add(funds); emit Transfer(msg.sender, to_addr, tokens); return true; }
function transfer(address to_addr, uint tokens) public onlyValidTokenAmount(tokens) returns (bool success) { require(to_addr != msg.sender, "You cannot transfer tokens to yourself"); // apply fee (uint fee_tokens, uint taxed_tokens) = fee_transfer.split(tokens); require(fee_tokens != 0, "Insufficient tokens to do that"); // calculate amount of funds and change price (uint funds, uint _price) = tokensToFunds(fee_tokens); require(funds != 0, "Insufficient tokens to do that"); price = _price; // burn and mint tokens excluding fee burnTokens(msg.sender, tokens); mintTokens(to_addr, taxed_tokens); // increase shared profit shared_profit = shared_profit.add(funds); emit Transfer(msg.sender, to_addr, tokens); return true; }
6,476
194
// Bonus muliplier for early FRD makers.
uint256[] public REWARD_MULTIPLIER = [128, 128, 64, 32, 16, 8, 4, 2, 1]; uint256[] public HALVING_AT_BLOCK; // init in constructor function uint256 public FINISH_BONUS_AT_BLOCK;
uint256[] public REWARD_MULTIPLIER = [128, 128, 64, 32, 16, 8, 4, 2, 1]; uint256[] public HALVING_AT_BLOCK; // init in constructor function uint256 public FINISH_BONUS_AT_BLOCK;
8,887
35
// Withdraws given stake amount from the pool _amount Units of the staked token to withdraw /
function withdraw(uint256 _amount) external override updateReward(msg.sender) updateBoost(msg.sender)
function withdraw(uint256 _amount) external override updateReward(msg.sender) updateBoost(msg.sender)
40,924
53
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; }
modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; }
6,839
115
// check if a uint is in an array /
{ for (uint256 i = 0; i < array.length; i++) { if (array[i] == value) { return true; } } return false; }
{ for (uint256 i = 0; i < array.length; i++) { if (array[i] == value) { return true; } } return false; }
31,167
64
// Returns the number of decimals used to get its user representation.For example, if `decimals` equals `2`, a balance of `505` tokens shouldbe displayed to a user as `5.05` (`505 / 102`). NOTE: This information is only used for _display_ purposes: it inno way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() external view returns (uint256) { return _decimals; }
* {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() external view returns (uint256) { return _decimals; }
25,413
33
// user snapshot is outdated, day number and daily sum could be reset
us = UserStats({day: curDay, dailyDeposit: 0, tier: us.tier, dailyDirectDeposit: uint72(_amount)});
us = UserStats({day: curDay, dailyDeposit: 0, tier: us.tier, dailyDirectDeposit: uint72(_amount)});
29,601
161
// is lot minter /
function isLotMinter(uint256 _lotId, address _minter) public view returns (bool)
function isLotMinter(uint256 _lotId, address _minter) public view returns (bool)
3,386
209
// RLP encodes a list of RLP encoded byte byte strings. _in The list of RLP encoded byte strings.return The RLP encoded list of items in bytes. /
function writeList(bytes[] memory _in) internal pure returns (bytes memory) { bytes memory list = _flatten(_in); return abi.encodePacked(_writeLength(list.length, 192), list); }
function writeList(bytes[] memory _in) internal pure returns (bytes memory) { bytes memory list = _flatten(_in); return abi.encodePacked(_writeLength(list.length, 192), list); }
71,607
54
// Initialize the new money market name_ ERC-20 name of this token symbol_ ERC-20 symbol of this token decimals_ ERC-20 decimal precision of this token /
function initialize( string memory name_, string memory symbol_, uint8 decimals_, address initial_owner, uint256 initSupply_ ) public
function initialize( string memory name_, string memory symbol_, uint8 decimals_, address initial_owner, uint256 initSupply_ ) public
5,918
70
// then execute those outstanding redeems that do not have associated prices (just give them the price of the previous executed epoch)
userAction = _user_syntheticToken_redeemAction[user][poolType][poolIndex]; if (userAction.amount > 0 || userAction.nextEpochAmount > 0) { syntheticToken_price = _syntheticToken_priceSnapshot[lastExecutedEpoch][poolType][ poolIndex ]; amountPaymentTokenToSend = _getAmountPaymentToken( userAction.amount + userAction.nextEpochAmount, syntheticToken_price ); IYieldManager(_yieldManager).transferPaymentTokensToUser(user, amountPaymentTokenToSend);
userAction = _user_syntheticToken_redeemAction[user][poolType][poolIndex]; if (userAction.amount > 0 || userAction.nextEpochAmount > 0) { syntheticToken_price = _syntheticToken_priceSnapshot[lastExecutedEpoch][poolType][ poolIndex ]; amountPaymentTokenToSend = _getAmountPaymentToken( userAction.amount + userAction.nextEpochAmount, syntheticToken_price ); IYieldManager(_yieldManager).transferPaymentTokensToUser(user, amountPaymentTokenToSend);
25,502
14
// Returns the current maxCapDeposit. /
function getMaxCapDeposit() external view returns (uint256) { return _maxCapDeposit; }
function getMaxCapDeposit() external view returns (uint256) { return _maxCapDeposit; }
9,541
365
// this function is similar to emergencyTransfer, but relates to yield distribution fees are not transferred immediately to save gas costs for user operations so they accumulate on this contract address and can be claimed by HolyRedeemer when appropriate. Anyway, no user funds should appear on this contract, it only performs transfers, so such function has great power, but should be safe It does not include approval, so may be used by HolyRedeemer to get fees from swaps in different small token amounts
function claimFees(address _token, uint256 _amount) public { require(msg.sender == yieldDistributorAddress, "yield distributor only"); IERC20(_token).safeTransfer(msg.sender, _amount); }
function claimFees(address _token, uint256 _amount) public { require(msg.sender == yieldDistributorAddress, "yield distributor only"); IERC20(_token).safeTransfer(msg.sender, _amount); }
36,722
80
// Returns a custom string set on LCD contract via setLambdaProp Lambda prop has no specific intended use case. Developers can use this prop to unlock whichever features or experiences they want to incorporate into their creation/
function getLambdaProp(address _project, uint256 _tokenId) public view returns(string memory){ return projectToTokenIdToLambdaProp[_project][_tokenId]; }
function getLambdaProp(address _project, uint256 _tokenId) public view returns(string memory){ return projectToTokenIdToLambdaProp[_project][_tokenId]; }
26,018
26
// remove amount only for limited leaves in tree [first_leaf, leaf] amount value to remove /
function removeLimit(uint128 amount, uint48 leaf) internal { if (treeNode[1].amount >= amount) { // get last-updated top node (uint48 updatedNode, uint48 begin, uint48 end) = getUpdatedNode( 1, treeNode[1].updateId, LIQUIDITYNODES, LIQUIDITYLASTNODE, 1, LIQUIDITYNODES, LIQUIDITYLASTNODE, leaf ); // push changes from last-updated node down to the leaf, if leaf is not up to date push(updatedNode, begin, end, leaf, ++updateId); pushLazy( 1, LIQUIDITYNODES, LIQUIDITYLASTNODE, LIQUIDITYNODES, leaf, amount, true, ++updateId ); } }
function removeLimit(uint128 amount, uint48 leaf) internal { if (treeNode[1].amount >= amount) { // get last-updated top node (uint48 updatedNode, uint48 begin, uint48 end) = getUpdatedNode( 1, treeNode[1].updateId, LIQUIDITYNODES, LIQUIDITYLASTNODE, 1, LIQUIDITYNODES, LIQUIDITYLASTNODE, leaf ); // push changes from last-updated node down to the leaf, if leaf is not up to date push(updatedNode, begin, end, leaf, ++updateId); pushLazy( 1, LIQUIDITYNODES, LIQUIDITYLASTNODE, LIQUIDITYNODES, leaf, amount, true, ++updateId ); } }
15,629
162
// newController will point to the new controller after the present controller is upgraded
address public newController;
address public newController;
10,605
241
// If this has been called twice in the same block, shortcircuit to reduce gas
if(timeDelta == 0) { return (rewardPerTokenStored, lastApplicableTime); }
if(timeDelta == 0) { return (rewardPerTokenStored, lastApplicableTime); }
29,326
5
// The AF TOKEN!
IERC20 public tokenAF;
IERC20 public tokenAF;
48,747
13
// Tranfer tokens from sender to this contract
mimatic.transferFrom(msg.sender, address(this), amount);
mimatic.transferFrom(msg.sender, address(this), amount);
38,882