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
2
// initate asset of client's accont
function InitAccount (address newaccount) public returns(bool)
function InitAccount (address newaccount) public returns(bool)
1,162
7
// Tier mapping for the token
mapping(uint256 => uint8) public tokenTier;
mapping(uint256 => uint8) public tokenTier;
73,862
169
// we just keep all money in want if we dont have any lenders
if(lenders.length == 0){ return; }
if(lenders.length == 0){ return; }
11,526
579
// Allows the owner to update the protocolFeeCollector address./updatedProtocolFeeCollector The updated protocolFeeCollector contract address.
function setProtocolFeeCollectorAddress(address updatedProtocolFeeCollector) external;
function setProtocolFeeCollectorAddress(address updatedProtocolFeeCollector) external;
54,976
79
// Allow the owner to transfer out any accidentally sent ERC20 tokens. _tokenAddress The address of the ERC20 contract. _amount The amount of tokens to be transferred. /
function transferAnyERC20Token(address _tokenAddress, uint256 _amount)onlyOwner public returns(bool success) { return ERC20(_tokenAddress).transfer(owner, _amount); }
function transferAnyERC20Token(address _tokenAddress, uint256 _amount)onlyOwner public returns(bool success) { return ERC20(_tokenAddress).transfer(owner, _amount); }
28,184
64
// Calculates partial value given a numerator and denominator./numerator Numerator./denominator Denominator./target Value to calculate partial of./ return Partial value of target.
function getPartialAmount(uint numerator, uint denominator, uint target) public constant returns (uint)
function getPartialAmount(uint numerator, uint denominator, uint target) public constant returns (uint)
16,267
169
// Mint ERC1155 token for the specified amount/amount Token amount to wrap
function mint(uint amount) external nonReentrant returns (uint) { IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount); IStakingRewards(staking).stake(amount); uint rewardPerToken = IStakingRewards(staking).rewardPerToken(); _mint(msg.sender, rewardPerToken, amount, ''); return rewardPerToken; }
function mint(uint amount) external nonReentrant returns (uint) { IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount); IStakingRewards(staking).stake(amount); uint rewardPerToken = IStakingRewards(staking).rewardPerToken(); _mint(msg.sender, rewardPerToken, amount, ''); return rewardPerToken; }
10,993
221
// check if token id is tradeabletokenId token id/
function isTokenTradeable(uint256 tokenId) public view returns (bool) { if(!exists(tokenId)) revert TokenDoesNotExist(); return tokenTradingStatus[tokenId] == 255; }
function isTokenTradeable(uint256 tokenId) public view returns (bool) { if(!exists(tokenId)) revert TokenDoesNotExist(); return tokenTradingStatus[tokenId] == 255; }
1,529
45
// Perform an internal option purchase/caller Address purchasing the option/currencies List of usable currencies/amounts List of usable currencies amounts/data Extra data usable by adapter/ return A tuple containing used amounts and output data
function purchase( address caller, address[] memory currencies, uint256[] memory amounts, bytes calldata data ) internal virtual returns (uint256[] memory, bytes memory);
function purchase( address caller, address[] memory currencies, uint256[] memory amounts, bytes calldata data ) internal virtual returns (uint256[] memory, bytes memory);
50,751
8
// Changes the address of the the related UBI contract._UBI The address of the new contract. /
function changeUBI(IERC20 _UBI) external { require(msg.sender == governor, "The caller must be the governor."); UBI = _UBI; }
function changeUBI(IERC20 _UBI) external { require(msg.sender == governor, "The caller must be the governor."); UBI = _UBI; }
38,135
42
// Stores a new beacon in the EIP1967 beacon slot. /
function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; }
function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; }
9,966
14
// Sets the expected loan amount. _NFTid The Id of the NFTDetail _expectedAmount The expected amount. /
function setExpectedAmount(uint256 _NFTid, uint256 _expectedAmount) public NFTOwner(_NFTid)
function setExpectedAmount(uint256 _NFTid, uint256 _expectedAmount) public NFTOwner(_NFTid)
2,398
306
// remove the position from the provider
_store.removeProtectedLiquidity(id);
_store.removeProtectedLiquidity(id);
38,755
40
// emit Transfer(to, reserve, reserve_amount);
reward(reserve_amount, point, to); return true;
reward(reserve_amount, point, to); return true;
10,393
11
// Recovers USDC accidentally sent to the contract /
function recoverUsdc() external { uint256 usdcBalance = IERC20(usdc).balanceOf(address(this)); IERC20(usdc).safeTransfer(beneficiary, usdcBalance); }
function recoverUsdc() external { uint256 usdcBalance = IERC20(usdc).balanceOf(address(this)); IERC20(usdc).safeTransfer(beneficiary, usdcBalance); }
10,661
26
// This function allows user to approve and at the same time call any other smart contract function and do any code execution. /
function approveAndCall(address spender, uint256 tokens, bytes calldata data) external returns (bool) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; }
function approveAndCall(address spender, uint256 tokens, bytes calldata data) external returns (bool) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; }
14,204
12
// assinging to map Object idToItem at the index [newTokenId] an object of type NFTItem
idToItem[newTokenId] = NFTItem( newTokenId, payable(msg.sender), payable(address(this)) );
idToItem[newTokenId] = NFTItem( newTokenId, payable(msg.sender), payable(address(this)) );
15,946
1
// Airdrop function
function airdrop(address[] memory recipients, uint256 amount) external { require(recipients.length > 0, "No recipients specified"); require(amount > 0, "Invalid amount"); uint256 totalAmount = amount * recipients.length; require(totalAmount <= balanceOf(msg.sender), "Insufficient balance"); for (uint256 i = 0; i < recipients.length; i++) { address recipient = recipients[i]; _transfer(msg.sender, recipient, amount); } }
function airdrop(address[] memory recipients, uint256 amount) external { require(recipients.length > 0, "No recipients specified"); require(amount > 0, "Invalid amount"); uint256 totalAmount = amount * recipients.length; require(totalAmount <= balanceOf(msg.sender), "Insufficient balance"); for (uint256 i = 0; i < recipients.length; i++) { address recipient = recipients[i]; _transfer(msg.sender, recipient, amount); } }
41,927
79
// vault (Brahma Vault)/0xAd1 and Bapireddy/Minimal vault contract to support trades across different protocols.
contract Vault is IVault, ERC20Permit, ReentrancyGuard { using AddrArrayLib for AddrArrayLib.Addresses; using SafeERC20 for IERC20; /*/////////////////////////////////////////////////////////////// CONSTANTS //////////////////////////////////////////////////////////////*/ /// @notice The maximum number of blocks for latest update to be valid. /// @dev Needed for processing deposits/withdrawals. uint256 constant BLOCK_LIMIT = 50; /// @dev minimum balance used to check when executor is removed. uint256 constant DUST_LIMIT = 10**6; /// @dev The max basis points used as normalizing factor. uint256 constant MAX_BPS = 10000; /// @dev The max amount of seconds in year. /// accounting for leap years there are 365.25 days in year. /// 365.25 * 86400 = 31557600.0 uint256 constant MAX_SECONDS = 31557600; /*/////////////////////////////////////////////////////////////// IMMUTABLES //////////////////////////////////////////////////////////////*/ /// @notice The underlying token the vault accepts. address public immutable override wantToken; uint8 private immutable tokenDecimals; /*/////////////////////////////////////////////////////////////// MUTABLE ACCESS MODFIERS //////////////////////////////////////////////////////////////*/ /// @notice boolean for enabling deposit/withdraw solely via batcher. bool public batcherOnlyDeposit; /// @notice boolean for enabling emergency mode to halt new withdrawal/deposits into vault. bool public emergencyMode; // @notice address of batcher used for batching user deposits/withdrawals. address public batcher; /// @notice keeper address to move funds between executors. address public override keeper; /// @notice Governance address to add/remove executors. address public override governance; address public pendingGovernance; /// @notice Creates a new Vault that accepts a specific underlying token. /// @param _wantToken The ERC20 compliant token the vault should accept. /// @param _name The name of the vault token. /// @param _symbol The symbol of the vault token. /// @param _keeper The address of the keeper to move funds between executors. /// @param _governance The address of the governance to perform governance functions. constructor( string memory _name, string memory _symbol, address _wantToken, address _keeper, address _governance ) ERC20(_name, _symbol) ERC20Permit(_name) { tokenDecimals = IERC20Metadata(_wantToken).decimals(); wantToken = _wantToken; keeper = _keeper; governance = _governance; // to prevent any front running deposits batcherOnlyDeposit = true; } function decimals() public view override returns (uint8) { return tokenDecimals; } /*/////////////////////////////////////////////////////////////// USER DEPOSIT/WITHDRAWAL LOGIC //////////////////////////////////////////////////////////////*/ /// @notice Initiates a deposit of want tokens to the vault. /// @param amountIn The amount of want tokens to deposit. /// @param receiver The address to receive vault tokens. function deposit(uint256 amountIn, address receiver) public override nonReentrant ensureFeesAreCollected returns (uint256 shares) { /// checks for only batcher deposit onlyBatcher(); isValidAddress(receiver); require(amountIn > 0, "ZERO_AMOUNT"); // calculate the shares based on the amount. shares = totalSupply() > 0 ? (totalSupply() * amountIn) / totalVaultFunds() : amountIn; require(shares != 0, "ZERO_SHARES"); IERC20(wantToken).safeTransferFrom(msg.sender, address(this), amountIn); _mint(receiver, shares); } /// @notice Initiates a withdrawal of vault tokens to the user. /// @param sharesIn The amount of vault tokens to withdraw. /// @param receiver The address to receive the vault tokens. function withdraw(uint256 sharesIn, address receiver) public override nonReentrant ensureFeesAreCollected returns (uint256 amountOut) { /// checks for only batcher withdrawal onlyBatcher(); isValidAddress(receiver); require(sharesIn > 0, "ZERO_SHARES"); // calculate the amount based on the shares. amountOut = (sharesIn * totalVaultFunds()) / totalSupply(); // burn shares of msg.sender _burn(msg.sender, sharesIn); /// charging exitFee if (exitFee > 0) { uint256 fee = (amountOut * exitFee) / MAX_BPS; IERC20(wantToken).transfer(governance, fee); amountOut = amountOut - fee; } IERC20(wantToken).safeTransfer(receiver, amountOut); } /// @notice Calculates the total amount of underlying tokens the vault holds. /// @return The total amount of underlying tokens the vault holds. function totalVaultFunds() public view returns (uint256) { return IERC20(wantToken).balanceOf(address(this)) + totalExecutorFunds(); } /*/////////////////////////////////////////////////////////////// EXECUTOR DEPOSIT/WITHDRAWAL LOGIC //////////////////////////////////////////////////////////////*/ /// @notice list of trade executors connected to vault. AddrArrayLib.Addresses tradeExecutorsList; /// @notice Emitted after the vault deposits into a executor contract. /// @param executor The executor that was deposited into. /// @param underlyingAmount The amount of underlying tokens that were deposited. event ExecutorDeposit(address indexed executor, uint256 underlyingAmount); /// @notice Emitted after the vault withdraws funds from a executor contract. /// @param executor The executor that was withdrawn from. /// @param underlyingAmount The amount of underlying tokens that were withdrawn. event ExecutorWithdrawal( address indexed executor, uint256 underlyingAmount ); /// @notice Deposit given amount of want tokens into valid executor. /// @param _executor The executor to deposit into. /// @param _amount The amount of want tokens to deposit. function depositIntoExecutor(address _executor, uint256 _amount) public nonReentrant { isActiveExecutor(_executor); onlyKeeper(); require(_amount > 0, "ZERO_AMOUNT"); IERC20(wantToken).safeTransfer(_executor, _amount); emit ExecutorDeposit(_executor, _amount); } /// @notice Withdraw given amount of want tokens into valid executor. /// @param _executor The executor to withdraw tokens from. /// @param _amount The amount of want tokens to withdraw. function withdrawFromExecutor(address _executor, uint256 _amount) public nonReentrant { isActiveExecutor(_executor); onlyKeeper(); require(_amount > 0, "ZERO_AMOUNT"); IERC20(wantToken).safeTransferFrom(_executor, address(this), _amount); emit ExecutorWithdrawal(_executor, _amount); } /*/////////////////////////////////////////////////////////////// FEE CONFIGURATION //////////////////////////////////////////////////////////////*/ /// @notice lagging value of vault total funds. /// @dev value intialized to max to prevent slashing on first deposit. uint256 public prevVaultFunds = type(uint256).max; /// @dev value intialized to max to prevent slashing on first deposit. uint256 public lastReportedTime = type(uint256).max; /// @dev Perfomance fee for the vault. uint256 public performanceFee; /// @notice Fee denominated in MAX_BPS charged during exit. uint256 public exitFee; /// @notice Mangement fee for operating the vault. uint256 public managementFee; /// @notice Emitted after perfomance fee updation. /// @param oldFee The old performance fee on vault. /// @param newFee The new performance fee on vault. event UpdatePerformanceFee(uint256 oldFee, uint256 newFee); /// @notice Updates the performance fee on the vault. /// @param _fee The new performance fee on the vault. /// @dev The new fee must be always less than 50% of yield. function setPerformanceFee(uint256 _fee) public { onlyGovernance(); require(_fee < MAX_BPS / 2, "FEE_TOO_HIGH"); emit UpdatePerformanceFee(performanceFee, _fee); performanceFee = _fee; } /// @notice Emitted after exit fee updation. /// @param oldFee The old exit fee on vault. /// @param newFee The new exit fee on vault. event UpdateExitFee(uint256 oldFee, uint256 newFee); /// @notice Function to set exit fee on the vault, can only be called by governance /// @param _fee Address of fee function setExitFee(uint256 _fee) public { onlyGovernance(); require(_fee < MAX_BPS / 2, "EXIT_FEE_TOO_HIGH"); emit UpdateExitFee(exitFee, _fee); exitFee = _fee; } /// @notice Emitted after management fee updation. /// @param oldFee The old management fee on vault. /// @param newFee The new management fee on vault. event UpdateManagementFee(uint256 oldFee, uint256 newFee); /// @notice Function to set exit fee on the vault, can only be called by governance /// @param _fee Address of fee function setManagementFee(uint256 _fee) public { onlyGovernance(); require(_fee < MAX_BPS / 2, "EXIT_FEE_TOO_HIGH"); emit UpdateManagementFee(managementFee, _fee); managementFee = _fee; } /// @notice Emitted when a fees are collected. /// @param collectedFees The amount of fees collected. event FeesCollected(uint256 collectedFees); /// @notice Calculates and collects the fees from the vault. /// @dev This function sends all the accured fees to governance. /// checks the yield made since previous harvest and /// calculates the fee based on it. Also note: this function /// should be called before processing any new deposits/withdrawals. function collectFees() internal { uint256 currentFunds = totalVaultFunds(); uint256 fees = 0; // collect fees only when profit is made. if ((performanceFee > 0) && (currentFunds > prevVaultFunds)) { uint256 yieldEarned = (currentFunds - prevVaultFunds); // normalization by MAX_BPS fees += ((yieldEarned * performanceFee) / MAX_BPS); } if ((managementFee > 0) && (lastReportedTime < block.timestamp)) { uint256 duration = block.timestamp - lastReportedTime; fees += ((duration * managementFee * currentFunds) / MAX_SECONDS) / MAX_BPS; } if (fees > 0) { IERC20(wantToken).safeTransfer(governance, fees); emit FeesCollected(fees); } } modifier ensureFeesAreCollected() { collectFees(); _; // update vault funds after fees are collected. prevVaultFunds = totalVaultFunds(); // update lastReportedTime after fees are collected. lastReportedTime = block.timestamp; } /*/////////////////////////////////////////////////////////////// EXECUTOR ADDITION/REMOVAL LOGIC //////////////////////////////////////////////////////////////*/ /// @notice Emitted when executor is added to vault. /// @param executor The address of added executor. event ExecutorAdded(address indexed executor); /// @notice Emitted when executor is removed from vault. /// @param executor The address of removed executor. event ExecutorRemoved(address indexed executor); /// @notice Adds a trade executor, enabling it to execute trades. /// @param _tradeExecutor The address of _tradeExecutor contract. function addExecutor(address _tradeExecutor) public { onlyGovernance(); isValidAddress(_tradeExecutor); require( ITradeExecutor(_tradeExecutor).vault() == address(this), "INVALID_VAULT" ); require( IERC20(wantToken).allowance(_tradeExecutor, address(this)) > 0, "NO_ALLOWANCE" ); tradeExecutorsList.pushAddress(_tradeExecutor); emit ExecutorAdded(_tradeExecutor); } /// @notice Adds a trade executor, enabling it to execute trades. /// @param _tradeExecutor The address of _tradeExecutor contract. /// @dev make sure all funds are withdrawn from executor before removing. function removeExecutor(address _tradeExecutor) public { onlyGovernance(); isValidAddress(_tradeExecutor); // check if executor attached to vault. isActiveExecutor(_tradeExecutor); (uint256 executorFunds, uint256 blockUpdated) = ITradeExecutor( _tradeExecutor ).totalFunds(); areFundsUpdated(blockUpdated); require(executorFunds < DUST_LIMIT, "FUNDS_TOO_HIGH"); tradeExecutorsList.removeAddress(_tradeExecutor); emit ExecutorRemoved(_tradeExecutor); } /// @notice gives the number of trade executors. /// @return The number of trade executors. function totalExecutors() public view returns (uint256) { return tradeExecutorsList.size(); } /// @notice Returns trade executor at given index. /// @return The executor address at given valid index. function executorByIndex(uint256 _index) public view returns (address) { return tradeExecutorsList.getAddressAtIndex(_index); } /// @notice Calculates funds held by all executors in want token. /// @return Sum of all funds held by executors. function totalExecutorFunds() public view returns (uint256) { uint256 totalFunds = 0; for (uint256 i = 0; i < totalExecutors(); i++) { address executor = executorByIndex(i); (uint256 executorFunds, uint256 blockUpdated) = ITradeExecutor( executor ).totalFunds(); areFundsUpdated(blockUpdated); totalFunds += executorFunds; } return totalFunds; } /*/////////////////////////////////////////////////////////////// GOVERNANCE ACTIONS //////////////////////////////////////////////////////////////*/ /// @notice Emitted when a batcher is updated. /// @param oldBatcher The address of the current batcher. /// @param newBatcher The address of new batcher. event UpdatedBatcher( address indexed oldBatcher, address indexed newBatcher ); /// @notice Changes the batcher address. /// @dev This can only be called by governance. /// @param _batcher The address to for new batcher. function setBatcher(address _batcher) public { onlyGovernance(); emit UpdatedBatcher(batcher, _batcher); batcher = _batcher; } /// @notice Emitted batcherOnlyDeposit is enabled. /// @param state The state of depositing only via batcher. event UpdatedBatcherOnlyDeposit(bool state); /// @notice Enables/disables deposits with batcher only. /// @dev This can only be called by governance. /// @param _batcherOnlyDeposit if true vault can accept deposit via batcher only or else anyone can deposit. function setBatcherOnlyDeposit(bool _batcherOnlyDeposit) public { onlyGovernance(); batcherOnlyDeposit = _batcherOnlyDeposit; emit UpdatedBatcherOnlyDeposit(_batcherOnlyDeposit); } /// @notice Nominates new governance address. /// @dev Governance will only be changed if the new governance accepts it. It will be pending till then. /// @param _governance The address of new governance. function setGovernance(address _governance) public { onlyGovernance(); pendingGovernance = _governance; } /// @notice Emitted when governance is updated. /// @param oldGovernance The address of the current governance. /// @param newGovernance The address of new governance. event UpdatedGovernance( address indexed oldGovernance, address indexed newGovernance ); /// @notice The nomine of new governance address proposed by `setGovernance` function can accept the governance. /// @dev This can only be called by address of pendingGovernance. function acceptGovernance() public { require(msg.sender == pendingGovernance, "INVALID_ADDRESS"); emit UpdatedGovernance(governance, pendingGovernance); governance = pendingGovernance; } /// @notice Emitted when keeper is updated. /// @param oldKeeper The address of the old keeper. /// @param newKeeper The address of the new keeper. event UpdatedKeeper(address indexed oldKeeper, address indexed newKeeper); /// @notice Sets new keeper address. /// @dev This can only be called by governance. /// @param _keeper The address of new keeper. function setKeeper(address _keeper) public { onlyGovernance(); emit UpdatedKeeper(keeper, _keeper); keeper = _keeper; } /// @notice Emitted when emergencyMode status is updated. /// @param emergencyMode boolean indicating state of emergency. event EmergencyModeStatus(bool emergencyMode); /// @notice sets emergencyMode. /// @dev This can only be called by governance. /// @param _emergencyMode if true, vault will be in emergency mode. function setEmergencyMode(bool _emergencyMode) public { onlyGovernance(); emergencyMode = _emergencyMode; batcherOnlyDeposit = true; batcher = address(0); emit EmergencyModeStatus(_emergencyMode); } /// @notice Removes invalid tokens from the vault. /// @dev This is used as fail safe to remove want tokens from the vault during emergency mode /// can be called by anyone to send funds to governance. /// @param _token The address of token to be removed. function sweep(address _token) public { isEmergencyMode(); IERC20(_token).safeTransfer( governance, IERC20(_token).balanceOf(address(this)) ); } /*/////////////////////////////////////////////////////////////// ACCESS MODIFERS //////////////////////////////////////////////////////////////*/ /// @dev Checks if the sender is the governance. function onlyGovernance() internal view { require(msg.sender == governance, "ONLY_GOV"); } /// @dev Checks if the sender is the keeper. function onlyKeeper() internal view { require(msg.sender == keeper, "ONLY_KEEPER"); } /// @dev Checks if the sender is the batcher. function onlyBatcher() internal view { if (batcherOnlyDeposit) { require(msg.sender == batcher, "ONLY_BATCHER"); } } /// @dev Checks if emergency mode is enabled. function isEmergencyMode() internal view { require(emergencyMode == true, "EMERGENCY_MODE"); } /// @dev Checks if the address is valid. function isValidAddress(address _addr) internal pure { require(_addr != address(0), "NULL_ADDRESS"); } /// @dev Checks if the tradeExecutor is valid. function isActiveExecutor(address _tradeExecutor) internal view { require(tradeExecutorsList.exists(_tradeExecutor), "INVALID_EXECUTOR"); } /// @dev Checks if funds are updated. function areFundsUpdated(uint256 _blockUpdated) internal view { require( block.number <= _blockUpdated + BLOCK_LIMIT, "FUNDS_NOT_UPDATED" ); } }
contract Vault is IVault, ERC20Permit, ReentrancyGuard { using AddrArrayLib for AddrArrayLib.Addresses; using SafeERC20 for IERC20; /*/////////////////////////////////////////////////////////////// CONSTANTS //////////////////////////////////////////////////////////////*/ /// @notice The maximum number of blocks for latest update to be valid. /// @dev Needed for processing deposits/withdrawals. uint256 constant BLOCK_LIMIT = 50; /// @dev minimum balance used to check when executor is removed. uint256 constant DUST_LIMIT = 10**6; /// @dev The max basis points used as normalizing factor. uint256 constant MAX_BPS = 10000; /// @dev The max amount of seconds in year. /// accounting for leap years there are 365.25 days in year. /// 365.25 * 86400 = 31557600.0 uint256 constant MAX_SECONDS = 31557600; /*/////////////////////////////////////////////////////////////// IMMUTABLES //////////////////////////////////////////////////////////////*/ /// @notice The underlying token the vault accepts. address public immutable override wantToken; uint8 private immutable tokenDecimals; /*/////////////////////////////////////////////////////////////// MUTABLE ACCESS MODFIERS //////////////////////////////////////////////////////////////*/ /// @notice boolean for enabling deposit/withdraw solely via batcher. bool public batcherOnlyDeposit; /// @notice boolean for enabling emergency mode to halt new withdrawal/deposits into vault. bool public emergencyMode; // @notice address of batcher used for batching user deposits/withdrawals. address public batcher; /// @notice keeper address to move funds between executors. address public override keeper; /// @notice Governance address to add/remove executors. address public override governance; address public pendingGovernance; /// @notice Creates a new Vault that accepts a specific underlying token. /// @param _wantToken The ERC20 compliant token the vault should accept. /// @param _name The name of the vault token. /// @param _symbol The symbol of the vault token. /// @param _keeper The address of the keeper to move funds between executors. /// @param _governance The address of the governance to perform governance functions. constructor( string memory _name, string memory _symbol, address _wantToken, address _keeper, address _governance ) ERC20(_name, _symbol) ERC20Permit(_name) { tokenDecimals = IERC20Metadata(_wantToken).decimals(); wantToken = _wantToken; keeper = _keeper; governance = _governance; // to prevent any front running deposits batcherOnlyDeposit = true; } function decimals() public view override returns (uint8) { return tokenDecimals; } /*/////////////////////////////////////////////////////////////// USER DEPOSIT/WITHDRAWAL LOGIC //////////////////////////////////////////////////////////////*/ /// @notice Initiates a deposit of want tokens to the vault. /// @param amountIn The amount of want tokens to deposit. /// @param receiver The address to receive vault tokens. function deposit(uint256 amountIn, address receiver) public override nonReentrant ensureFeesAreCollected returns (uint256 shares) { /// checks for only batcher deposit onlyBatcher(); isValidAddress(receiver); require(amountIn > 0, "ZERO_AMOUNT"); // calculate the shares based on the amount. shares = totalSupply() > 0 ? (totalSupply() * amountIn) / totalVaultFunds() : amountIn; require(shares != 0, "ZERO_SHARES"); IERC20(wantToken).safeTransferFrom(msg.sender, address(this), amountIn); _mint(receiver, shares); } /// @notice Initiates a withdrawal of vault tokens to the user. /// @param sharesIn The amount of vault tokens to withdraw. /// @param receiver The address to receive the vault tokens. function withdraw(uint256 sharesIn, address receiver) public override nonReentrant ensureFeesAreCollected returns (uint256 amountOut) { /// checks for only batcher withdrawal onlyBatcher(); isValidAddress(receiver); require(sharesIn > 0, "ZERO_SHARES"); // calculate the amount based on the shares. amountOut = (sharesIn * totalVaultFunds()) / totalSupply(); // burn shares of msg.sender _burn(msg.sender, sharesIn); /// charging exitFee if (exitFee > 0) { uint256 fee = (amountOut * exitFee) / MAX_BPS; IERC20(wantToken).transfer(governance, fee); amountOut = amountOut - fee; } IERC20(wantToken).safeTransfer(receiver, amountOut); } /// @notice Calculates the total amount of underlying tokens the vault holds. /// @return The total amount of underlying tokens the vault holds. function totalVaultFunds() public view returns (uint256) { return IERC20(wantToken).balanceOf(address(this)) + totalExecutorFunds(); } /*/////////////////////////////////////////////////////////////// EXECUTOR DEPOSIT/WITHDRAWAL LOGIC //////////////////////////////////////////////////////////////*/ /// @notice list of trade executors connected to vault. AddrArrayLib.Addresses tradeExecutorsList; /// @notice Emitted after the vault deposits into a executor contract. /// @param executor The executor that was deposited into. /// @param underlyingAmount The amount of underlying tokens that were deposited. event ExecutorDeposit(address indexed executor, uint256 underlyingAmount); /// @notice Emitted after the vault withdraws funds from a executor contract. /// @param executor The executor that was withdrawn from. /// @param underlyingAmount The amount of underlying tokens that were withdrawn. event ExecutorWithdrawal( address indexed executor, uint256 underlyingAmount ); /// @notice Deposit given amount of want tokens into valid executor. /// @param _executor The executor to deposit into. /// @param _amount The amount of want tokens to deposit. function depositIntoExecutor(address _executor, uint256 _amount) public nonReentrant { isActiveExecutor(_executor); onlyKeeper(); require(_amount > 0, "ZERO_AMOUNT"); IERC20(wantToken).safeTransfer(_executor, _amount); emit ExecutorDeposit(_executor, _amount); } /// @notice Withdraw given amount of want tokens into valid executor. /// @param _executor The executor to withdraw tokens from. /// @param _amount The amount of want tokens to withdraw. function withdrawFromExecutor(address _executor, uint256 _amount) public nonReentrant { isActiveExecutor(_executor); onlyKeeper(); require(_amount > 0, "ZERO_AMOUNT"); IERC20(wantToken).safeTransferFrom(_executor, address(this), _amount); emit ExecutorWithdrawal(_executor, _amount); } /*/////////////////////////////////////////////////////////////// FEE CONFIGURATION //////////////////////////////////////////////////////////////*/ /// @notice lagging value of vault total funds. /// @dev value intialized to max to prevent slashing on first deposit. uint256 public prevVaultFunds = type(uint256).max; /// @dev value intialized to max to prevent slashing on first deposit. uint256 public lastReportedTime = type(uint256).max; /// @dev Perfomance fee for the vault. uint256 public performanceFee; /// @notice Fee denominated in MAX_BPS charged during exit. uint256 public exitFee; /// @notice Mangement fee for operating the vault. uint256 public managementFee; /// @notice Emitted after perfomance fee updation. /// @param oldFee The old performance fee on vault. /// @param newFee The new performance fee on vault. event UpdatePerformanceFee(uint256 oldFee, uint256 newFee); /// @notice Updates the performance fee on the vault. /// @param _fee The new performance fee on the vault. /// @dev The new fee must be always less than 50% of yield. function setPerformanceFee(uint256 _fee) public { onlyGovernance(); require(_fee < MAX_BPS / 2, "FEE_TOO_HIGH"); emit UpdatePerformanceFee(performanceFee, _fee); performanceFee = _fee; } /// @notice Emitted after exit fee updation. /// @param oldFee The old exit fee on vault. /// @param newFee The new exit fee on vault. event UpdateExitFee(uint256 oldFee, uint256 newFee); /// @notice Function to set exit fee on the vault, can only be called by governance /// @param _fee Address of fee function setExitFee(uint256 _fee) public { onlyGovernance(); require(_fee < MAX_BPS / 2, "EXIT_FEE_TOO_HIGH"); emit UpdateExitFee(exitFee, _fee); exitFee = _fee; } /// @notice Emitted after management fee updation. /// @param oldFee The old management fee on vault. /// @param newFee The new management fee on vault. event UpdateManagementFee(uint256 oldFee, uint256 newFee); /// @notice Function to set exit fee on the vault, can only be called by governance /// @param _fee Address of fee function setManagementFee(uint256 _fee) public { onlyGovernance(); require(_fee < MAX_BPS / 2, "EXIT_FEE_TOO_HIGH"); emit UpdateManagementFee(managementFee, _fee); managementFee = _fee; } /// @notice Emitted when a fees are collected. /// @param collectedFees The amount of fees collected. event FeesCollected(uint256 collectedFees); /// @notice Calculates and collects the fees from the vault. /// @dev This function sends all the accured fees to governance. /// checks the yield made since previous harvest and /// calculates the fee based on it. Also note: this function /// should be called before processing any new deposits/withdrawals. function collectFees() internal { uint256 currentFunds = totalVaultFunds(); uint256 fees = 0; // collect fees only when profit is made. if ((performanceFee > 0) && (currentFunds > prevVaultFunds)) { uint256 yieldEarned = (currentFunds - prevVaultFunds); // normalization by MAX_BPS fees += ((yieldEarned * performanceFee) / MAX_BPS); } if ((managementFee > 0) && (lastReportedTime < block.timestamp)) { uint256 duration = block.timestamp - lastReportedTime; fees += ((duration * managementFee * currentFunds) / MAX_SECONDS) / MAX_BPS; } if (fees > 0) { IERC20(wantToken).safeTransfer(governance, fees); emit FeesCollected(fees); } } modifier ensureFeesAreCollected() { collectFees(); _; // update vault funds after fees are collected. prevVaultFunds = totalVaultFunds(); // update lastReportedTime after fees are collected. lastReportedTime = block.timestamp; } /*/////////////////////////////////////////////////////////////// EXECUTOR ADDITION/REMOVAL LOGIC //////////////////////////////////////////////////////////////*/ /// @notice Emitted when executor is added to vault. /// @param executor The address of added executor. event ExecutorAdded(address indexed executor); /// @notice Emitted when executor is removed from vault. /// @param executor The address of removed executor. event ExecutorRemoved(address indexed executor); /// @notice Adds a trade executor, enabling it to execute trades. /// @param _tradeExecutor The address of _tradeExecutor contract. function addExecutor(address _tradeExecutor) public { onlyGovernance(); isValidAddress(_tradeExecutor); require( ITradeExecutor(_tradeExecutor).vault() == address(this), "INVALID_VAULT" ); require( IERC20(wantToken).allowance(_tradeExecutor, address(this)) > 0, "NO_ALLOWANCE" ); tradeExecutorsList.pushAddress(_tradeExecutor); emit ExecutorAdded(_tradeExecutor); } /// @notice Adds a trade executor, enabling it to execute trades. /// @param _tradeExecutor The address of _tradeExecutor contract. /// @dev make sure all funds are withdrawn from executor before removing. function removeExecutor(address _tradeExecutor) public { onlyGovernance(); isValidAddress(_tradeExecutor); // check if executor attached to vault. isActiveExecutor(_tradeExecutor); (uint256 executorFunds, uint256 blockUpdated) = ITradeExecutor( _tradeExecutor ).totalFunds(); areFundsUpdated(blockUpdated); require(executorFunds < DUST_LIMIT, "FUNDS_TOO_HIGH"); tradeExecutorsList.removeAddress(_tradeExecutor); emit ExecutorRemoved(_tradeExecutor); } /// @notice gives the number of trade executors. /// @return The number of trade executors. function totalExecutors() public view returns (uint256) { return tradeExecutorsList.size(); } /// @notice Returns trade executor at given index. /// @return The executor address at given valid index. function executorByIndex(uint256 _index) public view returns (address) { return tradeExecutorsList.getAddressAtIndex(_index); } /// @notice Calculates funds held by all executors in want token. /// @return Sum of all funds held by executors. function totalExecutorFunds() public view returns (uint256) { uint256 totalFunds = 0; for (uint256 i = 0; i < totalExecutors(); i++) { address executor = executorByIndex(i); (uint256 executorFunds, uint256 blockUpdated) = ITradeExecutor( executor ).totalFunds(); areFundsUpdated(blockUpdated); totalFunds += executorFunds; } return totalFunds; } /*/////////////////////////////////////////////////////////////// GOVERNANCE ACTIONS //////////////////////////////////////////////////////////////*/ /// @notice Emitted when a batcher is updated. /// @param oldBatcher The address of the current batcher. /// @param newBatcher The address of new batcher. event UpdatedBatcher( address indexed oldBatcher, address indexed newBatcher ); /// @notice Changes the batcher address. /// @dev This can only be called by governance. /// @param _batcher The address to for new batcher. function setBatcher(address _batcher) public { onlyGovernance(); emit UpdatedBatcher(batcher, _batcher); batcher = _batcher; } /// @notice Emitted batcherOnlyDeposit is enabled. /// @param state The state of depositing only via batcher. event UpdatedBatcherOnlyDeposit(bool state); /// @notice Enables/disables deposits with batcher only. /// @dev This can only be called by governance. /// @param _batcherOnlyDeposit if true vault can accept deposit via batcher only or else anyone can deposit. function setBatcherOnlyDeposit(bool _batcherOnlyDeposit) public { onlyGovernance(); batcherOnlyDeposit = _batcherOnlyDeposit; emit UpdatedBatcherOnlyDeposit(_batcherOnlyDeposit); } /// @notice Nominates new governance address. /// @dev Governance will only be changed if the new governance accepts it. It will be pending till then. /// @param _governance The address of new governance. function setGovernance(address _governance) public { onlyGovernance(); pendingGovernance = _governance; } /// @notice Emitted when governance is updated. /// @param oldGovernance The address of the current governance. /// @param newGovernance The address of new governance. event UpdatedGovernance( address indexed oldGovernance, address indexed newGovernance ); /// @notice The nomine of new governance address proposed by `setGovernance` function can accept the governance. /// @dev This can only be called by address of pendingGovernance. function acceptGovernance() public { require(msg.sender == pendingGovernance, "INVALID_ADDRESS"); emit UpdatedGovernance(governance, pendingGovernance); governance = pendingGovernance; } /// @notice Emitted when keeper is updated. /// @param oldKeeper The address of the old keeper. /// @param newKeeper The address of the new keeper. event UpdatedKeeper(address indexed oldKeeper, address indexed newKeeper); /// @notice Sets new keeper address. /// @dev This can only be called by governance. /// @param _keeper The address of new keeper. function setKeeper(address _keeper) public { onlyGovernance(); emit UpdatedKeeper(keeper, _keeper); keeper = _keeper; } /// @notice Emitted when emergencyMode status is updated. /// @param emergencyMode boolean indicating state of emergency. event EmergencyModeStatus(bool emergencyMode); /// @notice sets emergencyMode. /// @dev This can only be called by governance. /// @param _emergencyMode if true, vault will be in emergency mode. function setEmergencyMode(bool _emergencyMode) public { onlyGovernance(); emergencyMode = _emergencyMode; batcherOnlyDeposit = true; batcher = address(0); emit EmergencyModeStatus(_emergencyMode); } /// @notice Removes invalid tokens from the vault. /// @dev This is used as fail safe to remove want tokens from the vault during emergency mode /// can be called by anyone to send funds to governance. /// @param _token The address of token to be removed. function sweep(address _token) public { isEmergencyMode(); IERC20(_token).safeTransfer( governance, IERC20(_token).balanceOf(address(this)) ); } /*/////////////////////////////////////////////////////////////// ACCESS MODIFERS //////////////////////////////////////////////////////////////*/ /// @dev Checks if the sender is the governance. function onlyGovernance() internal view { require(msg.sender == governance, "ONLY_GOV"); } /// @dev Checks if the sender is the keeper. function onlyKeeper() internal view { require(msg.sender == keeper, "ONLY_KEEPER"); } /// @dev Checks if the sender is the batcher. function onlyBatcher() internal view { if (batcherOnlyDeposit) { require(msg.sender == batcher, "ONLY_BATCHER"); } } /// @dev Checks if emergency mode is enabled. function isEmergencyMode() internal view { require(emergencyMode == true, "EMERGENCY_MODE"); } /// @dev Checks if the address is valid. function isValidAddress(address _addr) internal pure { require(_addr != address(0), "NULL_ADDRESS"); } /// @dev Checks if the tradeExecutor is valid. function isActiveExecutor(address _tradeExecutor) internal view { require(tradeExecutorsList.exists(_tradeExecutor), "INVALID_EXECUTOR"); } /// @dev Checks if funds are updated. function areFundsUpdated(uint256 _blockUpdated) internal view { require( block.number <= _blockUpdated + BLOCK_LIMIT, "FUNDS_NOT_UPDATED" ); } }
11,889
22
// Sets the current epoch as expired/Can only be called by the owner/_settlementPrice The settlement price/_settlementCollateralExchangeRate the settlement collateral exchange rate
function expire( uint256 _settlementPrice, uint256 _settlementCollateralExchangeRate
function expire( uint256 _settlementPrice, uint256 _settlementCollateralExchangeRate
22,896
0
// A descriptive name for a collection of NFTs. /
string internal nftName;
string internal nftName;
28,841
11
// _name = "Parsiq Finance Token";_symbol = "PRQF";
_name = "Parsiq Finance Token"; _symbol = "PRQF"; _decimals = 18; _totalSupply = 500000000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply);
_name = "Parsiq Finance Token"; _symbol = "PRQF"; _decimals = 18; _totalSupply = 500000000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply);
22,488
28
// List of addresses allowed to send ETH to this contract, empty if anyone is allowed
address[] public allowedSenders;
address[] public allowedSenders;
25,887
8
// Wrapper around `IUniswapV3Pool.positions()`.
function _position(int24 tickLower, int24 tickUpper) internal view returns ( uint128, // liquidity uint256, // feeGrowthInside0LastX128 uint256, // feeGrowthInside1LastX128 uint128, // tokensOwed0 uint128 // tokensOwed1 )
function _position(int24 tickLower, int24 tickUpper) internal view returns ( uint128, // liquidity uint256, // feeGrowthInside0LastX128 uint256, // feeGrowthInside1LastX128 uint128, // tokensOwed0 uint128 // tokensOwed1 )
35,944
2
// Functions//Allows the owner to set the address for the oracleID descriptors used by the ADO members for price key value pairs standarization_oracleDescriptos is the address for the OracleIDDescptions contract/
function setOracleIDDescriptors(address _oracleDescriptors) external { require(msg.sender == owner, "Sender is not owner"); oracleIDDescriptionsAddress = _oracleDescriptors; descriptions = OracleIDDescriptions(_oracleDescriptors); emit NewDescriptorSet(_oracleDescriptors); }
function setOracleIDDescriptors(address _oracleDescriptors) external { require(msg.sender == owner, "Sender is not owner"); oracleIDDescriptionsAddress = _oracleDescriptors; descriptions = OracleIDDescriptions(_oracleDescriptors); emit NewDescriptorSet(_oracleDescriptors); }
24,061
18
// ERC20 compatible methods // This function is used to tell outside contracts and applications the name of this token.
function name() public pure returns (string) { return NAME; }
function name() public pure returns (string) { return NAME; }
17,595
102
// Queries the approval status of an operator for a given owner _owner The owner of the Tokens _operatorAddress of authorized operatorreturn True if the operator is approved, false if not /
function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator)
function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator)
14,558
23
// success
emit NFTReceived(operator, from, tokenId, data); return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
emit NFTReceived(operator, from, tokenId, data); return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
18,963
58
// Returns the current total of tokens staked for an address addr address The address to queryreturn uint256 The number of tokens staked for the given address /
function totalStakedFor(address addr) external view returns (uint256);
function totalStakedFor(address addr) external view returns (uint256);
45,711
145
// Ensure that this function is only callable during contract construction.
assembly { if extcodesize(address()) { revert(0, 0) }
assembly { if extcodesize(address()) { revert(0, 0) }
79,950
330
// Invests all excess tokens. Leaves only minCashThreshold in underlying tokens.Requires interest for the given token to be enabled first. _token address of the token contract considered. /
function invest(address _token) external { IInterestImplementation impl = interestImplementation(_token); // less than _token.balanceOf(this), since it does not take into account mistakenly locked tokens that should be processed via fixMediatorBalance. uint256 balance = mediatorBalance(_token).sub(impl.investedAmount(_token)); uint256 minCash = minCashThreshold(_token); require(balance > minCash); uint256 amount = balance - minCash; IERC20(_token).safeTransfer(address(impl), amount); impl.invest(_token, amount); }
function invest(address _token) external { IInterestImplementation impl = interestImplementation(_token); // less than _token.balanceOf(this), since it does not take into account mistakenly locked tokens that should be processed via fixMediatorBalance. uint256 balance = mediatorBalance(_token).sub(impl.investedAmount(_token)); uint256 minCash = minCashThreshold(_token); require(balance > minCash); uint256 amount = balance - minCash; IERC20(_token).safeTransfer(address(impl), amount); impl.invest(_token, amount); }
16,620
37
// id A bytes32 bid id/bidder The address of the bidder/bidCollateralTokens The addresses of the token used as collateral/amounts The amounts of collateral tokens to unlock
function auctionUnlockBid( bytes32 id, address bidder, address[] calldata bidCollateralTokens, uint256[] calldata amounts
function auctionUnlockBid( bytes32 id, address bidder, address[] calldata bidCollateralTokens, uint256[] calldata amounts
27,795
110
// Converts total supplies of options into the tokenized payoff quantities usedby the LMSR For puts, multiply by strike price since option quantity is in terms of theunderlying, but lmsr quantities should be in terms of the strike currency /
function calcQuantities( uint256[] memory strikePrices, bool isPut, uint256[] memory longSupplies, uint256[] memory shortSupplies
function calcQuantities( uint256[] memory strikePrices, bool isPut, uint256[] memory longSupplies, uint256[] memory shortSupplies
37,089
258
// ███ Contract deployment
bytes memory creationCode = type(RiseToken).creationCode; string memory tokenName = string(abi.encodePacked(IERC20Metadata(collateral).symbol(), " 2x Long Risedle")); string memory tokenSymbol = string(abi.encodePacked(IERC20Metadata(collateral).symbol(), "RISE")); bytes memory constructorArgs = abi.encode(tokenName, tokenSymbol, address(this), _fCollateral, _fDebt, _uniswapAdapter, _oracleAdapter); bytes memory bytecode = abi.encodePacked(creationCode, constructorArgs); bytes32 salt = keccak256(abi.encodePacked(_fCollateral, _fDebt)); assembly { _token := create2(0, add(bytecode, 32), mload(bytecode), salt) }
bytes memory creationCode = type(RiseToken).creationCode; string memory tokenName = string(abi.encodePacked(IERC20Metadata(collateral).symbol(), " 2x Long Risedle")); string memory tokenSymbol = string(abi.encodePacked(IERC20Metadata(collateral).symbol(), "RISE")); bytes memory constructorArgs = abi.encode(tokenName, tokenSymbol, address(this), _fCollateral, _fDebt, _uniswapAdapter, _oracleAdapter); bytes memory bytecode = abi.encodePacked(creationCode, constructorArgs); bytes32 salt = keccak256(abi.encodePacked(_fCollateral, _fDebt)); assembly { _token := create2(0, add(bytecode, 32), mload(bytecode), salt) }
16,613
39
// LendingPool contract Main point of interaction with a protocol's market- Users can: Deposit Withdraw Borrow Repay Swap their loans between variable and stable rate Enable/disable their deposits as collateral rebalance stable rate borrow positions Liquidate positions Execute Flash Loans /
contract LendingPool is LendingPoolBase, ILendingPool, Delegator, ILendingPoolForTokens { using SafeERC20 for IERC20; using WadRayMath for uint256; using AccessHelper for IMarketAccessController; using ReserveLogic for DataTypes.ReserveData; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; uint256 private constant POOL_REVISION = 0x1; function getRevision() internal pure virtual override returns (uint256) { return POOL_REVISION; } function initialize(IMarketAccessController provider) public initializer(POOL_REVISION) { _addressesProvider = provider; _maxStableRateBorrowSizePct = 25 * PercentageMath.PCT; _flashLoanPremiumPct = 9 * PercentageMath.BP; } // solhint-disable-next-line payable-fallback fallback() external { // all IManagedLendingPool etc functions should be delegated to the extension _delegate(_extension); } function deposit( address asset, uint256 amount, address onBehalfOf, uint256 referral ) public override whenNotPaused noReentryOrFlashloanFeature(FEATURE_FLASHLOAN_DEPOSIT) { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateDeposit(reserve, amount); address depositToken = reserve.depositTokenAddress; uint256 liquidityIndex = reserve.updateStateForDeposit(asset); reserve.updateInterestRates(asset, depositToken, amount, 0); IERC20(asset).safeTransferFrom(msg.sender, depositToken, amount); bool isFirstDeposit = IDepositToken(depositToken).mint(onBehalfOf, amount, liquidityIndex, false); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit(asset, msg.sender, onBehalfOf, amount, referral); } function withdraw( address asset, uint256 amountToWithdraw, address to ) external override whenNotPaused noReentryOrFlashloanFeature(FEATURE_FLASHLOAN_WITHDRAW) returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; address depositToken = reserve.depositTokenAddress; uint256 liquidityIndex = reserve.updateStateForDeposit(asset); uint256 userBalance = IDepositToken(depositToken).scaledBalanceOf(msg.sender); userBalance = userBalance.rayMul(liquidityIndex); if (amountToWithdraw == type(uint256).max) { amountToWithdraw = userBalance; } ValidationLogic.validateWithdraw( asset, amountToWithdraw, userBalance, _reserves, _usersConfig[msg.sender], _reservesList, _addressesProvider.getPriceOracle() ); reserve.updateInterestRates(asset, depositToken, 0, amountToWithdraw); if (amountToWithdraw == userBalance) { _usersConfig[msg.sender].unsetUsingAsCollateral(reserve.id); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } IDepositToken(depositToken).burn(msg.sender, to, amountToWithdraw, liquidityIndex); emit Withdraw(asset, msg.sender, to, amountToWithdraw); return amountToWithdraw; } function borrow( address, uint256, uint256, uint256, address ) external override { // for compatibility with ILendingPool _delegate(_extension); } function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external override whenNotPaused noReentryOrFlashloanFeature(FEATURE_FLASHLOAN_REPAY) returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode); ValidationLogic.validateRepay(reserve, amount, interestRateMode, onBehalfOf, stableDebt, variableDebt); uint256 paybackAmount = interestRateMode == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } reserve.updateState(asset); if (interestRateMode == DataTypes.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount); } else { IVariableDebtToken(reserve.variableDebtTokenAddress).burn(onBehalfOf, paybackAmount, reserve.variableBorrowIndex); } address depositToken = reserve.depositTokenAddress; reserve.updateInterestRates(asset, depositToken, paybackAmount, 0); if (stableDebt + variableDebt <= paybackAmount) { _usersConfig[onBehalfOf].unsetBorrowing(reserve.id); } IERC20(asset).safeTransferFrom(msg.sender, depositToken, paybackAmount); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); return paybackAmount; } function swapBorrowRateMode(address asset, uint256 rateMode) external override whenNotPaused noReentryOrFlashloan { DataTypes.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(msg.sender, reserve); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode); ValidationLogic.validateSwapRateMode(reserve, _usersConfig[msg.sender], stableDebt, variableDebt, interestRateMode); reserve.updateState(asset); if (interestRateMode == DataTypes.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); IVariableDebtToken(reserve.variableDebtTokenAddress).mint( msg.sender, msg.sender, stableDebt, reserve.variableBorrowIndex ); } else { IVariableDebtToken(reserve.variableDebtTokenAddress).burn(msg.sender, variableDebt, reserve.variableBorrowIndex); IStableDebtToken(reserve.stableDebtTokenAddress).mint( msg.sender, msg.sender, variableDebt, reserve.currentStableBorrowRate ); } reserve.updateInterestRates(asset, reserve.depositTokenAddress, 0, 0); emit Swap(asset, msg.sender, rateMode); } function rebalanceStableBorrowRate(address asset, address user) external override whenNotPaused noReentryOrFlashloan { DataTypes.ReserveData storage reserve = _reserves[asset]; IERC20 stableDebtToken = IERC20(reserve.stableDebtTokenAddress); uint256 stableDebt = IERC20(stableDebtToken).balanceOf(user); address depositToken = reserve.depositTokenAddress; ValidationLogic.validateRebalanceStableBorrowRate(reserve, asset, stableDebtToken, depositToken); reserve.updateState(asset); IStableDebtToken(address(stableDebtToken)).burn(user, stableDebt); IStableDebtToken(address(stableDebtToken)).mint(user, user, stableDebt, reserve.currentStableBorrowRate); reserve.updateInterestRates(asset, depositToken, 0, 0); emit RebalanceStableBorrowRate(asset, user); } function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateSetUseReserveAsCollateral( reserve, asset, useAsCollateral, _reserves, _usersConfig[msg.sender], _reservesList, _addressesProvider.getPriceOracle() ); if (useAsCollateral) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.id); emit ReserveUsedAsCollateralEnabled(asset, msg.sender); } else { _usersConfig[msg.sender].unsetUsingAsCollateral(reserve.id); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } } function liquidationCall( address, address, address, uint256, bool ) external override { // for compatibility with ILendingPool _delegate(_extension); } function flashLoan( address, address[] calldata, uint256[] calldata, uint256[] calldata, address, bytes calldata, uint256 ) external override { // for compatibility with ILendingPool _delegate(_extension); } function getReserveData(address asset) external view override(ILendingPool, ILendingPoolForTokens) returns (DataTypes.ReserveData memory) { return _reserves[asset]; } function getUserAccountData(address user) external view override returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) { (totalCollateralETH, totalDebtETH, ltv, currentLiquidationThreshold, healthFactor) = GenericLogic .calculateUserAccountData( user, _reserves, _usersConfig[user], _reservesList, _addressesProvider.getPriceOracle() ); availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH(totalCollateralETH, totalDebtETH, ltv); } function getConfiguration(address asset) external view override(ILendingPool, ILendingPoolForTokens) returns (DataTypes.ReserveConfigurationMap memory) { return _reserves[asset].configuration; } function getUserConfiguration(address user) external view override returns (DataTypes.UserConfigurationMap memory) { return _usersConfig[user]; } function getReserveNormalizedIncome(address asset) external view virtual override(ILendingPool, ILendingPoolForTokens) returns (uint256) { return _reserves[asset].getNormalizedIncome(asset); } function getReserveNormalizedVariableDebt(address asset) external view override(ILendingPool, ILendingPoolForTokens) returns (uint256) { return _reserves[asset].getNormalizedDebt(); } function getReservesList() external view override(ILendingPool, ILendingPoolForTokens) returns (address[] memory) { address[] memory _activeReserves = new address[](_reservesCount); for (uint256 i = 0; i < _reservesCount; i++) { _activeReserves[i] = _reservesList[i]; } return _activeReserves; } function getAccessController() external view override returns (IMarketAccessController) { return _addressesProvider; } /// @dev Returns the percentage of available liquidity that can be borrowed at once at stable rate // solhint-disable-next-line func-name-mixedcase function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() public view returns (uint256) { return _maxStableRateBorrowSizePct; } /// @dev Returns the fee of flash loans - backward compatible // solhint-disable-next-line func-name-mixedcase function FLASHLOAN_PREMIUM_TOTAL() public view returns (uint256) { return _flashLoanPremiumPct; } function getFlashloanPremiumPct() public view override returns (uint16) { return _flashLoanPremiumPct; } function getAddressesProvider() external view override returns (address) { return address(_addressesProvider); } /// @dev Returns the address of the LendingPoolExtension function getLendingPoolExtension() external view returns (address) { return _extension; } /// @dev Updates the address of the LendingPoolExtension function setLendingPoolExtension(address extension) external onlyConfiguratorOrAdmin { require(Address.isContract(extension), Errors.VL_CONTRACT_REQUIRED); _extension = extension; emit LendingPoolExtensionUpdated(extension); } function finalizeTransfer( address asset, address from, address to, bool lastBalanceFrom, bool firstBalanceTo ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; require(msg.sender == reserve.depositTokenAddress, Errors.LP_CALLER_MUST_BE_DEPOSIT_TOKEN); DataTypes.UserConfigurationMap storage fromConfig = _usersConfig[from]; ValidationLogic.validateTransfer( asset, from, _reserves, fromConfig, _reservesList, _addressesProvider.getPriceOracle() ); if (from != to) { if (lastBalanceFrom) { fromConfig.unsetUsingAsCollateral(reserve.id); emit ReserveUsedAsCollateralDisabled(asset, from); } if (firstBalanceTo) { DataTypes.UserConfigurationMap storage toConfig = _usersConfig[to]; toConfig.setUsingAsCollateral(reserve.id); emit ReserveUsedAsCollateralEnabled(asset, to); } } } function setReservePaused(address asset, bool paused) external override { DataTypes.ReserveData storage reserve = _reserves[asset]; if (msg.sender != reserve.depositTokenAddress) { _onlyEmergencyAdmin(); require(reserve.depositTokenAddress != address(0), Errors.VL_UNKNOWN_RESERVE); } DataTypes.ReserveConfigurationMap memory config = reserve.configuration; config.setFrozen(paused); reserve.configuration = config; } }
contract LendingPool is LendingPoolBase, ILendingPool, Delegator, ILendingPoolForTokens { using SafeERC20 for IERC20; using WadRayMath for uint256; using AccessHelper for IMarketAccessController; using ReserveLogic for DataTypes.ReserveData; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; uint256 private constant POOL_REVISION = 0x1; function getRevision() internal pure virtual override returns (uint256) { return POOL_REVISION; } function initialize(IMarketAccessController provider) public initializer(POOL_REVISION) { _addressesProvider = provider; _maxStableRateBorrowSizePct = 25 * PercentageMath.PCT; _flashLoanPremiumPct = 9 * PercentageMath.BP; } // solhint-disable-next-line payable-fallback fallback() external { // all IManagedLendingPool etc functions should be delegated to the extension _delegate(_extension); } function deposit( address asset, uint256 amount, address onBehalfOf, uint256 referral ) public override whenNotPaused noReentryOrFlashloanFeature(FEATURE_FLASHLOAN_DEPOSIT) { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateDeposit(reserve, amount); address depositToken = reserve.depositTokenAddress; uint256 liquidityIndex = reserve.updateStateForDeposit(asset); reserve.updateInterestRates(asset, depositToken, amount, 0); IERC20(asset).safeTransferFrom(msg.sender, depositToken, amount); bool isFirstDeposit = IDepositToken(depositToken).mint(onBehalfOf, amount, liquidityIndex, false); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit(asset, msg.sender, onBehalfOf, amount, referral); } function withdraw( address asset, uint256 amountToWithdraw, address to ) external override whenNotPaused noReentryOrFlashloanFeature(FEATURE_FLASHLOAN_WITHDRAW) returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; address depositToken = reserve.depositTokenAddress; uint256 liquidityIndex = reserve.updateStateForDeposit(asset); uint256 userBalance = IDepositToken(depositToken).scaledBalanceOf(msg.sender); userBalance = userBalance.rayMul(liquidityIndex); if (amountToWithdraw == type(uint256).max) { amountToWithdraw = userBalance; } ValidationLogic.validateWithdraw( asset, amountToWithdraw, userBalance, _reserves, _usersConfig[msg.sender], _reservesList, _addressesProvider.getPriceOracle() ); reserve.updateInterestRates(asset, depositToken, 0, amountToWithdraw); if (amountToWithdraw == userBalance) { _usersConfig[msg.sender].unsetUsingAsCollateral(reserve.id); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } IDepositToken(depositToken).burn(msg.sender, to, amountToWithdraw, liquidityIndex); emit Withdraw(asset, msg.sender, to, amountToWithdraw); return amountToWithdraw; } function borrow( address, uint256, uint256, uint256, address ) external override { // for compatibility with ILendingPool _delegate(_extension); } function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external override whenNotPaused noReentryOrFlashloanFeature(FEATURE_FLASHLOAN_REPAY) returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode); ValidationLogic.validateRepay(reserve, amount, interestRateMode, onBehalfOf, stableDebt, variableDebt); uint256 paybackAmount = interestRateMode == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } reserve.updateState(asset); if (interestRateMode == DataTypes.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount); } else { IVariableDebtToken(reserve.variableDebtTokenAddress).burn(onBehalfOf, paybackAmount, reserve.variableBorrowIndex); } address depositToken = reserve.depositTokenAddress; reserve.updateInterestRates(asset, depositToken, paybackAmount, 0); if (stableDebt + variableDebt <= paybackAmount) { _usersConfig[onBehalfOf].unsetBorrowing(reserve.id); } IERC20(asset).safeTransferFrom(msg.sender, depositToken, paybackAmount); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); return paybackAmount; } function swapBorrowRateMode(address asset, uint256 rateMode) external override whenNotPaused noReentryOrFlashloan { DataTypes.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(msg.sender, reserve); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode); ValidationLogic.validateSwapRateMode(reserve, _usersConfig[msg.sender], stableDebt, variableDebt, interestRateMode); reserve.updateState(asset); if (interestRateMode == DataTypes.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); IVariableDebtToken(reserve.variableDebtTokenAddress).mint( msg.sender, msg.sender, stableDebt, reserve.variableBorrowIndex ); } else { IVariableDebtToken(reserve.variableDebtTokenAddress).burn(msg.sender, variableDebt, reserve.variableBorrowIndex); IStableDebtToken(reserve.stableDebtTokenAddress).mint( msg.sender, msg.sender, variableDebt, reserve.currentStableBorrowRate ); } reserve.updateInterestRates(asset, reserve.depositTokenAddress, 0, 0); emit Swap(asset, msg.sender, rateMode); } function rebalanceStableBorrowRate(address asset, address user) external override whenNotPaused noReentryOrFlashloan { DataTypes.ReserveData storage reserve = _reserves[asset]; IERC20 stableDebtToken = IERC20(reserve.stableDebtTokenAddress); uint256 stableDebt = IERC20(stableDebtToken).balanceOf(user); address depositToken = reserve.depositTokenAddress; ValidationLogic.validateRebalanceStableBorrowRate(reserve, asset, stableDebtToken, depositToken); reserve.updateState(asset); IStableDebtToken(address(stableDebtToken)).burn(user, stableDebt); IStableDebtToken(address(stableDebtToken)).mint(user, user, stableDebt, reserve.currentStableBorrowRate); reserve.updateInterestRates(asset, depositToken, 0, 0); emit RebalanceStableBorrowRate(asset, user); } function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateSetUseReserveAsCollateral( reserve, asset, useAsCollateral, _reserves, _usersConfig[msg.sender], _reservesList, _addressesProvider.getPriceOracle() ); if (useAsCollateral) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.id); emit ReserveUsedAsCollateralEnabled(asset, msg.sender); } else { _usersConfig[msg.sender].unsetUsingAsCollateral(reserve.id); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } } function liquidationCall( address, address, address, uint256, bool ) external override { // for compatibility with ILendingPool _delegate(_extension); } function flashLoan( address, address[] calldata, uint256[] calldata, uint256[] calldata, address, bytes calldata, uint256 ) external override { // for compatibility with ILendingPool _delegate(_extension); } function getReserveData(address asset) external view override(ILendingPool, ILendingPoolForTokens) returns (DataTypes.ReserveData memory) { return _reserves[asset]; } function getUserAccountData(address user) external view override returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) { (totalCollateralETH, totalDebtETH, ltv, currentLiquidationThreshold, healthFactor) = GenericLogic .calculateUserAccountData( user, _reserves, _usersConfig[user], _reservesList, _addressesProvider.getPriceOracle() ); availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH(totalCollateralETH, totalDebtETH, ltv); } function getConfiguration(address asset) external view override(ILendingPool, ILendingPoolForTokens) returns (DataTypes.ReserveConfigurationMap memory) { return _reserves[asset].configuration; } function getUserConfiguration(address user) external view override returns (DataTypes.UserConfigurationMap memory) { return _usersConfig[user]; } function getReserveNormalizedIncome(address asset) external view virtual override(ILendingPool, ILendingPoolForTokens) returns (uint256) { return _reserves[asset].getNormalizedIncome(asset); } function getReserveNormalizedVariableDebt(address asset) external view override(ILendingPool, ILendingPoolForTokens) returns (uint256) { return _reserves[asset].getNormalizedDebt(); } function getReservesList() external view override(ILendingPool, ILendingPoolForTokens) returns (address[] memory) { address[] memory _activeReserves = new address[](_reservesCount); for (uint256 i = 0; i < _reservesCount; i++) { _activeReserves[i] = _reservesList[i]; } return _activeReserves; } function getAccessController() external view override returns (IMarketAccessController) { return _addressesProvider; } /// @dev Returns the percentage of available liquidity that can be borrowed at once at stable rate // solhint-disable-next-line func-name-mixedcase function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() public view returns (uint256) { return _maxStableRateBorrowSizePct; } /// @dev Returns the fee of flash loans - backward compatible // solhint-disable-next-line func-name-mixedcase function FLASHLOAN_PREMIUM_TOTAL() public view returns (uint256) { return _flashLoanPremiumPct; } function getFlashloanPremiumPct() public view override returns (uint16) { return _flashLoanPremiumPct; } function getAddressesProvider() external view override returns (address) { return address(_addressesProvider); } /// @dev Returns the address of the LendingPoolExtension function getLendingPoolExtension() external view returns (address) { return _extension; } /// @dev Updates the address of the LendingPoolExtension function setLendingPoolExtension(address extension) external onlyConfiguratorOrAdmin { require(Address.isContract(extension), Errors.VL_CONTRACT_REQUIRED); _extension = extension; emit LendingPoolExtensionUpdated(extension); } function finalizeTransfer( address asset, address from, address to, bool lastBalanceFrom, bool firstBalanceTo ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; require(msg.sender == reserve.depositTokenAddress, Errors.LP_CALLER_MUST_BE_DEPOSIT_TOKEN); DataTypes.UserConfigurationMap storage fromConfig = _usersConfig[from]; ValidationLogic.validateTransfer( asset, from, _reserves, fromConfig, _reservesList, _addressesProvider.getPriceOracle() ); if (from != to) { if (lastBalanceFrom) { fromConfig.unsetUsingAsCollateral(reserve.id); emit ReserveUsedAsCollateralDisabled(asset, from); } if (firstBalanceTo) { DataTypes.UserConfigurationMap storage toConfig = _usersConfig[to]; toConfig.setUsingAsCollateral(reserve.id); emit ReserveUsedAsCollateralEnabled(asset, to); } } } function setReservePaused(address asset, bool paused) external override { DataTypes.ReserveData storage reserve = _reserves[asset]; if (msg.sender != reserve.depositTokenAddress) { _onlyEmergencyAdmin(); require(reserve.depositTokenAddress != address(0), Errors.VL_UNKNOWN_RESERVE); } DataTypes.ReserveConfigurationMap memory config = reserve.configuration; config.setFrozen(paused); reserve.configuration = config; } }
19,520
39
// Utility function to get the current block timestamp /
function _currentBlockTimestamp() internal view virtual returns (uint256) { return block.timestamp; }
function _currentBlockTimestamp() internal view virtual returns (uint256) { return block.timestamp; }
40,861
200
// Calculate next Set quantities
uint256 issueAmount; uint256 nextUnitShares; ( issueAmount, nextUnitShares ) = calculateNextSetIssueQuantity( _totalSupply, _naturalUnit, _nextSet, _vaultAddress
uint256 issueAmount; uint256 nextUnitShares; ( issueAmount, nextUnitShares ) = calculateNextSetIssueQuantity( _totalSupply, _naturalUnit, _nextSet, _vaultAddress
7,108
145
// View function to see pending HOLYs on frontend.
function pendingHoly(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHolyPerShare = pool.accHolyPerShare; uint256 lpSupply = totalStaked[address(pool.lpToken)]; if (block.number > pool.lastRewardCalcBlock && lpSupply != 0) { uint256 multiplier = block.number.sub(pool.lastRewardCalcBlock); uint256 tokenReward = multiplier.mul(holyPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accHolyPerShare = accHolyPerShare.add(tokenReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accHolyPerShare).div(1e12).sub(user.rewardDebt); }
function pendingHoly(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHolyPerShare = pool.accHolyPerShare; uint256 lpSupply = totalStaked[address(pool.lpToken)]; if (block.number > pool.lastRewardCalcBlock && lpSupply != 0) { uint256 multiplier = block.number.sub(pool.lastRewardCalcBlock); uint256 tokenReward = multiplier.mul(holyPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accHolyPerShare = accHolyPerShare.add(tokenReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accHolyPerShare).div(1e12).sub(user.rewardDebt); }
29,869
24
// we will slowly move commit-reveal related stuff from ONEWallet to here
library CommitManager { uint32 constant REVEAL_MAX_DELAY = 60; struct Commit { bytes32 paramsHash; bytes32 verificationHash; uint32 timestamp; bool completed; } struct CommitState { mapping(bytes32 => Commit[]) commitLocker; bytes32[] commits; // self-clean on commit (auto delete commits that are beyond REVEAL_MAX_DELAY), so it's bounded by the number of commits an attacker can spam within REVEAL_MAX_DELAY time in the worst case, which is not too bad. /// nonce tracking mapping(uint32 => uint8) nonces; // keys: otp index (=timestamp in seconds / interval); values: the expected nonce for that otp interval. An reveal with a nonce less than the expected value will be rejected uint32[] nonceTracker; // list of nonces keys that have a non-zero value. keys cannot possibly result a successful reveal (indices beyond REVEAL_MAX_DELAY old) are auto-deleted during a clean up procedure that is called every time the nonces are incremented for some key. For each deleted key, the corresponding key in nonces will also be deleted. So the size of nonceTracker and nonces are both bounded. } function getNumCommits(CommitState storage cs) view public returns (uint32){ uint32 numCommits = 0; for (uint32 i = 0; i < cs.commits.length; i++) { numCommits += uint32(cs.commitLocker[cs.commits[i]].length); } return numCommits; } function _getCommitHashes(CommitState storage cs, uint32 numCommits) internal view returns (bytes32[] memory){ bytes32[] memory hashes = new bytes32[](numCommits); uint32 index = 0; for (uint32 i = 0; i < cs.commits.length; i++) { Commit[] storage cc = cs.commitLocker[cs.commits[i]]; for (uint32 j = 0; j < cc.length; j++) { hashes[index] = cs.commits[i]; index++; } } return hashes; } function _getCommitParamHashes(CommitState storage cs, uint32 numCommits) internal view returns (bytes32[] memory){ bytes32[] memory paramHashes = new bytes32[](numCommits); uint32 index = 0; for (uint32 i = 0; i < cs.commits.length; i++) { Commit[] storage cc = cs.commitLocker[cs.commits[i]]; for (uint32 j = 0; j < cc.length; j++) { Commit storage c = cc[j]; paramHashes[index] = c.paramsHash; index++; } } return paramHashes; } function _getVerificationHashes(CommitState storage cs, uint32 numCommits) internal view returns (bytes32[] memory){ bytes32[] memory verificationHashes = new bytes32[](numCommits); uint32 index = 0; for (uint32 i = 0; i < cs.commits.length; i++) { Commit[] storage cc = cs.commitLocker[cs.commits[i]]; for (uint32 j = 0; j < cc.length; j++) { Commit storage c = cc[j]; verificationHashes[index] = c.verificationHash; index++; } } return verificationHashes; } function _getTimestamps(CommitState storage cs, uint32 numCommits) internal view returns (uint32[] memory){ uint32[] memory timestamps = new uint32[](numCommits); uint32 index = 0; for (uint32 i = 0; i < cs.commits.length; i++) { Commit[] storage cc = cs.commitLocker[cs.commits[i]]; for (uint32 j = 0; j < cc.length; j++) { Commit storage c = cc[j]; timestamps[index] = c.timestamp; index++; } } return timestamps; } function _getCompletionStatus(CommitState storage cs, uint32 numCommits) internal view returns (bool[] memory){ bool[] memory completed = new bool[](numCommits); uint32 index = 0; for (uint32 i = 0; i < cs.commits.length; i++) { Commit[] storage cc = cs.commitLocker[cs.commits[i]]; for (uint32 j = 0; j < cc.length; j++) { Commit storage c = cc[j]; completed[index] = c.completed; index++; } } return completed; } function getAllCommits(CommitState storage cs) public view returns (bytes32[] memory, bytes32[] memory, bytes32[] memory, uint32[] memory, bool[] memory){ uint32 numCommits = getNumCommits(cs); bytes32[] memory hashes = _getCommitHashes(cs, numCommits); bytes32[] memory paramHashes = _getCommitParamHashes(cs, numCommits); bytes32[] memory verificationHashes = _getVerificationHashes(cs, numCommits); uint32[] memory timestamps = _getTimestamps(cs, numCommits); bool[] memory completed = _getCompletionStatus(cs, numCommits); return (hashes, paramHashes, verificationHashes, timestamps, completed); } function lookupCommit(CommitState storage cs, bytes32 hash) external view returns (bytes32[] memory, bytes32[] memory, bytes32[] memory, uint32[] memory, bool[] memory){ Commit[] storage cc = cs.commitLocker[hash]; bytes32[] memory hashes = new bytes32[](cc.length); bytes32[] memory paramHashes = new bytes32[](cc.length); bytes32[] memory verificationHashes = new bytes32[](cc.length); uint32[] memory timestamps = new uint32[](cc.length); bool[] memory completed = new bool[](cc.length); for (uint32 i = 0; i < cc.length; i++) { Commit storage c = cc[i]; hashes[i] = hash; paramHashes[i] = c.paramsHash; verificationHashes[i] = c.verificationHash; timestamps[i] = c.timestamp; completed[i] = c.completed; } return (hashes, paramHashes, verificationHashes, timestamps, completed); } /// Remove old commits from storage, where the commit's timestamp is older than block.timestamp - REVEAL_MAX_DELAY. The purpose is to remove dangling data from blockchain, and prevent commits grow unbounded. This is executed at commit time. The committer pays for the gas of this cleanup. Therefore, any attacker who intend to spam commits would be disincentivized. The attacker would not succeed in preventing any normal operation by the user. function cleanupCommits(CommitState storage commitState) external { uint32 timelyIndex = 0; uint32 bt = uint32(block.timestamp); // go through past commits chronologically, starting from the oldest, and find the first commit that is not older than block.timestamp - REVEAL_MAX_DELAY. for (; timelyIndex < commitState.commits.length; timelyIndex++) { bytes32 hash = commitState.commits[timelyIndex]; Commit[] storage cc = commitState.commitLocker[hash]; // We may skip because the commit is already cleaned up and is considered "untimely". if (cc.length == 0) { continue; } // We take the first entry in `cc` as the timestamp for all commits under commit hash `hash`, because the first entry represents the oldest commit and only commit if an attacker is not attacking this wallet. If an attacker is front-running commits, the first entry may be from the attacker, but its timestamp should be identical to the user's commit (or close enough to the user's commit, if network is a bit congested) Commit storage c = cc[0]; unchecked { if (c.timestamp >= bt - REVEAL_MAX_DELAY) { break; } } } // Now `timelyIndex` holds the index of the first commit that is timely. All commits at an index less than `timelyIndex` must be deleted; if (timelyIndex == 0) { // no commit is older than block.timestamp - REVEAL_MAX_DELAY. Nothing needs to be cleaned up return; } // Delete Commit instances for commits that are are older than block.timestamp - REVEAL_MAX_DELAY for (uint32 i = 0; i < timelyIndex; i++) { bytes32 hash = commitState.commits[i]; Commit[] storage cc = commitState.commitLocker[hash]; for (uint32 j = 0; j < cc.length; j++) { delete cc[j]; } delete commitState.commitLocker[hash]; } // Shift all commit hashes up by `timelyIndex` positions, and discard `commitIndex` number of hashes at the end of the array // This process erases old commits uint32 len = uint32(commitState.commits.length); for (uint32 i = timelyIndex; i < len; i++) { unchecked{ commitState.commits[i - timelyIndex] = commitState.commits[i]; } } for (uint32 i = 0; i < timelyIndex; i++) { commitState.commits.pop(); } // TODO (@polymorpher): upgrade the above code after solidity implements proper support for struct-array memory-storage copy operation. } function getNonce(CommitState storage cs, uint8 interval) external view returns (uint8){ return cs.nonces[uint32(block.timestamp) / uint32(interval)]; } function incrementNonce(CommitState storage cs, uint32 index) external { uint8 v = cs.nonces[index]; if (v == 0) { cs.nonceTracker.push(index); } unchecked{ cs.nonces[index] = v + 1; } } /// This function removes all tracked nonce values correspond to interval blocks that are older than block.timestamp - REVEAL_MAX_DELAY. In doing so, extraneous data in the blockchain is removed, and both nonces and nonceTracker are bounded in size. function cleanupNonces(CommitState storage cs, uint8 interval) external { uint32 tMin = uint32(block.timestamp) - REVEAL_MAX_DELAY; uint32 indexMin = tMin / interval; uint32[] memory nonZeroNonces = new uint32[](cs.nonceTracker.length); uint32 numValidIndices = 0; for (uint8 i = 0; i < cs.nonceTracker.length; i++) { uint32 index = cs.nonceTracker[i]; if (index < indexMin) { delete cs.nonces[index]; } else { nonZeroNonces[numValidIndices] = index; unchecked { numValidIndices++; } } } // TODO (@polymorpher): This can be later made more efficient by inline assembly. https://ethereum.stackexchange.com/questions/51891/how-to-pop-from-decrease-the-length-of-a-memory-array-in-solidity uint32[] memory reducedArray = new uint32[](numValidIndices); for (uint8 i = 0; i < numValidIndices; i++) { reducedArray[i] = nonZeroNonces[i]; } cs.nonceTracker = reducedArray; } }
library CommitManager { uint32 constant REVEAL_MAX_DELAY = 60; struct Commit { bytes32 paramsHash; bytes32 verificationHash; uint32 timestamp; bool completed; } struct CommitState { mapping(bytes32 => Commit[]) commitLocker; bytes32[] commits; // self-clean on commit (auto delete commits that are beyond REVEAL_MAX_DELAY), so it's bounded by the number of commits an attacker can spam within REVEAL_MAX_DELAY time in the worst case, which is not too bad. /// nonce tracking mapping(uint32 => uint8) nonces; // keys: otp index (=timestamp in seconds / interval); values: the expected nonce for that otp interval. An reveal with a nonce less than the expected value will be rejected uint32[] nonceTracker; // list of nonces keys that have a non-zero value. keys cannot possibly result a successful reveal (indices beyond REVEAL_MAX_DELAY old) are auto-deleted during a clean up procedure that is called every time the nonces are incremented for some key. For each deleted key, the corresponding key in nonces will also be deleted. So the size of nonceTracker and nonces are both bounded. } function getNumCommits(CommitState storage cs) view public returns (uint32){ uint32 numCommits = 0; for (uint32 i = 0; i < cs.commits.length; i++) { numCommits += uint32(cs.commitLocker[cs.commits[i]].length); } return numCommits; } function _getCommitHashes(CommitState storage cs, uint32 numCommits) internal view returns (bytes32[] memory){ bytes32[] memory hashes = new bytes32[](numCommits); uint32 index = 0; for (uint32 i = 0; i < cs.commits.length; i++) { Commit[] storage cc = cs.commitLocker[cs.commits[i]]; for (uint32 j = 0; j < cc.length; j++) { hashes[index] = cs.commits[i]; index++; } } return hashes; } function _getCommitParamHashes(CommitState storage cs, uint32 numCommits) internal view returns (bytes32[] memory){ bytes32[] memory paramHashes = new bytes32[](numCommits); uint32 index = 0; for (uint32 i = 0; i < cs.commits.length; i++) { Commit[] storage cc = cs.commitLocker[cs.commits[i]]; for (uint32 j = 0; j < cc.length; j++) { Commit storage c = cc[j]; paramHashes[index] = c.paramsHash; index++; } } return paramHashes; } function _getVerificationHashes(CommitState storage cs, uint32 numCommits) internal view returns (bytes32[] memory){ bytes32[] memory verificationHashes = new bytes32[](numCommits); uint32 index = 0; for (uint32 i = 0; i < cs.commits.length; i++) { Commit[] storage cc = cs.commitLocker[cs.commits[i]]; for (uint32 j = 0; j < cc.length; j++) { Commit storage c = cc[j]; verificationHashes[index] = c.verificationHash; index++; } } return verificationHashes; } function _getTimestamps(CommitState storage cs, uint32 numCommits) internal view returns (uint32[] memory){ uint32[] memory timestamps = new uint32[](numCommits); uint32 index = 0; for (uint32 i = 0; i < cs.commits.length; i++) { Commit[] storage cc = cs.commitLocker[cs.commits[i]]; for (uint32 j = 0; j < cc.length; j++) { Commit storage c = cc[j]; timestamps[index] = c.timestamp; index++; } } return timestamps; } function _getCompletionStatus(CommitState storage cs, uint32 numCommits) internal view returns (bool[] memory){ bool[] memory completed = new bool[](numCommits); uint32 index = 0; for (uint32 i = 0; i < cs.commits.length; i++) { Commit[] storage cc = cs.commitLocker[cs.commits[i]]; for (uint32 j = 0; j < cc.length; j++) { Commit storage c = cc[j]; completed[index] = c.completed; index++; } } return completed; } function getAllCommits(CommitState storage cs) public view returns (bytes32[] memory, bytes32[] memory, bytes32[] memory, uint32[] memory, bool[] memory){ uint32 numCommits = getNumCommits(cs); bytes32[] memory hashes = _getCommitHashes(cs, numCommits); bytes32[] memory paramHashes = _getCommitParamHashes(cs, numCommits); bytes32[] memory verificationHashes = _getVerificationHashes(cs, numCommits); uint32[] memory timestamps = _getTimestamps(cs, numCommits); bool[] memory completed = _getCompletionStatus(cs, numCommits); return (hashes, paramHashes, verificationHashes, timestamps, completed); } function lookupCommit(CommitState storage cs, bytes32 hash) external view returns (bytes32[] memory, bytes32[] memory, bytes32[] memory, uint32[] memory, bool[] memory){ Commit[] storage cc = cs.commitLocker[hash]; bytes32[] memory hashes = new bytes32[](cc.length); bytes32[] memory paramHashes = new bytes32[](cc.length); bytes32[] memory verificationHashes = new bytes32[](cc.length); uint32[] memory timestamps = new uint32[](cc.length); bool[] memory completed = new bool[](cc.length); for (uint32 i = 0; i < cc.length; i++) { Commit storage c = cc[i]; hashes[i] = hash; paramHashes[i] = c.paramsHash; verificationHashes[i] = c.verificationHash; timestamps[i] = c.timestamp; completed[i] = c.completed; } return (hashes, paramHashes, verificationHashes, timestamps, completed); } /// Remove old commits from storage, where the commit's timestamp is older than block.timestamp - REVEAL_MAX_DELAY. The purpose is to remove dangling data from blockchain, and prevent commits grow unbounded. This is executed at commit time. The committer pays for the gas of this cleanup. Therefore, any attacker who intend to spam commits would be disincentivized. The attacker would not succeed in preventing any normal operation by the user. function cleanupCommits(CommitState storage commitState) external { uint32 timelyIndex = 0; uint32 bt = uint32(block.timestamp); // go through past commits chronologically, starting from the oldest, and find the first commit that is not older than block.timestamp - REVEAL_MAX_DELAY. for (; timelyIndex < commitState.commits.length; timelyIndex++) { bytes32 hash = commitState.commits[timelyIndex]; Commit[] storage cc = commitState.commitLocker[hash]; // We may skip because the commit is already cleaned up and is considered "untimely". if (cc.length == 0) { continue; } // We take the first entry in `cc` as the timestamp for all commits under commit hash `hash`, because the first entry represents the oldest commit and only commit if an attacker is not attacking this wallet. If an attacker is front-running commits, the first entry may be from the attacker, but its timestamp should be identical to the user's commit (or close enough to the user's commit, if network is a bit congested) Commit storage c = cc[0]; unchecked { if (c.timestamp >= bt - REVEAL_MAX_DELAY) { break; } } } // Now `timelyIndex` holds the index of the first commit that is timely. All commits at an index less than `timelyIndex` must be deleted; if (timelyIndex == 0) { // no commit is older than block.timestamp - REVEAL_MAX_DELAY. Nothing needs to be cleaned up return; } // Delete Commit instances for commits that are are older than block.timestamp - REVEAL_MAX_DELAY for (uint32 i = 0; i < timelyIndex; i++) { bytes32 hash = commitState.commits[i]; Commit[] storage cc = commitState.commitLocker[hash]; for (uint32 j = 0; j < cc.length; j++) { delete cc[j]; } delete commitState.commitLocker[hash]; } // Shift all commit hashes up by `timelyIndex` positions, and discard `commitIndex` number of hashes at the end of the array // This process erases old commits uint32 len = uint32(commitState.commits.length); for (uint32 i = timelyIndex; i < len; i++) { unchecked{ commitState.commits[i - timelyIndex] = commitState.commits[i]; } } for (uint32 i = 0; i < timelyIndex; i++) { commitState.commits.pop(); } // TODO (@polymorpher): upgrade the above code after solidity implements proper support for struct-array memory-storage copy operation. } function getNonce(CommitState storage cs, uint8 interval) external view returns (uint8){ return cs.nonces[uint32(block.timestamp) / uint32(interval)]; } function incrementNonce(CommitState storage cs, uint32 index) external { uint8 v = cs.nonces[index]; if (v == 0) { cs.nonceTracker.push(index); } unchecked{ cs.nonces[index] = v + 1; } } /// This function removes all tracked nonce values correspond to interval blocks that are older than block.timestamp - REVEAL_MAX_DELAY. In doing so, extraneous data in the blockchain is removed, and both nonces and nonceTracker are bounded in size. function cleanupNonces(CommitState storage cs, uint8 interval) external { uint32 tMin = uint32(block.timestamp) - REVEAL_MAX_DELAY; uint32 indexMin = tMin / interval; uint32[] memory nonZeroNonces = new uint32[](cs.nonceTracker.length); uint32 numValidIndices = 0; for (uint8 i = 0; i < cs.nonceTracker.length; i++) { uint32 index = cs.nonceTracker[i]; if (index < indexMin) { delete cs.nonces[index]; } else { nonZeroNonces[numValidIndices] = index; unchecked { numValidIndices++; } } } // TODO (@polymorpher): This can be later made more efficient by inline assembly. https://ethereum.stackexchange.com/questions/51891/how-to-pop-from-decrease-the-length-of-a-memory-array-in-solidity uint32[] memory reducedArray = new uint32[](numValidIndices); for (uint8 i = 0; i < numValidIndices; i++) { reducedArray[i] = nonZeroNonces[i]; } cs.nonceTracker = reducedArray; } }
20,592
26
// Update currency manager _currencyManager new currency manager address /
function updateCurrencyManager(address _currencyManager) external onlyOwner { require(_currencyManager != address(0), "Owner: Cannot be null address"); currencyManager = ICurrencyManager(_currencyManager); emit NewCurrencyManager(_currencyManager); }
function updateCurrencyManager(address _currencyManager) external onlyOwner { require(_currencyManager != address(0), "Owner: Cannot be null address"); currencyManager = ICurrencyManager(_currencyManager); emit NewCurrencyManager(_currencyManager); }
14,484
82
// Give this contract 6000 Tellor Tributes so that it can stake the initial 6 miners
TellorTransfer.updateBalanceAtNow(self.balances[address(this)], 2**256 - 1 - 6000e18);
TellorTransfer.updateBalanceAtNow(self.balances[address(this)], 2**256 - 1 - 6000e18);
26,759
30
// Withdraw deposits that haven't been used.
function withdraw(address _contractAddress) external nonReentrant contractExist(_contractAddress)
function withdraw(address _contractAddress) external nonReentrant contractExist(_contractAddress)
9,558
0
// Max slippage percent allowed
uint256 public constant override MAX_SLIPPAGE_PERCENT = 3000; // 30%
uint256 public constant override MAX_SLIPPAGE_PERCENT = 3000; // 30%
60,582
3
// Emitted when the existing owner is verified node node name hash /
event NodeVerified( bytes32 node );
event NodeVerified( bytes32 node );
34,868
29
// sets boundaries for incoming tx/
modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; }
modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; }
24,136
187
// The maximum number of synths issuable for this amount of collateral
function maxLoan(uint amount, bytes32 currency) public view returns (uint max) { max = issuanceRatio().multiplyDecimal(_exchangeRates().effectiveValue(collateralKey, amount, currency)); }
function maxLoan(uint amount, bytes32 currency) public view returns (uint max) { max = issuanceRatio().multiplyDecimal(_exchangeRates().effectiveValue(collateralKey, amount, currency)); }
47,795
27
// 0x11: The script contains too many calls.
ScriptTooManyCalls,
ScriptTooManyCalls,
24,479
22
// Divide [prod1 prod0] by lpotdod.
prod0 := div(prod0, lpotdod)
prod0 := div(prod0, lpotdod)
29,875
0
// IAtestor _atestator,
IToken _collateralToken, IToken _loanToken, address _borrower, uint256 _amountWanted, uint16 _interestPermil, uint64 _fundraisingDeadline, uint64 _paybackDeadline ) public
IToken _collateralToken, IToken _loanToken, address _borrower, uint256 _amountWanted, uint16 _interestPermil, uint64 _fundraisingDeadline, uint64 _paybackDeadline ) public
17,172
48
// Calculates the rate based on slabs
function fetchRate() constant returns (uint256){ if( block0 <= block.number && block1 > block.number ){ applicableRate = 1500000000000; return applicableRate; } if ( block1 <= block.number && block2 > block.number ){ applicableRate = 1400000000000; return applicableRate; } if ( block2 <= block.number && block3 > block.number ){ applicableRate = 1300000000000; return applicableRate; } if ( block3 <= block.number && block4 > block.number ){ applicableRate = 1200000000000; return applicableRate; } if ( block4 <= block.number && block5 > block.number ){ applicableRate = 1100000000000; return applicableRate; } if ( block5 <= block.number && block6 > block.number ){ applicableRate = 1000000000000; return applicableRate; } }
function fetchRate() constant returns (uint256){ if( block0 <= block.number && block1 > block.number ){ applicableRate = 1500000000000; return applicableRate; } if ( block1 <= block.number && block2 > block.number ){ applicableRate = 1400000000000; return applicableRate; } if ( block2 <= block.number && block3 > block.number ){ applicableRate = 1300000000000; return applicableRate; } if ( block3 <= block.number && block4 > block.number ){ applicableRate = 1200000000000; return applicableRate; } if ( block4 <= block.number && block5 > block.number ){ applicableRate = 1100000000000; return applicableRate; } if ( block5 <= block.number && block6 > block.number ){ applicableRate = 1000000000000; return applicableRate; } }
28,103
41
// Update the allow list on SeaDrop.
ISeaDrop(seaDropImpl).updateAllowList(allowListData);
ISeaDrop(seaDropImpl).updateAllowList(allowListData);
21,795
112
// call setProvider from there
if(!c4fec.setOwner(newOwner)) revert(); contractOwnerChanged(C4Fcontract,newOwner); return true;
if(!c4fec.setOwner(newOwner)) revert(); contractOwnerChanged(C4Fcontract,newOwner); return true;
39,103
1
// TODO: specify event to be emitted on transfer
event ToSend(address indexed _from, address indexed _to, uint256 _value);
event ToSend(address indexed _from, address indexed _to, uint256 _value);
1,160
21
// release the locked tokens owned by an account, which only have only one locked timeand don't have release stage._target the account address that hold an amount of locked tokens _tk the erc20 token need to be transferred /
function releaseAccount(address _target, address _tk) onlyOwner public returns (bool) { require(_tk != address(0)); if (!lockedStorage.isExisted(_target)) { return false; } if (lockedStorage.lockedStagesNum(_target) == 1 && lockedStorage.endTimeOfStage(_target, 0) == lockedStorage.releaseEndTimeOfStage(_target, 0) && lockedStorage.endTimeOfStage(_target, 0) > 0 && now >= lockedStorage.endTimeOfStage(_target, 0)) { uint256 releasedAmount = lockedStorage.amountOfStage(_target, 0); // remove current release period time record if (!lockedStorage.removeLockedTime(_target, 0)) { return false; } // remove the froze account if (!lockedStorage.removeAccount(_target)) { return false; } releaseTokens(_target, _tk, releasedAmount); emit ReleaseFunds(_target, releasedAmount); } // if the account are not locked for once, we will do nothing here return true; }
function releaseAccount(address _target, address _tk) onlyOwner public returns (bool) { require(_tk != address(0)); if (!lockedStorage.isExisted(_target)) { return false; } if (lockedStorage.lockedStagesNum(_target) == 1 && lockedStorage.endTimeOfStage(_target, 0) == lockedStorage.releaseEndTimeOfStage(_target, 0) && lockedStorage.endTimeOfStage(_target, 0) > 0 && now >= lockedStorage.endTimeOfStage(_target, 0)) { uint256 releasedAmount = lockedStorage.amountOfStage(_target, 0); // remove current release period time record if (!lockedStorage.removeLockedTime(_target, 0)) { return false; } // remove the froze account if (!lockedStorage.removeAccount(_target)) { return false; } releaseTokens(_target, _tk, releasedAmount); emit ReleaseFunds(_target, releasedAmount); } // if the account are not locked for once, we will do nothing here return true; }
28,286
19
// Returns most recent expired block. Know if the block number use with generateRandomNumberis actually the hash that generates the number. /
contract Fresh is SafeMath { function expiredBlock() internal constant returns(uint) { uint256 expired = block.number; if (expired > 256) { expired = sub(expired, 256); } return expired; } }
contract Fresh is SafeMath { function expiredBlock() internal constant returns(uint) { uint256 expired = block.number; if (expired > 256) { expired = sub(expired, 256); } return expired; } }
35,652
17
// MUTUAL UPGRADE: Update the SetToken manager address. Operator and Methodologist must each callthis function to execute the update._newManager New manager address /
function setManager(address _newManager) external mutualUpgrade(operator, methodologist) { require(_newManager != address(0), "Zero address not valid"); setToken.setManager(_newManager); }
function setManager(address _newManager) external mutualUpgrade(operator, methodologist) { require(_newManager != address(0), "Zero address not valid"); setToken.setManager(_newManager); }
64,720
34
// Fetch all the posts created accross users/ return The list of post records
function getAllPosts() view external returns (Post[] memory)
function getAllPosts() view external returns (Post[] memory)
23,051
166
// Clear the active portfolio active flags and they will be recalculated in the next step
accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies); uint256 lastCurrency; while (portfolioCurrencies != 0) {
accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies); uint256 lastCurrency; while (portfolioCurrencies != 0) {
64,900
105
// Returns deposited amount in USD.If deposit failed return zeroreturn Returns deposited amount in USD. amounts - amounts in stablecoins that user deposit /
function deposit(uint256[3] memory amounts) external returns (uint256) { if (!checkDepositSuccessful(amounts)) { return 0; } uint256 poolLPs = depositPool(amounts); return (poolLPs * getCurvePoolPrice()) / CURVE_PRICE_DENOMINATOR; }
function deposit(uint256[3] memory amounts) external returns (uint256) { if (!checkDepositSuccessful(amounts)) { return 0; } uint256 poolLPs = depositPool(amounts); return (poolLPs * getCurvePoolPrice()) / CURVE_PRICE_DENOMINATOR; }
9,884
14
// Sets a new owner for the wallet. _newOwner The new owner. /
function setOwner(address _newOwner) external moduleOnly { require(_newOwner != address(0), "BW: address cannot be null"); owner = _newOwner; emit OwnerChanged(_newOwner); }
function setOwner(address _newOwner) external moduleOnly { require(_newOwner != address(0), "BW: address cannot be null"); owner = _newOwner; emit OwnerChanged(_newOwner); }
27,416
309
// q[i] is total supply of longs[:i] and shorts[i:]
uint256[] memory q = new uint256[](numStrikes + 1); q[0] = s; uint256 max = s; uint256 sum = s;
uint256[] memory q = new uint256[](numStrikes + 1); q[0] = s; uint256 max = s; uint256 sum = s;
38,716
78
// Addresses that are able to call methods for repay and boost
mapping(address => bool) public approvedCallers;
mapping(address => bool) public approvedCallers;
975
51
// Checks whether the period in which the crowdsale is open.return Whether crowdsale period has opened /
function hasOpened() public view returns (bool) { // solium-disable-next-line security/no-block-members return (openingTime < block.timestamp && block.timestamp < closingTime); }
function hasOpened() public view returns (bool) { // solium-disable-next-line security/no-block-members return (openingTime < block.timestamp && block.timestamp < closingTime); }
10,288
143
// Admin function to change the Pause Guardian newPauseGuardian The address of the new Pause Guardianreturn uint 0=success, otherwise a failure. (See enum Error for details) /
function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, newPauseGuardian); return uint(Error.NO_ERROR); }
function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, newPauseGuardian); return uint(Error.NO_ERROR); }
43,635
255
// This function mints a new NFT/the tokenId (NFT_index is auto incremented)/destination_address addres of the underwriter of the NFT
function mintNFT(address destination_address) onlyOwner public returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(destination_address, newItemId); return newItemId; }
function mintNFT(address destination_address) onlyOwner public returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(destination_address, newItemId); return newItemId; }
10,077
30
// chainSelectors Array of chain selectors. portals Array of portal addresses corresponding to each chain selector in the chainSelectors array. The chainSelectors and portals arrays must have the same length. /
function _setChainPortals(uint64[] calldata chainSelectors, address[] calldata portals) internal { if (chainSelectors.length != portals.length) { revert ChainPortal__ArrayLengthMismatch(); } for (uint256 i; i < chainSelectors.length;) { if(!IRouterClient(i_router).isChainSupported(chainSelectors[i])){ revert IRouterClient.UnsupportedDestinationChain(chainSelectors[i]); } s_chainPortal[chainSelectors[i]] = portals[i]; unchecked { ++i; } } emit ChainPortalsChanged(chainSelectors, portals); }
function _setChainPortals(uint64[] calldata chainSelectors, address[] calldata portals) internal { if (chainSelectors.length != portals.length) { revert ChainPortal__ArrayLengthMismatch(); } for (uint256 i; i < chainSelectors.length;) { if(!IRouterClient(i_router).isChainSupported(chainSelectors[i])){ revert IRouterClient.UnsupportedDestinationChain(chainSelectors[i]); } s_chainPortal[chainSelectors[i]] = portals[i]; unchecked { ++i; } } emit ChainPortalsChanged(chainSelectors, portals); }
36,141
41
// Updates proxy implementation address of ambassadors_newAmbassadors address of new implementation contract /
function updateAmbassadors(IAmbassadors _newAmbassadors) external override onlyOwner { emit AmbassadorsUpdated(address(ambassadors), address(_newAmbassadors)); ambassadors = _newAmbassadors; }
function updateAmbassadors(IAmbassadors _newAmbassadors) external override onlyOwner { emit AmbassadorsUpdated(address(ambassadors), address(_newAmbassadors)); ambassadors = _newAmbassadors; }
24,483
79
// Calculates if user's share of wETH in the pool is creater than their deposit amts (used for potential earnings)
uint256 iTBVal = fairShare(userTokenBalances[GUILD][wETH], sharesAndLootM, initialTotalSharesAndLoot); uint256 iBase = totalDeposits.div(initialTotalSharesAndLoot).mul(sharesAndLootM); require(iTBVal.sub(iBase) >= amount, "not enough earnings to redeem this many tokens"); uint256 earningsToUser = subFees(GUILD, amount);
uint256 iTBVal = fairShare(userTokenBalances[GUILD][wETH], sharesAndLootM, initialTotalSharesAndLoot); uint256 iBase = totalDeposits.div(initialTotalSharesAndLoot).mul(sharesAndLootM); require(iTBVal.sub(iBase) >= amount, "not enough earnings to redeem this many tokens"); uint256 earningsToUser = subFees(GUILD, amount);
19,150
16
// computes square roots using the babylonian mBnbod https:en.wikipedia.org/wiki/MBnbods_of_computing_square_rootsBabylonian_mBnbod
library Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } }
library Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } }
14,267
28
// require(_amount <= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount); _callonERC1155Received(_from, _to, _id, _amount, gasleft(), _data);
_safeTransferFrom(_from, _to, _id, _amount); _callonERC1155Received(_from, _to, _id, _amount, gasleft(), _data);
26,454
30
// uint256 private _tokensaleTotalAmount = (10uint256(18)).mul(8000); 8000 obs
uint256 private _tokensaleTotalSold;
uint256 private _tokensaleTotalSold;
28,979
5
// The function takes campaign id as parameter and it is of type payable which means we can pay using our crypto wallet.
uint256 amount = msg.value; //This is what we will send from our frontend. Campaign storage campaign = campaigns[_id]; campaign.donators.push(msg.sender); //Push address of sender in donators array campaign.donations.push(amount); //Push amount that is sent by sender in donations array
uint256 amount = msg.value; //This is what we will send from our frontend. Campaign storage campaign = campaigns[_id]; campaign.donators.push(msg.sender); //Push address of sender in donators array campaign.donations.push(amount); //Push amount that is sent by sender in donations array
22,485
9
// value of user's total debt
uint256 borrowTotalValue = EasyMath.sum(borrowValues); if (borrowTotalValue == 0) return (0, 0); uint256[] memory collateralValues = getUserCollateralValues(priceProvidersRepository, _params);
uint256 borrowTotalValue = EasyMath.sum(borrowValues); if (borrowTotalValue == 0) return (0, 0); uint256[] memory collateralValues = getUserCollateralValues(priceProvidersRepository, _params);
26,922
1
// Constructor. /
constructor( address _arthContractAddres, address _arthxContractAddres, address _collateralAddress, address _creatorAddress, address _timelockAddress, address _mahaToken, address _arthMAHAOracle,
constructor( address _arthContractAddres, address _arthxContractAddres, address _collateralAddress, address _creatorAddress, address _timelockAddress, address _mahaToken, address _arthMAHAOracle,
28,611
68
// Line the bond up for next time, when it will be added to somebody's queued_funds
last_bond = bonds[i]; last_history_hash = history_hashes[i];
last_bond = bonds[i]; last_history_hash = history_hashes[i];
27,745
161
// Simple approval for operation check on token for address/spender address spending/changing token/tokenId tokenID to change / operate on
function __isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool); function __isApprovedForAll(address owner, address operator) external view returns (bool);
function __isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool); function __isApprovedForAll(address owner, address operator) external view returns (bool);
798
6
// // USER FUNCTIONS ///
function mint(uint256 quantity) external payable nonReentrant { // checks require(tx.origin == msg.sender, "smart contract not allowed"); require(publicSaleStartTime != 0, "start time not set yet"); require(block.timestamp >= publicSaleStartTime, "not started"); require(quantity > 0, "quantity cannot be 0"); require( quantity <= publicSaleMaxPurchaseAmount, "cant buy more than publicSaleMaxPurchaseAmount in each tx" ); require(quantity <= remainingCount, "sold out"); require( msg.value == mintPrice * quantity, "sent ether value incorrect" ); // effects remainingCount -= quantity; // interactions for (uint256 i = 0; i < quantity; i++) { NFT(sueiBianDAOAddress).mint(msg.sender); } }
function mint(uint256 quantity) external payable nonReentrant { // checks require(tx.origin == msg.sender, "smart contract not allowed"); require(publicSaleStartTime != 0, "start time not set yet"); require(block.timestamp >= publicSaleStartTime, "not started"); require(quantity > 0, "quantity cannot be 0"); require( quantity <= publicSaleMaxPurchaseAmount, "cant buy more than publicSaleMaxPurchaseAmount in each tx" ); require(quantity <= remainingCount, "sold out"); require( msg.value == mintPrice * quantity, "sent ether value incorrect" ); // effects remainingCount -= quantity; // interactions for (uint256 i = 0; i < quantity; i++) { NFT(sueiBianDAOAddress).mint(msg.sender); } }
44,836
21
// returns the size (the maximum number of tokens that can be minted) of an edition
function editionSize(uint256 _editionId) external view returns (uint256);
function editionSize(uint256 _editionId) external view returns (uint256);
40,267
205
// Helper function to withdraw stakes for the _msgSender() _amount uint256 The amount to withdraw. MUST match the stake amount for the stake at personalStakeIndex. _data bytes optional data to include in the Unstake event /
function withdrawStake( uint256 _amount, bytes memory _data) internal isUserCapEnabledForUnStakeFor(_amount)
function withdrawStake( uint256 _amount, bytes memory _data) internal isUserCapEnabledForUnStakeFor(_amount)
77,411
88
// Mint per mint schedule
uint256 devShare = 0; if(_currentWeek > 1){
uint256 devShare = 0; if(_currentWeek > 1){
83,775
1
// Default 80..BF range
uint256 constant internal DL = 0x80; uint256 constant internal DH = 0xBF;
uint256 constant internal DL = 0x80; uint256 constant internal DH = 0xBF;
4,030
22
// Get the token balance for account `tokenOwner`
function balanceOf(address tokenOwner) public view returns (uint balance) { return _balances[tokenOwner]; }
function balanceOf(address tokenOwner) public view returns (uint balance) { return _balances[tokenOwner]; }
17,009
21
// emits dispute ended event and then return_result to be emitted and returned_claims to be emitted and returned_validators to be emitted and returnedthis function existis to make code more clear/concise
function emitDisputeEndedAndReturn( Result _result, bytes32[2] memory _claims, address payable[2] memory _validators ) internal returns ( Result, bytes32[2] memory, address payable[2] memory
function emitDisputeEndedAndReturn( Result _result, bytes32[2] memory _claims, address payable[2] memory _validators ) internal returns ( Result, bytes32[2] memory, address payable[2] memory
31,991
44
// Force balances to match tokens that were deposited, but not sent directly to the contract./ Any excess tokens are sent to the penaltyCollector
function skim() external { require(msg.sender == tx.origin, "LaunchEvent: EOA only"); address penaltyCollector = rocketJoeFactory.penaltyCollector(); uint256 excessToken = token.balanceOf(address(this)) - tokenReserve - tokenIncentivesBalance; if (excessToken > 0) { token.safeTransfer(penaltyCollector, excessToken); } uint256 excessAvax = address(this).balance - avaxReserve; if (excessAvax > 0) { _safeTransferAVAX(penaltyCollector, excessAvax); } }
function skim() external { require(msg.sender == tx.origin, "LaunchEvent: EOA only"); address penaltyCollector = rocketJoeFactory.penaltyCollector(); uint256 excessToken = token.balanceOf(address(this)) - tokenReserve - tokenIncentivesBalance; if (excessToken > 0) { token.safeTransfer(penaltyCollector, excessToken); } uint256 excessAvax = address(this).balance - avaxReserve; if (excessAvax > 0) { _safeTransferAVAX(penaltyCollector, excessAvax); } }
37,952
46
// transfer rainbowCut to rainbow phoenix owner
userFunds[PHOENIXES[0].currentOwner] = userFunds[PHOENIXES[0].currentOwner].add(rainbowCut);
userFunds[PHOENIXES[0].currentOwner] = userFunds[PHOENIXES[0].currentOwner].add(rainbowCut);
4,277
9
// ERC20
string public name = "CryptoQuantumTradingFund"; string public symbol = "CQTF"; uint8 public decimals = 18; uint256 private fixTotalBalance = 100000000000000000000000000; uint256 private _totalBalance = 92000000000000000000000000; uint256 public creatorsLocked = 8000000000000000000000000; //创世团队当前锁定额度 address public owner = 0x0;
string public name = "CryptoQuantumTradingFund"; string public symbol = "CQTF"; uint8 public decimals = 18; uint256 private fixTotalBalance = 100000000000000000000000000; uint256 private _totalBalance = 92000000000000000000000000; uint256 public creatorsLocked = 8000000000000000000000000; //创世团队当前锁定额度 address public owner = 0x0;
47,168
2
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH());
36,337
39
// Compound 以cETH和cERC20作为抵押 进入借贷市场
function enterCompoundMarkets(address collateral_cTokenAddress) public { Comptroller comptroller = Comptroller(ComptrollerAddress); // 携带cETH和cERC20进入市场 address[] memory cTokens = new address[](2); cTokens[0] = CETHAddress; cTokens[1] = collateral_cTokenAddress; uint256[] memory errors = comptroller.enterMarkets(cTokens); if (errors[0] != 0) { revert("Comptroller.enterMarkets failed."); } }
function enterCompoundMarkets(address collateral_cTokenAddress) public { Comptroller comptroller = Comptroller(ComptrollerAddress); // 携带cETH和cERC20进入市场 address[] memory cTokens = new address[](2); cTokens[0] = CETHAddress; cTokens[1] = collateral_cTokenAddress; uint256[] memory errors = comptroller.enterMarkets(cTokens); if (errors[0] != 0) { revert("Comptroller.enterMarkets failed."); } }
12,172
12
// ========== CONVERTER ========== / Vader -> Vether Conversion Rate (1000:1)
uint256 internal constant _VADER_VETHER_CONVERSION_RATE = 1000;
uint256 internal constant _VADER_VETHER_CONVERSION_RATE = 1000;
13,821
7
// GOLDx is a token with no interest rate, so the interest rate is 0. Get the interest rate for a fixed interval time. _interval Interval time in seconds.return interest rate. /
function getFixedInterestRate(uint256 _interval) external view override returns (uint256) { _interval; return 0; }
function getFixedInterestRate(uint256 _interval) external view override returns (uint256) { _interval; return 0; }
24,310
24
// Missed Full Period! Very Bad!
PaymentHistory memory lastExecPeriod = payments[lastPeriodExecIdx]; uint256 tokensReceived = availableTokens.sub(lastExecPeriod.endBalance);
PaymentHistory memory lastExecPeriod = payments[lastPeriodExecIdx]; uint256 tokensReceived = availableTokens.sub(lastExecPeriod.endBalance);
11,250
122
// Bid for the current auction round _amount: amount of the bid in $pDust token Callable by (whitelisted) bidders /
function bid(uint256 _amount) external nonReentrant { require(bidders.contains(msg.sender), "Whitelist: Not whitelisted"); require(auctions[currentAuctionId].status == Status.Open, "Auction: Not in progress"); require(block.number > auctions[currentAuctionId].startBlock, "Auction: Too early"); require(block.number < auctions[currentAuctionId].endBlock, "Auction: Too late"); require(_amount % uint256(10**19) == uint256(0), "Bid: Incorrect amount"); if (auctionBids[currentAuctionId][msg.sender].totalAmount == 0) { require(_amount >= auctions[currentAuctionId].initialBidAmount, "Bid: Incorrect initial bid amount"); } pdustToken.safeTransferFrom(address(msg.sender), address(this), _amount); auctionBids[currentAuctionId][msg.sender].totalAmount += _amount; if (!_auctionBidders[currentAuctionId].contains(msg.sender)) { _auctionBidders[currentAuctionId].add(msg.sender); _bidderAuctions[msg.sender].push(currentAuctionId); } emit AuctionBid(currentAuctionId, msg.sender, _amount); }
function bid(uint256 _amount) external nonReentrant { require(bidders.contains(msg.sender), "Whitelist: Not whitelisted"); require(auctions[currentAuctionId].status == Status.Open, "Auction: Not in progress"); require(block.number > auctions[currentAuctionId].startBlock, "Auction: Too early"); require(block.number < auctions[currentAuctionId].endBlock, "Auction: Too late"); require(_amount % uint256(10**19) == uint256(0), "Bid: Incorrect amount"); if (auctionBids[currentAuctionId][msg.sender].totalAmount == 0) { require(_amount >= auctions[currentAuctionId].initialBidAmount, "Bid: Incorrect initial bid amount"); } pdustToken.safeTransferFrom(address(msg.sender), address(this), _amount); auctionBids[currentAuctionId][msg.sender].totalAmount += _amount; if (!_auctionBidders[currentAuctionId].contains(msg.sender)) { _auctionBidders[currentAuctionId].add(msg.sender); _bidderAuctions[msg.sender].push(currentAuctionId); } emit AuctionBid(currentAuctionId, msg.sender, _amount); }
25,462
10
// See {ICreatorCore-blacklistExtension}. /
function blacklistExtension(address extension) external override adminRequired { _blacklistExtension(extension); }
function blacklistExtension(address extension) external override adminRequired { _blacklistExtension(extension); }
27,097
109
// returns how much tokens for _amount currency/tokens and equivalents get oracle data
function getCurrencyToToken( address _oracle, uint256 _amount, bytes memory _oracleData
function getCurrencyToToken( address _oracle, uint256 _amount, bytes memory _oracleData
37,646
85
// Total amount coins/tokens that were bridged from the other side and are out of execution limits.return total amount of all bridge operations above limits. /
function outOfLimitAmount() public view returns (uint256) { return uintStorage[OUT_OF_LIMIT_AMOUNT]; }
function outOfLimitAmount() public view returns (uint256) { return uintStorage[OUT_OF_LIMIT_AMOUNT]; }
23,597
96
// Transfer the ownership of a proxy owned Safe/manager address - Safe Manager/safe uint - Safe Id/usr address - Owner of the safe
function transferSAFEOwnership( address manager, uint safe, address usr
function transferSAFEOwnership( address manager, uint safe, address usr
30,271
215
// The debt is equal to the difference between the total active and total borrowed balances.
uint256 totalActiveCurrent = getTotalActiveBalanceCurrentEpoch(); uint256 totalBorrowed = _TOTAL_BORROWED_BALANCE_; require(totalBorrowed > totalActiveCurrent, 'LS1DebtAccounting: No shortfall'); uint256 shortfallDebt = totalBorrowed.sub(totalActiveCurrent);
uint256 totalActiveCurrent = getTotalActiveBalanceCurrentEpoch(); uint256 totalBorrowed = _TOTAL_BORROWED_BALANCE_; require(totalBorrowed > totalActiveCurrent, 'LS1DebtAccounting: No shortfall'); uint256 shortfallDebt = totalBorrowed.sub(totalActiveCurrent);
30,006
57
// Stake 1 unit of each cardId
uint256[] memory amounts = new uint256[](_cardIds.length); for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; }
uint256[] memory amounts = new uint256[](_cardIds.length); for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; }
7,890
8
// The address must be empty. 비어있는 주소인 경우에만
require(address(buildingManager) == address(0)); buildingManager = DelightBuildingManager(addr);
require(address(buildingManager) == address(0)); buildingManager = DelightBuildingManager(addr);
30,235
70
// let the world know
emit Staked(msg.sender, _staker, _amount);
emit Staked(msg.sender, _staker, _amount);
48,618