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
51
// else if the requestid is part of the requestQ[51] then update the tip for it
else if (_tip > 0){ zap.requestQ[_request.apiUintVars[keccak256("requestQPosition")]] += _tip; }
else if (_tip > 0){ zap.requestQ[_request.apiUintVars[keccak256("requestQPosition")]] += _tip; }
28,774
15
// updateSecondary, called only by owner/update secondary address/_newSecondary, new address to receive royalty payments
function updateSecondary(address _newSecondary) external onlyOwner { require(_newSecondary != address(0), "Lynchs Locks: new secondary is the zero address"); secondary = payable(_newSecondary); emit SecondaryUpdated(msg.sender, _newSecondary); }
function updateSecondary(address _newSecondary) external onlyOwner { require(_newSecondary != address(0), "Lynchs Locks: new secondary is the zero address"); secondary = payable(_newSecondary); emit SecondaryUpdated(msg.sender, _newSecondary); }
31,881
29
// return the address associated to the authority /
function authorityAddress() public view returns (address) { return authority; }
function authorityAddress() public view returns (address) { return authority; }
3,322
10
// Only CarDealer can call this, sets Proposed Purchase values, such as CarID, price, offer valid time and approval state (to 0)/
function RepurchaseCarPropose(uint256 carId, uint price, uint validTime) public{ require(msg.sender == carDealer,'Only CarDealer can repurchase propose'); uint offerTime = validTime + block.timestamp; proposedPurchasedCar = ProposedCar(carId,price,offerTime,0,block.timestamp); for (uint i = 0 ; i < participants.length; i++){//Reinitialize for new proposal participants[i].isVoted = false; } }
function RepurchaseCarPropose(uint256 carId, uint price, uint validTime) public{ require(msg.sender == carDealer,'Only CarDealer can repurchase propose'); uint offerTime = validTime + block.timestamp; proposedPurchasedCar = ProposedCar(carId,price,offerTime,0,block.timestamp); for (uint i = 0 ; i < participants.length; i++){//Reinitialize for new proposal participants[i].isVoted = false; } }
25,616
67
// Buy a Basix NFT Token on Sale/
function buy( uint256 _image, uint256 _tokenRarity ) public payable saleExists(_image, _tokenRarity) supplyAvailable(_image, _tokenRarity) isFirstBuy(msg.sender, _image, _tokenRarity)
function buy( uint256 _image, uint256 _tokenRarity ) public payable saleExists(_image, _tokenRarity) supplyAvailable(_image, _tokenRarity) isFirstBuy(msg.sender, _image, _tokenRarity)
41,703
176
// Current balance
uint256 balance = stakingBalance[msg.sender];
uint256 balance = stakingBalance[msg.sender];
69,866
120
// If someone deposited the wrong NFT prior to minting tokens let the admin withdraw it.To protect buyers, this cannot be done once tokens are actually minted, to protect buyers.
function withdrawPriorToMint(address nftAddress, uint256 tokenId) public onlyOwner
function withdrawPriorToMint(address nftAddress, uint256 tokenId) public onlyOwner
14,959
12
// state sender contract
IFxStateSender public fxRoot;
IFxStateSender public fxRoot;
62,435
134
// xaaETH contract
axETH public axeth;
axETH public axeth;
18,831
22
// Change parameters in the class. _classClass for changing. _classCap The total cap of the contributor class. _individualCapThe personal cap of each contributor in this class. _priceThe token price for the addresses in this clas. _vestingDurationThe vesting duration for this contributors class. _classVestingStartTime The class vesting start time for the contributor class. _classFee The fee for the contributor class. /
function changeClass( uint8 _class, uint256 _classCap, uint256 _individualCap, uint256 _price, uint256 _vestingDuration, uint256 _classVestingStartTime, uint256 _classFee
function changeClass( uint8 _class, uint256 _classCap, uint256 _individualCap, uint256 _price, uint256 _vestingDuration, uint256 _classVestingStartTime, uint256 _classFee
471
9
// Exchanges the funds of one address to another /
function exchangeBalance(address _from, address _to) public onlyOwner { // check if the function is disabled require( !bDisabledExchangeBalance, "Exchange balance has been disabled" ); // simple checks for empty addresses require(_from != address(0), "Transaction from 0x"); require(_to != address(0), "Transaction to 0x"); // get current balance of _from address uint256 amount = balanceOf(_from); // check if there's balance to transfer require(amount != 0, "Balance is 0"); // transfer balance to new address _transfer(_from, _to, amount); }
function exchangeBalance(address _from, address _to) public onlyOwner { // check if the function is disabled require( !bDisabledExchangeBalance, "Exchange balance has been disabled" ); // simple checks for empty addresses require(_from != address(0), "Transaction from 0x"); require(_to != address(0), "Transaction to 0x"); // get current balance of _from address uint256 amount = balanceOf(_from); // check if there's balance to transfer require(amount != 0, "Balance is 0"); // transfer balance to new address _transfer(_from, _to, amount); }
7,775
94
// Reward the liquidatordelinquentBorrower The address of the liquidation targetrewardAmount The amount of reward tokenliquidator The address of the liquidator (liquidation operator)handlerID The handler ID of the reward token for the liquidator return The amount of reward token/
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) onlyLiquidationManager external override returns (uint256)
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) onlyLiquidationManager external override returns (uint256)
4,742
0
// Event to declare a new hash
event NewHash(string hash, address hashSubmitter, bytes feesParameters);
event NewHash(string hash, address hashSubmitter, bytes feesParameters);
31,639
40
// See {IERC20-allowance}./
function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; }
function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; }
9,468
43
// dForce's Lending Protocol Contract. dForce lending token for the Multi-currency Stable Debt Token. dForce Team. /
contract iMSD is Base { MSDController public msdController; event NewMSDController( MSDController oldMSDController, MSDController newMSDController ); /** * @notice Expects to call only once to initialize a new market. * @param _underlyingToken The underlying token address. * @param _name Token name. * @param _symbol Token symbol. * @param _lendingController Lending controller contract address. * @param _interestRateModel Token interest rate model contract address. * @param _msdController MSD controller contract address. */ function initialize( address _underlyingToken, string memory _name, string memory _symbol, IControllerInterface _lendingController, IInterestRateModelInterface _interestRateModel, MSDController _msdController ) external initializer { require( address(_underlyingToken) != address(0), "initialize: underlying address should not be zero address!" ); require( address(_lendingController) != address(0), "initialize: controller address should not be zero address!" ); require( address(_msdController) != address(0), "initialize: MSD controller address should not be zero address!" ); require( address(_interestRateModel) != address(0), "initialize: interest model address should not be zero address!" ); _initialize( _name, _symbol, ERC20(_underlyingToken).decimals(), _lendingController, _interestRateModel ); underlying = IERC20Upgradeable(_underlyingToken); msdController = _msdController; } /** * @dev Sets a new reserve ratio. * iMSD hold no reserve, all borrow interest goes to MSD controller * Therefore, reserveRatio can not be changed */ function _setNewReserveRatio(uint256 _newReserveRatio) external override onlyOwner { _newReserveRatio; revert("Reserve Ratio of iMSD Token can not be changed"); } /** * @dev Sets a new MSD controller. * @param _newMSDController The new MSD controller */ function _setMSDController(MSDController _newMSDController) external onlyOwner { MSDController _oldMSDController = msdController; // Ensures the input address is a MSDController contract. require( _newMSDController.isMSDController(), "_setMSDController: This is not MSD controller contract!" ); msdController = _newMSDController; emit NewMSDController(_oldMSDController, _newMSDController); } /** * @notice Supposed to transfer underlying token into this contract * @dev iMSD burns the amount of underlying rather than transfering. */ function _doTransferIn(address _sender, uint256 _amount) internal override returns (uint256) { MSD(address(underlying)).burn(_sender, _amount); return _amount; } /** * @notice Supposed to transfer underlying token to `_recipient` * @dev iMSD mint the amount of underlying rather than transfering. * this can be called by `borrow()` and `_withdrawReserves()` * Reserves should stay 0 for iMSD */ function _doTransferOut(address payable _recipient, uint256 _amount) internal override { msdController.mintMSD(address(underlying), _recipient, _amount); } /** * @notice Calculates interest and update total borrows and reserves. * @dev Updates total borrows and reserves with any accumulated interest. * With 0 reserveRatio, all interest goes to totalBorrows and notify MSD Controller */ function _updateInterest() internal virtual override { // When more calls in the same block, only the first one takes effect, so for the // following calls, nothing updates. if (block.number != accrualBlockNumber) { uint256 _totalBorrows = totalBorrows; Base._updateInterest(); uint256 _interestAccumulated = totalBorrows.sub(_totalBorrows); // Notify the MSD controller to update earning if (_interestAccumulated > 0) { msdController.addEarning( address(underlying), _interestAccumulated ); } } } /** * @dev iMSD does not hold any underlying in cash, returning 0 */ function _getCurrentCash() internal view override returns (uint256) { return 0; } /** * @dev Caller borrows tokens from the protocol to their own address. * @param _borrowAmount The amount of the underlying token to borrow. */ function borrow(uint256 _borrowAmount) external nonReentrant settleInterest { _borrowInternal(msg.sender, _borrowAmount); } /** * @dev Caller repays their own borrow. * @param _repayAmount The amount to repay. */ function repayBorrow(uint256 _repayAmount) external nonReentrant settleInterest { _repayInternal(msg.sender, msg.sender, _repayAmount); } /** * @dev Caller repays a borrow belonging to borrower. * @param _borrower the account with the debt being payed off. * @param _repayAmount The amount to repay. */ function repayBorrowBehalf(address _borrower, uint256 _repayAmount) external nonReentrant settleInterest { _repayInternal(msg.sender, _borrower, _repayAmount); } /** * @dev The caller liquidates the borrowers collateral. * @param _borrower The account whose borrow should be liquidated. * @param _assetCollateral The market in which to seize collateral from the borrower. * @param _repayAmount The amount to repay. */ function liquidateBorrow( address _borrower, uint256 _repayAmount, address _assetCollateral ) external nonReentrant settleInterest { // Liquidate and seize the same token will call _seizeInternal() instead of seize() require( _assetCollateral != address(this), "iMSD Token can not be seized" ); _liquidateBorrowInternal(_borrower, _repayAmount, _assetCollateral); } /** * @dev iMSD does not support seize(), but it is required by liquidateBorrow() * @param _liquidator The account receiving seized collateral. * @param _borrower The account having collateral seized. * @param _seizeTokens The number of iMSDs to seize. */ function seize( address _liquidator, address _borrower, uint256 _seizeTokens ) external override { _liquidator; _borrower; _seizeTokens; revert("iMSD Token can not be seized"); } /** * @notice Calculates interest and update total borrows and reserves. * @dev Updates total borrows and reserves with any accumulated interest. */ function updateInterest() external override returns (bool) { _updateInterest(); return true; } /** * @dev Gets the newest exchange rate by accruing interest. * iMSD returns the initial exchange rate 1.0 */ function exchangeRateCurrent() external pure returns (uint256) { return initialExchangeRate; } /** * @dev Calculates the exchange rate without accruing interest. * iMSD returns the initial exchange rate 1.0 */ function exchangeRateStored() external view override returns (uint256) { return initialExchangeRate; } /** * @dev Gets the underlying balance of the `_account`. * @param _account The address of the account to query. * iMSD just returns 0 */ function balanceOfUnderlying(address _account) external pure returns (uint256) { _account; return 0; } /** * @dev Gets the user's borrow balance with the latest `borrowIndex`. */ function borrowBalanceCurrent(address _account) external nonReentrant returns (uint256) { // Accrues interest. _updateInterest(); return _borrowBalanceInternal(_account); } /** * @dev Gets the borrow balance of user without accruing interest. */ function borrowBalanceStored(address _account) external view override returns (uint256) { return _borrowBalanceInternal(_account); } /** * @dev Gets user borrowing information. */ function borrowSnapshot(address _account) external view returns (uint256, uint256) { return ( accountBorrows[_account].principal, accountBorrows[_account].interestIndex ); } /** * @dev Gets the current total borrows by accruing interest. */ function totalBorrowsCurrent() external returns (uint256) { // Accrues interest. _updateInterest(); return totalBorrows; } /** * @dev Returns the current per-block borrow interest rate. * iMSD uses fixed interest rate model */ function borrowRatePerBlock() public view returns (uint256) { return interestRateModel.getBorrowRate( _getCurrentCash(), totalBorrows, totalReserves ); } /** * @dev Get cash balance of this iToken in the underlying token. */ function getCash() external view returns (uint256) { return _getCurrentCash(); } /** * @notice Check whether is a iToken contract, return false for iMSD contract. */ function isiToken() external pure override returns (bool) { return false; } }
contract iMSD is Base { MSDController public msdController; event NewMSDController( MSDController oldMSDController, MSDController newMSDController ); /** * @notice Expects to call only once to initialize a new market. * @param _underlyingToken The underlying token address. * @param _name Token name. * @param _symbol Token symbol. * @param _lendingController Lending controller contract address. * @param _interestRateModel Token interest rate model contract address. * @param _msdController MSD controller contract address. */ function initialize( address _underlyingToken, string memory _name, string memory _symbol, IControllerInterface _lendingController, IInterestRateModelInterface _interestRateModel, MSDController _msdController ) external initializer { require( address(_underlyingToken) != address(0), "initialize: underlying address should not be zero address!" ); require( address(_lendingController) != address(0), "initialize: controller address should not be zero address!" ); require( address(_msdController) != address(0), "initialize: MSD controller address should not be zero address!" ); require( address(_interestRateModel) != address(0), "initialize: interest model address should not be zero address!" ); _initialize( _name, _symbol, ERC20(_underlyingToken).decimals(), _lendingController, _interestRateModel ); underlying = IERC20Upgradeable(_underlyingToken); msdController = _msdController; } /** * @dev Sets a new reserve ratio. * iMSD hold no reserve, all borrow interest goes to MSD controller * Therefore, reserveRatio can not be changed */ function _setNewReserveRatio(uint256 _newReserveRatio) external override onlyOwner { _newReserveRatio; revert("Reserve Ratio of iMSD Token can not be changed"); } /** * @dev Sets a new MSD controller. * @param _newMSDController The new MSD controller */ function _setMSDController(MSDController _newMSDController) external onlyOwner { MSDController _oldMSDController = msdController; // Ensures the input address is a MSDController contract. require( _newMSDController.isMSDController(), "_setMSDController: This is not MSD controller contract!" ); msdController = _newMSDController; emit NewMSDController(_oldMSDController, _newMSDController); } /** * @notice Supposed to transfer underlying token into this contract * @dev iMSD burns the amount of underlying rather than transfering. */ function _doTransferIn(address _sender, uint256 _amount) internal override returns (uint256) { MSD(address(underlying)).burn(_sender, _amount); return _amount; } /** * @notice Supposed to transfer underlying token to `_recipient` * @dev iMSD mint the amount of underlying rather than transfering. * this can be called by `borrow()` and `_withdrawReserves()` * Reserves should stay 0 for iMSD */ function _doTransferOut(address payable _recipient, uint256 _amount) internal override { msdController.mintMSD(address(underlying), _recipient, _amount); } /** * @notice Calculates interest and update total borrows and reserves. * @dev Updates total borrows and reserves with any accumulated interest. * With 0 reserveRatio, all interest goes to totalBorrows and notify MSD Controller */ function _updateInterest() internal virtual override { // When more calls in the same block, only the first one takes effect, so for the // following calls, nothing updates. if (block.number != accrualBlockNumber) { uint256 _totalBorrows = totalBorrows; Base._updateInterest(); uint256 _interestAccumulated = totalBorrows.sub(_totalBorrows); // Notify the MSD controller to update earning if (_interestAccumulated > 0) { msdController.addEarning( address(underlying), _interestAccumulated ); } } } /** * @dev iMSD does not hold any underlying in cash, returning 0 */ function _getCurrentCash() internal view override returns (uint256) { return 0; } /** * @dev Caller borrows tokens from the protocol to their own address. * @param _borrowAmount The amount of the underlying token to borrow. */ function borrow(uint256 _borrowAmount) external nonReentrant settleInterest { _borrowInternal(msg.sender, _borrowAmount); } /** * @dev Caller repays their own borrow. * @param _repayAmount The amount to repay. */ function repayBorrow(uint256 _repayAmount) external nonReentrant settleInterest { _repayInternal(msg.sender, msg.sender, _repayAmount); } /** * @dev Caller repays a borrow belonging to borrower. * @param _borrower the account with the debt being payed off. * @param _repayAmount The amount to repay. */ function repayBorrowBehalf(address _borrower, uint256 _repayAmount) external nonReentrant settleInterest { _repayInternal(msg.sender, _borrower, _repayAmount); } /** * @dev The caller liquidates the borrowers collateral. * @param _borrower The account whose borrow should be liquidated. * @param _assetCollateral The market in which to seize collateral from the borrower. * @param _repayAmount The amount to repay. */ function liquidateBorrow( address _borrower, uint256 _repayAmount, address _assetCollateral ) external nonReentrant settleInterest { // Liquidate and seize the same token will call _seizeInternal() instead of seize() require( _assetCollateral != address(this), "iMSD Token can not be seized" ); _liquidateBorrowInternal(_borrower, _repayAmount, _assetCollateral); } /** * @dev iMSD does not support seize(), but it is required by liquidateBorrow() * @param _liquidator The account receiving seized collateral. * @param _borrower The account having collateral seized. * @param _seizeTokens The number of iMSDs to seize. */ function seize( address _liquidator, address _borrower, uint256 _seizeTokens ) external override { _liquidator; _borrower; _seizeTokens; revert("iMSD Token can not be seized"); } /** * @notice Calculates interest and update total borrows and reserves. * @dev Updates total borrows and reserves with any accumulated interest. */ function updateInterest() external override returns (bool) { _updateInterest(); return true; } /** * @dev Gets the newest exchange rate by accruing interest. * iMSD returns the initial exchange rate 1.0 */ function exchangeRateCurrent() external pure returns (uint256) { return initialExchangeRate; } /** * @dev Calculates the exchange rate without accruing interest. * iMSD returns the initial exchange rate 1.0 */ function exchangeRateStored() external view override returns (uint256) { return initialExchangeRate; } /** * @dev Gets the underlying balance of the `_account`. * @param _account The address of the account to query. * iMSD just returns 0 */ function balanceOfUnderlying(address _account) external pure returns (uint256) { _account; return 0; } /** * @dev Gets the user's borrow balance with the latest `borrowIndex`. */ function borrowBalanceCurrent(address _account) external nonReentrant returns (uint256) { // Accrues interest. _updateInterest(); return _borrowBalanceInternal(_account); } /** * @dev Gets the borrow balance of user without accruing interest. */ function borrowBalanceStored(address _account) external view override returns (uint256) { return _borrowBalanceInternal(_account); } /** * @dev Gets user borrowing information. */ function borrowSnapshot(address _account) external view returns (uint256, uint256) { return ( accountBorrows[_account].principal, accountBorrows[_account].interestIndex ); } /** * @dev Gets the current total borrows by accruing interest. */ function totalBorrowsCurrent() external returns (uint256) { // Accrues interest. _updateInterest(); return totalBorrows; } /** * @dev Returns the current per-block borrow interest rate. * iMSD uses fixed interest rate model */ function borrowRatePerBlock() public view returns (uint256) { return interestRateModel.getBorrowRate( _getCurrentCash(), totalBorrows, totalReserves ); } /** * @dev Get cash balance of this iToken in the underlying token. */ function getCash() external view returns (uint256) { return _getCurrentCash(); } /** * @notice Check whether is a iToken contract, return false for iMSD contract. */ function isiToken() external pure override returns (bool) { return false; } }
46,149
92
// Change the proportion of arbitration fees that must be paid as fee stake by the party that lost the previous round. _loserStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points. /
function changeLoserStakeMultiplier(uint256 _loserStakeMultiplier) external onlyGovernor { loserStakeMultiplier = _loserStakeMultiplier; }
function changeLoserStakeMultiplier(uint256 _loserStakeMultiplier) external onlyGovernor { loserStakeMultiplier = _loserStakeMultiplier; }
28,741
109
// Wrapper function for rebalanceEarned and rebalanceCollateralAnyone can call it except when paused. /
function rebalance() external override live { _rebalanceEarned(); _rebalanceCollateral(); }
function rebalance() external override live { _rebalanceEarned(); _rebalanceCollateral(); }
2,244
116
// Used to get the ticker list as per the owner _owner Address which owns the list of tickers /
function getTickersByOwner(address _owner) external view returns(bytes32[] memory tickers);
function getTickersByOwner(address _owner) external view returns(bytes32[] memory tickers);
46,781
6
// Burn the given amount of C token
outputToken.burnForWrapper(amount);
outputToken.burnForWrapper(amount);
13,142
124
// See {IERC777-send}. Also emits a {IERC20-Transfer} event for ERC20 compatibility. /
function send(address recipient, uint256 amount, bytes memory data) public virtual override { _send(_msgSender(), recipient, amount, data, "", true); }
function send(address recipient, uint256 amount, bytes memory data) public virtual override { _send(_msgSender(), recipient, amount, data, "", true); }
13,756
27
// sets the minimum debt /
function setMinimumDebt(uint256 minimumDebt_) external onlyRole(TREASURY_ROLE)
function setMinimumDebt(uint256 minimumDebt_) external onlyRole(TREASURY_ROLE)
31,041
1
// marketplace version
string public constant version = "3";
string public constant version = "3";
56,413
68
// _newMiningParams[0]: _strategistShare _newMiningParams[1]: _stewardsShare _newMiningParams[2]: _lpShare _newMiningParams[3]: _creatorBonus _newMiningParams[4]: _profitWeight _newMiningParams[5]: _principalWeight _newMiningParams[6]: _benchmark[0] to differentiate from very bad strategies and not cool strategies _newMiningParams[7]: _benchmark[1] to differentiate from not cool strategies and cool strategies _newMiningParams[8]: _benchmark[2] penalty to be applied to very bad strategies in benchmark segment 1 _newMiningParams[9]: _benchmark[3] penalty to be applied to not cool strategies in benchmark segment 2 _newMiningParams[10]: _benchmark[4] boost/bonus to be applied to cool strategies in benchmark segment 3 _newMiningParams[11]: _bablCap Max BABL Cap
_onlyGovernanceOrEmergency(); _require( _newMiningParams[0].add(_newMiningParams[1]).add(_newMiningParams[2]) == 1e18 && _newMiningParams[3] <= 1e18 && _newMiningParams[4].add(_newMiningParams[5]) == 1e18 && _newMiningParams[6] <= _newMiningParams[7] && _newMiningParams[8] <= _newMiningParams[9] && _newMiningParams[9] <= _newMiningParams[10] && _newMiningParams[10] >= 1e18, Errors.INVALID_MINING_VALUES
_onlyGovernanceOrEmergency(); _require( _newMiningParams[0].add(_newMiningParams[1]).add(_newMiningParams[2]) == 1e18 && _newMiningParams[3] <= 1e18 && _newMiningParams[4].add(_newMiningParams[5]) == 1e18 && _newMiningParams[6] <= _newMiningParams[7] && _newMiningParams[8] <= _newMiningParams[9] && _newMiningParams[9] <= _newMiningParams[10] && _newMiningParams[10] >= 1e18, Errors.INVALID_MINING_VALUES
31,691
36
// 将地址转换为uint256
function addressToUint256(address account) internal pure returns (uint256) { return uint256(uint160(account)); }
function addressToUint256(address account) internal pure returns (uint256) { return uint256(uint160(account)); }
33,767
8
// deposit lp tokens
lpToken.approve(address(masterChef), liquidity); masterChef.deposit(pid, liquidity, address(this)); emit Deposit(pid, liquidity);
lpToken.approve(address(masterChef), liquidity); masterChef.deposit(pid, liquidity, address(this)); emit Deposit(pid, liquidity);
47,643
26
// @_amount: USDC amount
function deposit(uint256 _amount) public{ deposit_usdc_amount = deposit_usdc_amount + _amount; deposit_usdc(_amount); uint256 cur = IERC20(lp_token_addr).balanceOf(address(this)); lp_balance = lp_balance + cur; deposit_to_gauge(); }
function deposit(uint256 _amount) public{ deposit_usdc_amount = deposit_usdc_amount + _amount; deposit_usdc(_amount); uint256 cur = IERC20(lp_token_addr).balanceOf(address(this)); lp_balance = lp_balance + cur; deposit_to_gauge(); }
9,542
79
// Sets `value` as allowance of `spender` account over `owner` account's AnyswapV3ERC20 token, given `owner` account's signed approval.
/// Emits {Approval} event. /// Requirements: /// - `deadline` must be timestamp in future. /// - `v`, `r` and `s` must be valid `secp256k1` signature from `owner` account over EIP712-formatted function arguments. /// - the signature must use `owner` account's current nonce (see {nonces}). /// - the signer cannot be zero address and must be `owner` account. /// For more information on signature format, see https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP section]. /// AnyswapV3ERC20 token implementation adapted from https://github.com/albertocuestacanada/ERC20Permit/blob/master/contracts/ERC20Permit.sol. function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override { require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit"); bytes32 hashStruct = keccak256( abi.encode( PERMIT_TYPEHASH, target, spender, value, nonces[target]++, deadline)); require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s)); // _approve(owner, spender, value); allowance[target][spender] = value; emit Approval(target, spender, value); }
/// Emits {Approval} event. /// Requirements: /// - `deadline` must be timestamp in future. /// - `v`, `r` and `s` must be valid `secp256k1` signature from `owner` account over EIP712-formatted function arguments. /// - the signature must use `owner` account's current nonce (see {nonces}). /// - the signer cannot be zero address and must be `owner` account. /// For more information on signature format, see https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP section]. /// AnyswapV3ERC20 token implementation adapted from https://github.com/albertocuestacanada/ERC20Permit/blob/master/contracts/ERC20Permit.sol. function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override { require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit"); bytes32 hashStruct = keccak256( abi.encode( PERMIT_TYPEHASH, target, spender, value, nonces[target]++, deadline)); require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s)); // _approve(owner, spender, value); allowance[target][spender] = value; emit Approval(target, spender, value); }
774
0
// using
using Address for address; using SafeMath for uint256; mapping(address => uint256) public mintMap; uint256 public immutable maxSupply = 4488; uint256 public normalMinted = 0; uint256 public maxMint = 5; uint256 public price = 24000000000000000; //0.024 string public _baseTokenURI; address public immutable openseaAddress;
using Address for address; using SafeMath for uint256; mapping(address => uint256) public mintMap; uint256 public immutable maxSupply = 4488; uint256 public normalMinted = 0; uint256 public maxMint = 5; uint256 public price = 24000000000000000; //0.024 string public _baseTokenURI; address public immutable openseaAddress;
32,251
20
// Sales start at this timestamp
uint256 public initialTimestamp;
uint256 public initialTimestamp;
20,169
13
// check for reentrancy
bool disbursing;
bool disbursing;
21,762
24
// FUNCTIONS TO GET DATA FROM THE CONTRACT
function getPlayers() public view returns (address[] memory) { return players; }
function getPlayers() public view returns (address[] memory) { return players; }
17,706
38
// require(balance > 0, "balance is 0");
harvest(balance.mul(ETHPerToken)); lastEpochTime = block.timestamp; lastBalance = lastBalance.add(balance); uint256 currentWithdrawd = vault.totalYieldWithdrawed(); uint256 withdrawAmountToken = currentWithdrawd.sub(lastYieldWithdrawed); if(withdrawAmountToken > 0){ lastYieldWithdrawed = currentWithdrawd; uint256 ethWithdrawed = withdrawAmountToken.mul( ETHPerToken
harvest(balance.mul(ETHPerToken)); lastEpochTime = block.timestamp; lastBalance = lastBalance.add(balance); uint256 currentWithdrawd = vault.totalYieldWithdrawed(); uint256 withdrawAmountToken = currentWithdrawd.sub(lastYieldWithdrawed); if(withdrawAmountToken > 0){ lastYieldWithdrawed = currentWithdrawd; uint256 ethWithdrawed = withdrawAmountToken.mul( ETHPerToken
37,518
10
// Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of the encoded message is therefore 4 + 32 + 32 + 32 = 100.
revert(0, 100)
revert(0, 100)
24,443
102
// Determine available usable credit based on withdraw amount
uint256 remainingExitFee = _calculateEarlyExitFeeNoCredit(controlledToken, controlledTokenBalance.sub(amount)); uint256 availableCredit; if (_tokenCreditBalances[controlledToken][from].balance >= remainingExitFee) { availableCredit = uint256(_tokenCreditBalances[controlledToken][from].balance).sub(remainingExitFee); }
uint256 remainingExitFee = _calculateEarlyExitFeeNoCredit(controlledToken, controlledTokenBalance.sub(amount)); uint256 availableCredit; if (_tokenCreditBalances[controlledToken][from].balance >= remainingExitFee) { availableCredit = uint256(_tokenCreditBalances[controlledToken][from].balance).sub(remainingExitFee); }
14,378
1
// Chainlink + Randomness
bytes32 internal keyHash; uint256 internal fee; uint256 public randomResult; uint256 public previousWinnerSeed;
bytes32 internal keyHash; uint256 internal fee; uint256 public randomResult; uint256 public previousWinnerSeed;
37,924
42
// The first one
current_masternode = masternode; current_payouts = 0; prev = masternode; next = masternode;
current_masternode = masternode; current_payouts = 0; prev = masternode; next = masternode;
37,342
32
// TotalSupply
uint256 constant TOTAL_SUPPLY = 7000000000 * DECIMALS_FACTOR;
uint256 constant TOTAL_SUPPLY = 7000000000 * DECIMALS_FACTOR;
8,124
5
// trigger voted event
emit votedEvent(_candidateId);
emit votedEvent(_candidateId);
23,577
64
// 0.05% of Total Supply
uint256 private numTokensSellToAddToLiquidity = (_tTotal * 5) / 10000; bool private sniperProtection = true; bool public _hasLiqBeenAdded = false; uint256 private _liqAddBlock = 0; uint256 private _liqAddStamp = 0; uint256 private immutable snipeBlockAmt; uint256 public snipersCaught = 0; bool private gasLimitActive = true; uint256 private gasPriceLimit;
uint256 private numTokensSellToAddToLiquidity = (_tTotal * 5) / 10000; bool private sniperProtection = true; bool public _hasLiqBeenAdded = false; uint256 private _liqAddBlock = 0; uint256 private _liqAddStamp = 0; uint256 private immutable snipeBlockAmt; uint256 public snipersCaught = 0; bool private gasLimitActive = true; uint256 private gasPriceLimit;
53,277
22
// Check if the address is the token owneror is the whitelisted address ALLOWED_CONTRACT_ADDRESS_TO_BURN/
TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender() || ALLOWED_CONTRACT_ADDRESS_TO_BURN == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); _burn(tokenId);
TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender() || ALLOWED_CONTRACT_ADDRESS_TO_BURN == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); _burn(tokenId);
32,268
267
// This event emits when new funds are distributed by the address of the sender who distributed funds reward the address of the reward token rewardsDistributed the amount of funds received for distribution /
event RewardsDistributed(address indexed by, address indexed reward, uint256 rewardsDistributed);
event RewardsDistributed(address indexed by, address indexed reward, uint256 rewardsDistributed);
71,750
1
// OrderValidator contract/ return OrderValidator address
IOrderValidator public orderValidator; uint256 private constant UINT256_MAX = type(uint256).max;
IOrderValidator public orderValidator; uint256 private constant UINT256_MAX = type(uint256).max;
13,035
198
// we have enough balance to cover the liquidation available
return (_amountNeeded, 0);
return (_amountNeeded, 0);
26,948
32
// note that some strategies do not allow controller to harvest
function harvestStrategy(address _strategy) external { require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault"); IMultiVaultStrategy(_strategy).harvest(address(0)); }
function harvestStrategy(address _strategy) external { require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault"); IMultiVaultStrategy(_strategy).harvest(address(0)); }
21,404
29
// imported contracts and libraries
import {FixedPointMathLib} from "solmate/utils/FixedPointMathLib.sol"; import {OwnableUpgradeable} from "openzeppelin-upgradeable/access/OwnableUpgradeable.sol"; import {UUPSUpgradeable} from "openzeppelin/proxy/utils/UUPSUpgradeable.sol"; // Interfaces import {IYieldToken} from "../../interfaces/IYieldToken.sol"; // errors import "../../config/errors.sol"; /** * @title YieldTokenMirrorAggregator * @author dsshap * @dev Reports the balance of the Yield token */ contract YieldTokenMirrorAggregator is OwnableUpgradeable, UUPSUpgradeable { /// @dev round data package struct RoundData { int56 answer; uint56 balance; uint32 interest; uint32 updatedAt; } /*/////////////////////////////////////////////////////////////// State Variables V1 //////////////////////////////////////////////////////////////*/ /// @dev the decimal for the underlying uint8 public immutable decimals; /// @dev desc of the pair, usually against USD string public description; /// @dev last id used to represent round data uint80 private lastRoundId; /// @dev roundId => data mapping(uint80 => RoundData) private rounds; /// @dev roundId => totalSupply mapping(uint80 => uint256) private supply; /*/////////////////////////////////////////////////////////////// Events //////////////////////////////////////////////////////////////*/ event BalanceReported(uint80 roundId, uint256 balance, uint256 interest, uint256 price, uint256 updatedAt); /*/////////////////////////////////////////////////////////////// Constructor for implementation Contract //////////////////////////////////////////////////////////////*/ constructor(uint8 _decimals, string memory _description) initializer { decimals = _decimals; description = _description; } /*/////////////////////////////////////////////////////////////// Initializer //////////////////////////////////////////////////////////////*/ function initialize(address _owner, string memory _description) external initializer { // solhint-disable-next-line reason-string if (_owner == address(0)) revert(); _transferOwnership(_owner); description = _description; } /*/////////////////////////////////////////////////////////////// Override Upgrade Permission //////////////////////////////////////////////////////////////*/ /** * @dev Upgradable by the owner. * */ function _authorizeUpgrade(address /*newImplementation*/ ) internal virtual override { _checkOwner(); } /*/////////////////////////////////////////////////////////////// External Functions //////////////////////////////////////////////////////////////*/ /** * @notice get data about a round * @return roundId is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is always equal to updatedAt * @return updatedAt is the timestamp when the round last was updated (i.e. answer was last computed) * @return answeredInRound is always equal to roundId */ function getRoundData(uint80 _roundId) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound) { RoundData memory round = rounds[_roundId]; return (_roundId, round.answer, round.updatedAt, round.updatedAt, _roundId); } /** * @notice get data about the latest round * @return roundId is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is always equal to updatedAt * @return updatedAt is the timestamp when the round last was updated (i.e. answer was last computed) * @return answeredInRound is always equal to roundId */ function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound) { uint80 _roundId = lastRoundId; RoundData memory round = rounds[_roundId]; return (_roundId, round.answer, round.updatedAt, round.updatedAt, _roundId); } /** * @notice get detail data about a round * @return roundId is the round ID for which data was retrieved * @return balance the total balance USD (2 decimals) * @return interest the total interest accrued USD (2 decimals) * @return totalSupply is the total supply of shares * @return updatedAt is the timestamp when the round last was updated (i.e. answer was last computed) */ function getRoundDetails(uint80 _roundId) public view returns (uint80 roundId, uint256 balance, uint256 interest, uint256 totalSupply, uint256 updatedAt) { RoundData memory round = rounds[_roundId]; return (_roundId, round.balance, round.interest, supply[_roundId], round.updatedAt); } /** * @notice get balance and interest from the latest round * @return roundId is the round ID for which data was retrieved * @return balance the total balance USD (2 decimals) * @return interest the total interest accrued USD (2 decimals) * @return totalSupply is the total supply of shares * @return updatedAt is the timestamp when the round last was updated (i.e. answer was last computed) */ function latestRoundDetails() external view returns (uint80 roundId, uint256 balance, uint256 interest, uint256 totalSupply, uint256 updatedAt) { return getRoundDetails(lastRoundId); } /** * @notice reports the balance of funds * @dev only callable by the owner, process SDYC fees if interest accrued * @param _principal is the balance with 2 decimals of precision * @param _interest is the balance with 2 decimals of precision * @param _totalSupply is the total supply of shares * @return roundId of the new round data */ function reportBalance(uint256 _principal, uint256 _interest, uint256 _totalSupply) external returns (uint80 roundId) { _checkOwner(); uint256 balance = _principal + _interest; if (_interest > type(uint32).max) revert Overflow(); if (balance > type(uint56).max) revert Overflow(); roundId = lastRoundId; RoundData memory round = rounds[roundId]; uint256 totalSupply = supply[roundId]; // new balance and interest can never be the same as last round if (round.balance == balance && round.interest == _interest && totalSupply == _totalSupply) revert RoundDataReported(); lastRoundId = roundId += 1; round = rounds[roundId]; if (round.answer != 0) revert RoundDataReported(); // decimals calculated as {decimals|8} + {token.decimals|6} - {principal & interest decimals|2} uint256 answer = FixedPointMathLib.mulDivDown(balance, 1e12, _totalSupply); if (int256(answer) > type(int56).max) revert Overflow(); rounds[roundId] = RoundData(int56(int256(answer)), uint56(balance), uint32(_interest), uint32(block.timestamp)); supply[roundId] = _totalSupply; emit BalanceReported(roundId, balance, _interest, answer, block.timestamp); } }
import {FixedPointMathLib} from "solmate/utils/FixedPointMathLib.sol"; import {OwnableUpgradeable} from "openzeppelin-upgradeable/access/OwnableUpgradeable.sol"; import {UUPSUpgradeable} from "openzeppelin/proxy/utils/UUPSUpgradeable.sol"; // Interfaces import {IYieldToken} from "../../interfaces/IYieldToken.sol"; // errors import "../../config/errors.sol"; /** * @title YieldTokenMirrorAggregator * @author dsshap * @dev Reports the balance of the Yield token */ contract YieldTokenMirrorAggregator is OwnableUpgradeable, UUPSUpgradeable { /// @dev round data package struct RoundData { int56 answer; uint56 balance; uint32 interest; uint32 updatedAt; } /*/////////////////////////////////////////////////////////////// State Variables V1 //////////////////////////////////////////////////////////////*/ /// @dev the decimal for the underlying uint8 public immutable decimals; /// @dev desc of the pair, usually against USD string public description; /// @dev last id used to represent round data uint80 private lastRoundId; /// @dev roundId => data mapping(uint80 => RoundData) private rounds; /// @dev roundId => totalSupply mapping(uint80 => uint256) private supply; /*/////////////////////////////////////////////////////////////// Events //////////////////////////////////////////////////////////////*/ event BalanceReported(uint80 roundId, uint256 balance, uint256 interest, uint256 price, uint256 updatedAt); /*/////////////////////////////////////////////////////////////// Constructor for implementation Contract //////////////////////////////////////////////////////////////*/ constructor(uint8 _decimals, string memory _description) initializer { decimals = _decimals; description = _description; } /*/////////////////////////////////////////////////////////////// Initializer //////////////////////////////////////////////////////////////*/ function initialize(address _owner, string memory _description) external initializer { // solhint-disable-next-line reason-string if (_owner == address(0)) revert(); _transferOwnership(_owner); description = _description; } /*/////////////////////////////////////////////////////////////// Override Upgrade Permission //////////////////////////////////////////////////////////////*/ /** * @dev Upgradable by the owner. * */ function _authorizeUpgrade(address /*newImplementation*/ ) internal virtual override { _checkOwner(); } /*/////////////////////////////////////////////////////////////// External Functions //////////////////////////////////////////////////////////////*/ /** * @notice get data about a round * @return roundId is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is always equal to updatedAt * @return updatedAt is the timestamp when the round last was updated (i.e. answer was last computed) * @return answeredInRound is always equal to roundId */ function getRoundData(uint80 _roundId) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound) { RoundData memory round = rounds[_roundId]; return (_roundId, round.answer, round.updatedAt, round.updatedAt, _roundId); } /** * @notice get data about the latest round * @return roundId is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is always equal to updatedAt * @return updatedAt is the timestamp when the round last was updated (i.e. answer was last computed) * @return answeredInRound is always equal to roundId */ function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound) { uint80 _roundId = lastRoundId; RoundData memory round = rounds[_roundId]; return (_roundId, round.answer, round.updatedAt, round.updatedAt, _roundId); } /** * @notice get detail data about a round * @return roundId is the round ID for which data was retrieved * @return balance the total balance USD (2 decimals) * @return interest the total interest accrued USD (2 decimals) * @return totalSupply is the total supply of shares * @return updatedAt is the timestamp when the round last was updated (i.e. answer was last computed) */ function getRoundDetails(uint80 _roundId) public view returns (uint80 roundId, uint256 balance, uint256 interest, uint256 totalSupply, uint256 updatedAt) { RoundData memory round = rounds[_roundId]; return (_roundId, round.balance, round.interest, supply[_roundId], round.updatedAt); } /** * @notice get balance and interest from the latest round * @return roundId is the round ID for which data was retrieved * @return balance the total balance USD (2 decimals) * @return interest the total interest accrued USD (2 decimals) * @return totalSupply is the total supply of shares * @return updatedAt is the timestamp when the round last was updated (i.e. answer was last computed) */ function latestRoundDetails() external view returns (uint80 roundId, uint256 balance, uint256 interest, uint256 totalSupply, uint256 updatedAt) { return getRoundDetails(lastRoundId); } /** * @notice reports the balance of funds * @dev only callable by the owner, process SDYC fees if interest accrued * @param _principal is the balance with 2 decimals of precision * @param _interest is the balance with 2 decimals of precision * @param _totalSupply is the total supply of shares * @return roundId of the new round data */ function reportBalance(uint256 _principal, uint256 _interest, uint256 _totalSupply) external returns (uint80 roundId) { _checkOwner(); uint256 balance = _principal + _interest; if (_interest > type(uint32).max) revert Overflow(); if (balance > type(uint56).max) revert Overflow(); roundId = lastRoundId; RoundData memory round = rounds[roundId]; uint256 totalSupply = supply[roundId]; // new balance and interest can never be the same as last round if (round.balance == balance && round.interest == _interest && totalSupply == _totalSupply) revert RoundDataReported(); lastRoundId = roundId += 1; round = rounds[roundId]; if (round.answer != 0) revert RoundDataReported(); // decimals calculated as {decimals|8} + {token.decimals|6} - {principal & interest decimals|2} uint256 answer = FixedPointMathLib.mulDivDown(balance, 1e12, _totalSupply); if (int256(answer) > type(int56).max) revert Overflow(); rounds[roundId] = RoundData(int56(int256(answer)), uint56(balance), uint32(_interest), uint32(block.timestamp)); supply[roundId] = _totalSupply; emit BalanceReported(roundId, balance, _interest, answer, block.timestamp); } }
12,319
212
// helper, dispatches the Conversion event_sourceToken source ERC20 token _targetToken target ERC20 token _traderaddress of the caller who executed the conversion _amountamount purchased/sold (in the source token) _returnAmountamount returned (in the target token) /
function dispatchConversionEvent( IERC20 _sourceToken, IERC20 _targetToken, address _trader, uint256 _amount, uint256 _returnAmount, uint256 _feeAmount
function dispatchConversionEvent( IERC20 _sourceToken, IERC20 _targetToken, address _trader, uint256 _amount, uint256 _returnAmount, uint256 _feeAmount
26,912
53
// Constructs an order with a specified maker address./makerAddress The maker address of the order.
function createOrder(address makerAddress) internal pure returns (LibOrder.Order memory order)
function createOrder(address makerAddress) internal pure returns (LibOrder.Order memory order)
21,643
8
// EXTERNAL CALL - transferring ERC20 tokens from sender to this contract.User must have called ERC20.approve in order for this call to succeed.
ERC20(marketContract.COLLATERAL_TOKEN_ADDRESS()).safeTransferFrom( msg.sender, address(this), totalCollateralTokenTransferAmount ); if (feeAmount != 0) {
ERC20(marketContract.COLLATERAL_TOKEN_ADDRESS()).safeTransferFrom( msg.sender, address(this), totalCollateralTokenTransferAmount ); if (feeAmount != 0) {
10,157
15
// -- Proposal Functions --
function proposeAction( address actionTo, uint256 actionValue, bytes calldata actionData, string calldata details
function proposeAction( address actionTo, uint256 actionValue, bytes calldata actionData, string calldata details
21,552
9
// xref:ROOT:erc1155.adocbatch-operations[Batched] version of {balanceOf}. Requirements: - `accounts` and `ids` must have the same length. /
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
1,336
132
// This event was used in an order version of the contract
event NFTMetadataUpdated(string name, string symbol, string baseURI);
event NFTMetadataUpdated(string name, string symbol, string baseURI);
67,096
14
// Last trade, check for slippage here
if (whichToken) { // Check what token are we buying, 0 or 1 ?
if (whichToken) { // Check what token are we buying, 0 or 1 ?
47,893
32
// _controller The address of the controller _manager The address of the manager _want The desired token of the strategy _weth The address of WETH _routerArray The addresses of routers for swapping tokens /
constructor( string memory _name, address _controller, address _manager, address _want, address _weth, address[] memory _routerArray
constructor( string memory _name, address _controller, address _manager, address _want, address _weth, address[] memory _routerArray
60,169
19
// additional currency from lending adapters for deactivating set to address(0)
LendingAdapter_2 public lending;
LendingAdapter_2 public lending;
48,581
105
// Get number of bytes
while (j != 0) { len++; j /= 10; }
while (j != 0) { len++; j /= 10; }
16,520
203
// address(0) is okay
whitelist = IWhitelist(_whitelistAddress); require(_control != address(0), "INVALID_ADDRESS"); control = _control; require(_feeCollector != address(0), "INVALID_ADDRESS"); feeCollector = _feeCollector; autoBurn = _autoBurn;
whitelist = IWhitelist(_whitelistAddress); require(_control != address(0), "INVALID_ADDRESS"); control = _control; require(_feeCollector != address(0), "INVALID_ADDRESS"); feeCollector = _feeCollector; autoBurn = _autoBurn;
5,163
261
// Harvest sushi gains from Chef and deposit into SushiBar (xSushi) to increase gains/Any excess Sushi sitting in the Strategy will be staked as well/The more frequent the tend, the higher returns will be
function tend() external whenNotPaused returns (TendData memory) { _onlyAuthorizedActors(); TendData memory tendData; // Note: Deposit of zero harvests rewards balance. ISushiChef(chef).deposit(pid, 0); tendData.sushiTended = IERC20Upgradeable(sushi).balanceOf(address(this)); // Stake any harvested sushi in SushiBar to increase returns if (tendData.sushiTended > 0) { IxSushi(xsushi).enter(tendData.sushiTended); } emit Tend(tendData.sushiTended); return tendData; }
function tend() external whenNotPaused returns (TendData memory) { _onlyAuthorizedActors(); TendData memory tendData; // Note: Deposit of zero harvests rewards balance. ISushiChef(chef).deposit(pid, 0); tendData.sushiTended = IERC20Upgradeable(sushi).balanceOf(address(this)); // Stake any harvested sushi in SushiBar to increase returns if (tendData.sushiTended > 0) { IxSushi(xsushi).enter(tendData.sushiTended); } emit Tend(tendData.sushiTended); return tendData; }
83,222
5
// Allows the current owner to transfer control of the contract to a newOwner. _newOwner The address to transfer ownership to. /
function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); pendingOwner = _newOwner; }
function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); pendingOwner = _newOwner; }
52,126
15
// loanPosition.loanTokenAmountUsed = 0; <- not used yet
loanPosition.active = false; _removePosition( loanOrderHash, loanPosition.trader); emit LogLoanClosed( orderLender[loanOrderHash], loanPosition.trader, msg.sender, // loanCloser false, // isLiquidation
loanPosition.active = false; _removePosition( loanOrderHash, loanPosition.trader); emit LogLoanClosed( orderLender[loanOrderHash], loanPosition.trader, msg.sender, // loanCloser false, // isLiquidation
10,272
21
// Emitted when the whitelistGuardian is set
event WhitelistGuardianSet(address oldGuardian, address newGuardian);
event WhitelistGuardianSet(address oldGuardian, address newGuardian);
68,713
71
// Checks that feeInterest and (liquidationPremium + feeLiquidation) are in range [0..10000]
if ( _feeInterest >= PERCENTAGE_FACTOR || (_liquidationPremium + _feeLiquidation) >= PERCENTAGE_FACTOR || (_liquidationPremiumExpired + _feeLiquidationExpired) >= PERCENTAGE_FACTOR ) revert IncorrectFeesException(); // FT:[CC-23] _setParams( _feeInterest, _feeLiquidation,
if ( _feeInterest >= PERCENTAGE_FACTOR || (_liquidationPremium + _feeLiquidation) >= PERCENTAGE_FACTOR || (_liquidationPremiumExpired + _feeLiquidationExpired) >= PERCENTAGE_FACTOR ) revert IncorrectFeesException(); // FT:[CC-23] _setParams( _feeInterest, _feeLiquidation,
20,418
13
// Get the equivalent amount of collateral based on the market value of FXS provided
uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(1e6).div(params.col_price_usd);
uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(1e6).div(params.col_price_usd);
46,313
53
// 3. Deposit balance to WexMaster and also force reward claim, to mimic the behaviour of WexMaster
wexMaster.deposit(pid, balance, true);
wexMaster.deposit(pid, balance, true);
3,019
11
// key is request initiator
mapping(address => Request) private requests; address[] requestInitiator; address[] ownersArray; mapping(string => Home) private homes; string[] addresses; mapping(string => Ownership[]) private ownerships; uint private amount;
mapping(address => Request) private requests; address[] requestInitiator; address[] ownersArray; mapping(string => Home) private homes; string[] addresses; mapping(string => Ownership[]) private ownerships; uint private amount;
16,340
16
// Send coins throws on any error rather then return a false flag to minimize user errors_to target address_amount transfer amount return true if the transfer was successful/
function transfer(address _to, uint _amount) public returns (bool) { require(!tokensAreFrozen); require(_to != address(0) && _to != address(this)); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(msg.sender, _to, _amount); return true; }
function transfer(address _to, uint _amount) public returns (bool) { require(!tokensAreFrozen); require(_to != address(0) && _to != address(this)); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(msg.sender, _to, _amount); return true; }
46,039
97
// withdraws all of your earnings.-functionhash- 0x3ccfd60b /
function withdraw() isActivated() isHuman() public
function withdraw() isActivated() isHuman() public
33,319
6
// Contract initialization logic solhint-disable-next-line func-name-mixedcase
function __ERC3525Upgradeable_init() public onlyInitializing { tokenCounter = 0; }
function __ERC3525Upgradeable_init() public onlyInitializing { tokenCounter = 0; }
37,327
151
// ------------------------------------------------------------------------ Transfer the balance from token owner's account to receiver account - Owner's account must have sufficient balance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------
function transfer(address receiver, uint tokens) public override returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[receiver] = safeAdd(balances[receiver], tokens); emit Transfer(msg.sender, receiver, tokens); return true; }
function transfer(address receiver, uint tokens) public override returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[receiver] = safeAdd(balances[receiver], tokens); emit Transfer(msg.sender, receiver, tokens); return true; }
13,002
50
// Internal Functions/
) internal nonReentrant { address _messageQueue = messageQueue; // gas saving address _counterpart = counterpart; // gas saving // compute the actual cross domain message calldata. uint256 _messageNonce = IL1MessageQueue(_messageQueue).nextCrossDomainMessageIndex(); bytes memory _xDomainCalldata = _encodeXDomainCalldata(_msgSender(), _to, _value, _messageNonce, _message); // compute and deduct the messaging fee to fee vault. uint256 _fee = IL1MessageQueue(_messageQueue).estimateCrossDomainMessageFee(_gasLimit); require(msg.value >= _fee + _value, "Insufficient msg.value"); if (_fee > 0) { (bool _success, ) = feeVault.call{value: _fee}(""); require(_success, "Failed to deduct the fee"); } // append message to L1MessageQueue IL1MessageQueue(_messageQueue).appendCrossDomainMessage(_counterpart, _gasLimit, _xDomainCalldata); // record the message hash for future use. bytes32 _xDomainCalldataHash = keccak256(_xDomainCalldata); // normally this won't happen, since each message has different nonce, but just in case. require(messageSendTimestamp[_xDomainCalldataHash] == 0, "Duplicated message"); messageSendTimestamp[_xDomainCalldataHash] = block.timestamp; emit SentMessage(_msgSender(), _to, _value, _messageNonce, _gasLimit, _message); // refund fee to `_refundAddress` unchecked { uint256 _refund = msg.value - _fee - _value; if (_refund > 0) { (bool _success, ) = _refundAddress.call{value: _refund}(""); require(_success, "Failed to refund the fee"); } } }
) internal nonReentrant { address _messageQueue = messageQueue; // gas saving address _counterpart = counterpart; // gas saving // compute the actual cross domain message calldata. uint256 _messageNonce = IL1MessageQueue(_messageQueue).nextCrossDomainMessageIndex(); bytes memory _xDomainCalldata = _encodeXDomainCalldata(_msgSender(), _to, _value, _messageNonce, _message); // compute and deduct the messaging fee to fee vault. uint256 _fee = IL1MessageQueue(_messageQueue).estimateCrossDomainMessageFee(_gasLimit); require(msg.value >= _fee + _value, "Insufficient msg.value"); if (_fee > 0) { (bool _success, ) = feeVault.call{value: _fee}(""); require(_success, "Failed to deduct the fee"); } // append message to L1MessageQueue IL1MessageQueue(_messageQueue).appendCrossDomainMessage(_counterpart, _gasLimit, _xDomainCalldata); // record the message hash for future use. bytes32 _xDomainCalldataHash = keccak256(_xDomainCalldata); // normally this won't happen, since each message has different nonce, but just in case. require(messageSendTimestamp[_xDomainCalldataHash] == 0, "Duplicated message"); messageSendTimestamp[_xDomainCalldataHash] = block.timestamp; emit SentMessage(_msgSender(), _to, _value, _messageNonce, _gasLimit, _message); // refund fee to `_refundAddress` unchecked { uint256 _refund = msg.value - _fee - _value; if (_refund > 0) { (bool _success, ) = _refundAddress.call{value: _refund}(""); require(_success, "Failed to refund the fee"); } } }
30,029
92
// returns the total supply at a certain block numberused by the voting strategy contracts to calculate the total votes needed for threshold/quorumIn this initial implementation with no AAVE minting, simply returns the current supplyA snapshots mapping will need to be added in case a mint function is added to the AAVE token in the future /
function totalSupplyAt(uint256 blockNumber) external view override returns (uint256) { return super.totalSupply(); }
function totalSupplyAt(uint256 blockNumber) external view override returns (uint256) { return super.totalSupply(); }
80,351
11
// Checks whether a pool is registered and active./poolId Id of the pool./ return Bool the pool is active.
function isActive(uint256 poolId) external view returns (bool);
function isActive(uint256 poolId) external view returns (bool);
42,104
32
// It's an open game anyone could have joined, or a reserved game that has not been joined yet.
if (game_.gameState == GameState.Canceled) {
if (game_.gameState == GameState.Canceled) {
17,263
175
// solhint-disable private-vars-leading-underscore, ordering /
interface IZora { /** * @title Interface for Decimal */ struct D256 { uint256 value; } /** * @title Interface for Zora Protocol's Media */ struct EIP712Signature { uint256 deadline; uint8 v; bytes32 r; bytes32 s; } struct MediaData { // A valid URI of the content represented by this token string tokenURI; // A valid URI of the metadata associated with this token string metadataURI; // A SHA256 hash of the content pointed to by tokenURI bytes32 contentHash; // A SHA256 hash of the content pointed to by metadataURI bytes32 metadataHash; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() external returns (uint256); /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) external returns (uint256); /** * @notice Mint new media for msg.sender. */ function mint(MediaData calldata data, BidShares calldata bidShares) external; /** * @notice EIP-712 mintWithSig method. Mints new media for a creator given a valid signature. */ function mintWithSig( address creator, MediaData calldata data, BidShares calldata bidShares, EIP712Signature calldata sig ) external; /** * @notice Update the token URI */ function updateTokenURI(uint256 tokenId, string calldata tokenURI) external; /** * @notice Update the token metadata uri */ function updateTokenMetadataURI( uint256 tokenId, string calldata metadataURI ) external; /** * @title Interface for Zora Protocol's Market */ struct Bid { // Amount of the currency being bid uint256 amount; // Address to the ERC20 token being used to bid address currency; // Address of the bidder address bidder; // Address of the recipient address recipient; // % of the next sale to award the current owner D256 sellOnShare; } struct Ask { // Amount of the currency being asked uint256 amount; // Address to the ERC20 token being asked address currency; } struct BidShares { // % of sale value that goes to the _previous_ owner of the nft D256 prevOwner; // % of sale value that goes to the original creator of the nft D256 creator; // % of sale value that goes to the seller (current owner) of the nft D256 owner; } function setBidShares(uint256 tokenId, BidShares calldata bidShares) external; function setAsk(uint256 tokenId, Ask calldata ask) external; function removeAsk(uint256 tokenId) external; function setBid( uint256 tokenId, Bid calldata bid, address spender ) external; function removeBid(uint256 tokenId, address bidder) external; function acceptBid(uint256 tokenId, Bid calldata expectedBid) external; /** * @title Interface for Auction House */ struct Auction { // ID for the ERC721 token uint256 tokenId; // Address for the ERC721 contract address tokenContract; // Whether or not the auction curator has approved the auction to start bool approved; // The current highest bid amount uint256 amount; // The length of time to run the auction for, after the first bid was made uint256 duration; // The time of the first bid uint256 firstBidTime; // The minimum price of the first bid uint256 reservePrice; // The sale percentage to send to the curator uint8 curatorFeePercentage; // The address that should receive the funds once the NFT is sold. address tokenOwner; // The address of the current highest bid address payable bidder; // The address of the auction's curator. // The curator can reject or approve an auction address payable curator; // The address of the ERC-20 currency to run the auction with. // If set to 0x0, the auction will be run in ETH address auctionCurrency; } function createAuction( uint256 tokenId, address tokenContract, uint256 duration, uint256 reservePrice, address payable curator, uint8 curatorFeePercentage, address auctionCurrency ) external returns (uint256); function setAuctionApproval(uint256 auctionId, bool approved) external; function setAuctionReservePrice(uint256 auctionId, uint256 reservePrice) external; function createBid(uint256 auctionId, uint256 amount) external payable; function endAuction(uint256 auctionId) external; function cancelAuction(uint256 auctionId) external; /** * @title Interface for NFT-Editions */ /// Creates a new edition contract as a factory with a deterministic address /// Important: None of these fields (except the Url fields with the same hash) can be changed after calling /// @param _name Name of the edition contract /// @param _symbol Symbol of the edition contract /// @param _description Metadata: Description of the edition entry /// @param _animationUrl Metadata: Animation url (optional) of the edition entry /// @param _animationHash Metadata: SHA-256 Hash of the animation (if no animation url, can be 0x0) /// @param _imageUrl Metadata: Image url (semi-required) of the edition entry /// @param _imageHash Metadata: SHA-256 hash of the Image of the edition entry (if not image, can be 0x0) /// @param _editionSize Total size of the edition (number of possible editions) /// @param _royaltyBPS BPS amount of royalty function createEdition( string memory _name, string memory _symbol, string memory _description, string memory _animationUrl, bytes32 _animationHash, string memory _imageUrl, bytes32 _imageHash, uint256 _editionSize, uint256 _royaltyBPS ) external returns (uint256); /** @param _salePrice if sale price is 0 sale is stopped, otherwise that amount of ETH is needed to start the sale. @dev This sets a simple ETH sales price Setting a sales price allows users to mint the edition until it sells out. For more granular sales, use an external sales contract. */ function setSalePrice(uint256 _salePrice) external; /** @dev This withdraws ETH from the contract to the contract owner. */ function withdraw() external; /** @param recipients list of addresses to send the newly minted editions to @dev This mints multiple editions to the given list of addresses. */ function mintEditions(address[] memory recipients) external returns (uint256); /** Get edition given the created ID @param editionId id of edition to get contract for @return address of SingleEditionMintable Edition NFT contract */ function getEditionAtId(uint256 editionId) external view returns (address); /** @param minter address to set approved minting status for @param allowed boolean if that address is allowed to mint @dev Sets the approved minting status of the given address. This requires that msg.sender is the owner of the given edition id. If the ZeroAddress (address(0x0)) is set as a minter, anyone will be allowed to mint. This setup is similar to setApprovalForAll in the ERC721 spec. */ function setApprovedMinter(address minter, bool allowed) external; /** @dev Allows for updates of edition urls by the owner of the edition. Only URLs can be updated (data-uris are supported), hashes cannot be updated. */ function updateEditionURLs( string memory _imageUrl, string memory _animationUrl ) external; }
interface IZora { /** * @title Interface for Decimal */ struct D256 { uint256 value; } /** * @title Interface for Zora Protocol's Media */ struct EIP712Signature { uint256 deadline; uint8 v; bytes32 r; bytes32 s; } struct MediaData { // A valid URI of the content represented by this token string tokenURI; // A valid URI of the metadata associated with this token string metadataURI; // A SHA256 hash of the content pointed to by tokenURI bytes32 contentHash; // A SHA256 hash of the content pointed to by metadataURI bytes32 metadataHash; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() external returns (uint256); /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) external returns (uint256); /** * @notice Mint new media for msg.sender. */ function mint(MediaData calldata data, BidShares calldata bidShares) external; /** * @notice EIP-712 mintWithSig method. Mints new media for a creator given a valid signature. */ function mintWithSig( address creator, MediaData calldata data, BidShares calldata bidShares, EIP712Signature calldata sig ) external; /** * @notice Update the token URI */ function updateTokenURI(uint256 tokenId, string calldata tokenURI) external; /** * @notice Update the token metadata uri */ function updateTokenMetadataURI( uint256 tokenId, string calldata metadataURI ) external; /** * @title Interface for Zora Protocol's Market */ struct Bid { // Amount of the currency being bid uint256 amount; // Address to the ERC20 token being used to bid address currency; // Address of the bidder address bidder; // Address of the recipient address recipient; // % of the next sale to award the current owner D256 sellOnShare; } struct Ask { // Amount of the currency being asked uint256 amount; // Address to the ERC20 token being asked address currency; } struct BidShares { // % of sale value that goes to the _previous_ owner of the nft D256 prevOwner; // % of sale value that goes to the original creator of the nft D256 creator; // % of sale value that goes to the seller (current owner) of the nft D256 owner; } function setBidShares(uint256 tokenId, BidShares calldata bidShares) external; function setAsk(uint256 tokenId, Ask calldata ask) external; function removeAsk(uint256 tokenId) external; function setBid( uint256 tokenId, Bid calldata bid, address spender ) external; function removeBid(uint256 tokenId, address bidder) external; function acceptBid(uint256 tokenId, Bid calldata expectedBid) external; /** * @title Interface for Auction House */ struct Auction { // ID for the ERC721 token uint256 tokenId; // Address for the ERC721 contract address tokenContract; // Whether or not the auction curator has approved the auction to start bool approved; // The current highest bid amount uint256 amount; // The length of time to run the auction for, after the first bid was made uint256 duration; // The time of the first bid uint256 firstBidTime; // The minimum price of the first bid uint256 reservePrice; // The sale percentage to send to the curator uint8 curatorFeePercentage; // The address that should receive the funds once the NFT is sold. address tokenOwner; // The address of the current highest bid address payable bidder; // The address of the auction's curator. // The curator can reject or approve an auction address payable curator; // The address of the ERC-20 currency to run the auction with. // If set to 0x0, the auction will be run in ETH address auctionCurrency; } function createAuction( uint256 tokenId, address tokenContract, uint256 duration, uint256 reservePrice, address payable curator, uint8 curatorFeePercentage, address auctionCurrency ) external returns (uint256); function setAuctionApproval(uint256 auctionId, bool approved) external; function setAuctionReservePrice(uint256 auctionId, uint256 reservePrice) external; function createBid(uint256 auctionId, uint256 amount) external payable; function endAuction(uint256 auctionId) external; function cancelAuction(uint256 auctionId) external; /** * @title Interface for NFT-Editions */ /// Creates a new edition contract as a factory with a deterministic address /// Important: None of these fields (except the Url fields with the same hash) can be changed after calling /// @param _name Name of the edition contract /// @param _symbol Symbol of the edition contract /// @param _description Metadata: Description of the edition entry /// @param _animationUrl Metadata: Animation url (optional) of the edition entry /// @param _animationHash Metadata: SHA-256 Hash of the animation (if no animation url, can be 0x0) /// @param _imageUrl Metadata: Image url (semi-required) of the edition entry /// @param _imageHash Metadata: SHA-256 hash of the Image of the edition entry (if not image, can be 0x0) /// @param _editionSize Total size of the edition (number of possible editions) /// @param _royaltyBPS BPS amount of royalty function createEdition( string memory _name, string memory _symbol, string memory _description, string memory _animationUrl, bytes32 _animationHash, string memory _imageUrl, bytes32 _imageHash, uint256 _editionSize, uint256 _royaltyBPS ) external returns (uint256); /** @param _salePrice if sale price is 0 sale is stopped, otherwise that amount of ETH is needed to start the sale. @dev This sets a simple ETH sales price Setting a sales price allows users to mint the edition until it sells out. For more granular sales, use an external sales contract. */ function setSalePrice(uint256 _salePrice) external; /** @dev This withdraws ETH from the contract to the contract owner. */ function withdraw() external; /** @param recipients list of addresses to send the newly minted editions to @dev This mints multiple editions to the given list of addresses. */ function mintEditions(address[] memory recipients) external returns (uint256); /** Get edition given the created ID @param editionId id of edition to get contract for @return address of SingleEditionMintable Edition NFT contract */ function getEditionAtId(uint256 editionId) external view returns (address); /** @param minter address to set approved minting status for @param allowed boolean if that address is allowed to mint @dev Sets the approved minting status of the given address. This requires that msg.sender is the owner of the given edition id. If the ZeroAddress (address(0x0)) is set as a minter, anyone will be allowed to mint. This setup is similar to setApprovalForAll in the ERC721 spec. */ function setApprovedMinter(address minter, bool allowed) external; /** @dev Allows for updates of edition urls by the owner of the edition. Only URLs can be updated (data-uris are supported), hashes cannot be updated. */ function updateEditionURLs( string memory _imageUrl, string memory _animationUrl ) external; }
24,632
3
// uniswap v3 router address
_swapRouter = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); _v3SwapRouter = IV3SwapRouter( 0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45 );
_swapRouter = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); _v3SwapRouter = IV3SwapRouter( 0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45 );
6,682
2
// Address of Curve Eth/StEth stableswap pool.
IStableSwapStEth immutable public stableswap;
IStableSwapStEth immutable public stableswap;
46,129
56
// Allows vault dao/factory to upgrade its address/_vaultDao Address of the new vault dao
function changeVaultDao(address _vaultDao) external onlyVaultDao
function changeVaultDao(address _vaultDao) external onlyVaultDao
48,641
207
// cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) { uint256 nav = 0; for (uint256 i = 0; i < lenders.length; i++) { nav += lenders[i].nav(); } return nav; }
function lentTotalAssets() public view returns (uint256) { uint256 nav = 0; for (uint256 i = 0; i < lenders.length; i++) { nav += lenders[i].nav(); } return nav; }
4,557
143
// This function is to get check whether the address is a minter. /
function isMinter(address addr) external view override returns (bool) { return _isMinter_[addr]; }
function isMinter(address addr) external view override returns (bool) { return _isMinter_[addr]; }
38,255
70
// update referrer's invitation info if he exists
if (refId_ != 0) { address refAddr = _userAddrBook[refId_.sub(1)];
if (refId_ != 0) { address refAddr = _userAddrBook[refId_.sub(1)];
27,151
56
// Updates a protocol adapter. protocolAdapterName Protocol adapter's protocolAdapterName. newProtocolAdapterAddress Protocol adapter's new address. newSupportedTokens Array of the protocol adapter's new supported tokens.Empty array is always allowed. /
function updateProtocolAdapter( bytes32 protocolAdapterName, address newProtocolAdapterAddress, address[] calldata newSupportedTokens )
function updateProtocolAdapter( bytes32 protocolAdapterName, address newProtocolAdapterAddress, address[] calldata newSupportedTokens )
5,411
37
// add this file to the file hash dict and the patient's file list
fileHashDict[file_hash] = file({file_name:_file_name, record_type:_file_type, uploader_address:msg.sender, uploader_name:d.name, contents:_contents, date_uploaded:_date_uploaded});
fileHashDict[file_hash] = file({file_name:_file_name, record_type:_file_type, uploader_address:msg.sender, uploader_name:d.name, contents:_contents, date_uploaded:_date_uploaded});
34,872
16
// update last selector slot position info
l.facets[lastSelector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(l.facets[lastSelector]);
l.facets[lastSelector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(l.facets[lastSelector]);
35,808
16
// 70000000000000000 = .07 eth
NFT_PRICE = price;
NFT_PRICE = price;
28,441
66
// calculate the total dividend accrued since last dividend checkpoint to now this contains a unbounded loop, use calculateAccruedDividendBounded for determimistic gas cost tokenAmount amount of token being held timestamp timestamp to start calculating dividend accrued fromIndex index in the dividend history that the timestamp falls intoreturn amount of dividend accrued in 1e18, and the latest dividend index /
function calculateAccruedDividends( uint256 tokenAmount, uint256 timestamp, uint256 fromIndex
function calculateAccruedDividends( uint256 tokenAmount, uint256 timestamp, uint256 fromIndex
12,871
4
// Returns the rebuilt hash obtained by traversing a Merkle tree upfrom `leaf` using `proof`. A `proof` is valid if and only if the rebuilthash matches the root of the tree. When processing the proof, the pairsof leafs & pre-images are assumed to be sorted. _Available since v4.4._ /
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; }
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; }
754
107
// EVENTS // FUNCTIONS //takes funds from _confiscatee and sends them to _receiver_confiscatee address who's funds are being confiscated_receiver address who's receiving the funds /
function forceTransfer(address _confiscatee, address _receiver) public onlyOwner { uint256 balance = balanceOf(_confiscatee); _transfer(_confiscatee, _receiver, balance); emit ForcedTransfer(_confiscatee, balance, _receiver); }
function forceTransfer(address _confiscatee, address _receiver) public onlyOwner { uint256 balance = balanceOf(_confiscatee); _transfer(_confiscatee, _receiver, balance); emit ForcedTransfer(_confiscatee, balance, _receiver); }
26,264
57
// Implementation of the {IERC20} interface.that a supply mechanism has to be added in a derived contract using {_mint}.For a generic mechanism see {ERC20PresetMinterPauser}.Additionally, an {Approval} event is emitted on calls to {transferFrom}.Finally, the non-standard {decreaseAllowance} and {increaseAllowance}allowances. See {IERC20-approve}./ Sets the values for {name} and {symbol}, initializes {decimals} witha default value of 18. All three of these values are immutable: they can only be set once duringconstruction. /
constructor(address banker) public { _name = "Keep Pro"; _symbol = "KPP"; _decimals = 18; _setOwner(banker); _mint(banker, 50000 * (10**uint256(_decimals))); _mint(address(this), 40000 * (10**uint256(_decimals))); }
constructor(address banker) public { _name = "Keep Pro"; _symbol = "KPP"; _decimals = 18; _setOwner(banker); _mint(banker, 50000 * (10**uint256(_decimals))); _mint(address(this), 40000 * (10**uint256(_decimals))); }
41,757
302
// only a minter can call this/ @inheritdocIMintingStation
function mint( string memory tokenURI_, address royaltiesRecipient, uint256 royaltiesAmount
function mint( string memory tokenURI_, address royaltiesRecipient, uint256 royaltiesAmount
38,566
30
// Далее идут продукционные правила верхнего уровня - они срабатывают на определенныепаттерны в исходном предложении и порождают новое содержимое.
16,662
1
// if there is a borrow, there can't be 0 collateral
if (vars.collateralBalanceAfterDecrease == 0) { return false; }
if (vars.collateralBalanceAfterDecrease == 0) { return false; }
5,360
27
// Swap fees are typically charged on 'token in', but there is no 'token in' here, o we apply it to 'token out'. This results in slightly larger price impact.
uint256 amountOutWithFee; if (invariantRatioWithoutFees > balanceRatiosWithoutFee[i]) { uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithoutFees.complement()); uint256 taxableAmount = amountsOut[i].sub(nonTaxableAmount); amountOutWithFee = nonTaxableAmount.add(taxableAmount.divUp(swapFee.complement())); } else {
uint256 amountOutWithFee; if (invariantRatioWithoutFees > balanceRatiosWithoutFee[i]) { uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithoutFees.complement()); uint256 taxableAmount = amountsOut[i].sub(nonTaxableAmount); amountOutWithFee = nonTaxableAmount.add(taxableAmount.divUp(swapFee.complement())); } else {
8,634
28
// Give random tokens to the provided address /
function devMintTokensToAddress(address _address, uint16 amount) external onlyOwner
function devMintTokensToAddress(address _address, uint16 amount) external onlyOwner
28,625
24
// Directly remove an item from the list bypassing request-challenge. Can only be used by the relay contract. _itemID The ID of the item to remove. /
function removeItemDirectly(bytes32 _itemID) external onlyRelayer { Item storage item = items[_itemID]; require(item.status == Status.Registered, "Item must be registered to be removed."); item.status = Status.Absent; emit ItemStatusChange(_itemID, true); }
function removeItemDirectly(bytes32 _itemID) external onlyRelayer { Item storage item = items[_itemID]; require(item.status == Status.Registered, "Item must be registered to be removed."); item.status = Status.Absent; emit ItemStatusChange(_itemID, true); }
12,090
24
// To redeem the due interests. This function can always be called regardless of whether the XYT has expired or not only be called by Router/
function redeemDueInterests( address _user, address _underlyingAsset, uint256 _expiry
function redeemDueInterests( address _user, address _underlyingAsset, uint256 _expiry
4,428
44
// @des Determines if an address is a pre-TDE contributor
function isAwaitingPRETDETokens(address _contributorAddress) internal returns (bool)
function isAwaitingPRETDETokens(address _contributorAddress) internal returns (bool)
45,986
21
// Store the redeemer in case there's an issue with redemption and coins need to be recovered
redeemers[_depositToRedeem] = msg.sender;
redeemers[_depositToRedeem] = msg.sender;
14,436
155
// Implements Boost and Repay for MCD CDPs
contract MCDSaverProxy is SaverExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Manager public constant manager = Manager(MANAGER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount); (, uint daiAmount) = _sell(_exchangeData); uint daiAfterFee = sub(daiAmount, getFee(daiAmount, _gasCost, owner)); paybackDebt(_cdpId, ilk, daiAfterFee, owner); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, owner, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount); uint daiAfterFee = sub(daiDrawn, getFee(daiDrawn, _gasCost, owner)); _exchangeData.srcAmount = daiAfterFee; (, uint swapedColl) = _sell(_exchangeData); addCollateral(_cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, owner, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(manager.urns(_cdpId)); uint maxAmount = getMaxDebt(_cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); manager.move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, 0); ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( manager.ilks(_cdpId), manager.urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } manager.frob(_cdpId, -toPositiveInt(frobAmount), 0); manager.flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = manager.urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Calculates the fee amount /// @param _amount Dai amount that is converted /// @param _gasCost Used for Monitor, estimated gas cost of tx /// @param _owner The address that controlls the DSProxy that owns the CDP function getFee(uint _amount, uint _gasCost, address _owner) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint ethDaiPrice = getPrice(ETH_ILK); _gasCost = rmul(_gasCost, ethDaiPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } /// @notice Gets the maximum amount of collateral available to draw /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(sub(collateral, (div(mul(mat, debt), price))), 10); uint normalizeMaxCollateral = maxCollateral; if (Join(_joinAddr).dec() != 18) { normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); } return normalizeMaxCollateral; } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) { address urn = manager.urns(_cdpId); ilk = manager.ilks(_cdpId); (collateral, debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); price = getPrice(ilk); } } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external virtual view returns(address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external virtual view returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external virtual view returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external virtual view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public virtual view returns (address); function getReserveConfiguration(address _reserve) external virtual view returns (uint256, uint256, uint256, bool); function getUserUnderlyingAssetBalance(address _reserve, address _user) public virtual view returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveTotalLiquidity(address _reserve) public virtual view returns (uint256); function getReserveAvailableLiquidity(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public virtual view returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); }
contract MCDSaverProxy is SaverExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Manager public constant manager = Manager(MANAGER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount); (, uint daiAmount) = _sell(_exchangeData); uint daiAfterFee = sub(daiAmount, getFee(daiAmount, _gasCost, owner)); paybackDebt(_cdpId, ilk, daiAfterFee, owner); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, owner, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount); uint daiAfterFee = sub(daiDrawn, getFee(daiDrawn, _gasCost, owner)); _exchangeData.srcAmount = daiAfterFee; (, uint swapedColl) = _sell(_exchangeData); addCollateral(_cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, owner, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(manager.urns(_cdpId)); uint maxAmount = getMaxDebt(_cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); manager.move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, 0); ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( manager.ilks(_cdpId), manager.urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } manager.frob(_cdpId, -toPositiveInt(frobAmount), 0); manager.flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = manager.urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Calculates the fee amount /// @param _amount Dai amount that is converted /// @param _gasCost Used for Monitor, estimated gas cost of tx /// @param _owner The address that controlls the DSProxy that owns the CDP function getFee(uint _amount, uint _gasCost, address _owner) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint ethDaiPrice = getPrice(ETH_ILK); _gasCost = rmul(_gasCost, ethDaiPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } /// @notice Gets the maximum amount of collateral available to draw /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(sub(collateral, (div(mul(mat, debt), price))), 10); uint normalizeMaxCollateral = maxCollateral; if (Join(_joinAddr).dec() != 18) { normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); } return normalizeMaxCollateral; } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) { address urn = manager.urns(_cdpId); ilk = manager.ilks(_cdpId); (collateral, debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); price = getPrice(ilk); } } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external virtual view returns(address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external virtual view returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external virtual view returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external virtual view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public virtual view returns (address); function getReserveConfiguration(address _reserve) external virtual view returns (uint256, uint256, uint256, bool); function getUserUnderlyingAssetBalance(address _reserve, address _user) public virtual view returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveTotalLiquidity(address _reserve) public virtual view returns (uint256); function getReserveAvailableLiquidity(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public virtual view returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); }
27,488
78
// Returns the current block number, converted to uint64.Using a function rather than `block.number` allows us to easily mock the block number intests./
function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); }
function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); }
5,567
14
// set First Block
firstBlock = block.number;
firstBlock = block.number;
9,920
250
// memory[ptr:ptr+0x80] = (hash, v, r, s)
switch signature.length case 65 {
switch signature.length case 65 {
15,176