function
stringlengths
12
63.3k
severity
stringclasses
4 values
```\njusdOutside[msg.sender] -= repayJUSDAmount;\nuint256 index = getIndex();\nuint256 lockedEarnUSDCAmount = jusdOutside[msg.sender].decimalDiv(index);\nrequire(\n earnUSDCBalance[msg.sender] >= lockedEarnUSDCAmount, "lockedEarnUSDCAmount is bigger than earnUSDCBalance"\n);\nwithdrawEarnUSDCAmount = earnUSDCBalance[msg.sender] - lockedEarnUSDCAmount;\n```\n
high
```\nconstructor(address owner) {\n _owner = owner;\n isAuthorized[owner] = true;\n}\n```\n
none
```\nfunction simulateValidation(UserOperation calldata userOp) external {\n UserOpInfo memory outOpInfo;\n\n _simulationOnlyValidations(userOp);\n (uint256 validationData, uint256 paymasterValidationData) = _validatePrepayment(0, userOp, outOpInfo);\n StakeInfo memory paymasterInfo = _getStakeInfo(outOpInfo.mUserOp.paymaster);\n StakeInfo memory senderInfo = _getStakeInfo(outOpInfo.mUserOp.sender);\n StakeInfo memory factoryInfo;\n {\n bytes calldata initCode = userOp.initCode;\n address factory = initCode.length >= 20 ? address(bytes20(initCode[0 : 20])) : address(0);\n factoryInfo = _getStakeInfo(factory);\n }\n\n ValidationData memory data = _intersectTimeRange(validationData, paymasterValidationData);\n address aggregator = data.aggregator;\n bool sigFailed = aggregator == address(1);\n ReturnInfo memory returnInfo = ReturnInfo(outOpInfo.preOpGas, outOpInfo.prefund,\n sigFailed, data.validAfter, data.validUntil, getMemoryBytesFromOffset(outOpInfo.contextOffset));\n\n if (aggregator != address(0) && aggregator != address(1)) {\n AggregatorStakeInfo memory aggregatorInfo = AggregatorStakeInfo(aggregator, _getStakeInfo(aggregator));\n revert ValidationResultWithAggregation(returnInfo, senderInfo, factoryInfo, paymasterInfo, aggregatorInfo);\n }\n revert ValidationResult(returnInfo, senderInfo, factoryInfo, paymasterInfo);\n\n}\n```\n
none
```\nfunction tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n}\n```\n
none
```\n wAuraPools.getVault(lpToken).exitPool(\n IBalancerPool(lpToken).getPoolId(),\n address(this),\n address(this),\n IBalancerVault.ExitPoolRequest(\n tokens,\n minAmountsOut,\n abi.encode(0, amountPosRemove, borrowTokenIndex),\n false\n )\n );\n }\n }\n\n /// 4. Swap each reward token for the debt token\n uint256 rewardTokensLength = rewardTokens.length;\n for (uint256 i; i != rewardTokensLength; ) {\n address sellToken = rewardTokens[i];\n if (sellToken == STASH_AURA) sellToken = AURA;\n\n _doCutRewardsFee(sellToken);\n```\n
medium
```\n // Need to transfer before minting or ERC777s could reenter.\n asset.safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n}\n\n function previewMint(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n}\n```\n
high
```\nfunction setFeesBuy(\n uint256 _marketingFee,\n uint256 _devFee\n) external onlyOwner {\n buyMarketingTax = _marketingFee;\n buyProjectTax = _devFee;\n buyTaxTotal = buyMarketingTax + buyProjectTax;\n require(buyTaxTotal <= 100, "Total buy fee cannot be higher than 100%");\n emit BuyFeeUpdated(buyTaxTotal, buyMarketingTax, buyProjectTax);\n}\n```\n
none
```\nFile: VaultAccount.sol\n function _setVaultAccount(\n..SNIP..\n // An account must maintain a minimum borrow size in order to enter the vault. If the account\n // wants to exit under the minimum borrow size it must fully exit so that we do not have dust\n // accounts that become insolvent.\n if (\n vaultAccount.accountDebtUnderlying.neg() < vaultConfig.minAccountBorrowSize &&\n // During local currency liquidation and settlement, the min borrow check is skipped\n checkMinBorrow\n ) {\n // NOTE: use 1 to represent the minimum amount of vault shares due to rounding in the\n // vaultSharesToLiquidator calculation\n require(vaultAccount.accountDebtUnderlying == 0 || vaultAccount.vaultShares <= 1, "Min Borrow");\n }\n```\n
medium
```\nfunction beginGlobalSettlement(uint256 price) public onlyWhitelistAdmin {\n require(status != LibTypes.Status.SETTLED, "already settled");\n settlementPrice = price;\n status = LibTypes.Status.SETTLING;\n emit BeginGlobalSettlement(price);\n}\n```\n
low
```\nfor (uint256 i = 0; i < tokens.length; i++) {\n uint256 amountToRagequit = fairShare(userTokenBalances[GUILD][tokens[i]], sharesAndLootToBurn, initialTotalSharesAndLoot);\n // deliberately not using safemath here to keep overflows from preventing the function execution (which would break ragekicks)\n // if a token overflows, it is because the supply was artificially inflated to oblivion, so we probably don't care about it anyways\n userTokenBalances[GUILD][tokens[i]] -= amountToRagequit;\n userTokenBalances[memberAddress][tokens[i]] += amountToRagequit;\n}\n```\n
high
```\nstakedToken.transferFrom(from, address(this), amount);\n```\n
medium
```\n /**\n * Calculate total notional rebalance quantity and chunked rebalance quantity in collateral units.\n *\n * return uint256 Chunked rebalance notional in collateral units\n * return uint256 Total rebalance notional in collateral units\n */\n function _calculateChunkRebalanceNotional(\n LeverageInfo memory _leverageInfo,\n uint256 _newLeverageRatio,\n bool _isLever\n )\n internal\n view\n returns (uint256, uint256)\n {\n // Calculate absolute value of difference between new and current leverage ratio\n uint256 leverageRatioDifference = _isLever ? _newLeverageRatio.sub(_leverageInfo.currentLeverageRatio) : _leverageInfo.currentLeverageRatio.sub(_newLeverageRatio);\n\n uint256 totalRebalanceNotional = leverageRatioDifference.preciseDiv(_leverageInfo.currentLeverageRatio).preciseMul(_leverageInfo.action.collateralBalance);\n\n uint256 maxBorrow = _calculateMaxBorrowCollateral(_leverageInfo.action, _isLever);\n\n uint256 chunkRebalanceNotional = Math.min(Math.min(maxBorrow, totalRebalanceNotional), _leverageInfo.twapMaxTradeSize);\n\n return (chunkRebalanceNotional, totalRebalanceNotional);\n }\n\n /**\n * Calculate the max borrow / repay amount allowed in base units for lever / delever. This is due to overcollateralization requirements on\n * assets deposited in lending protocols for borrowing.\n *\n * For lever, max borrow is calculated as:\n * (Net borrow limit in USD - existing borrow value in USD) / collateral asset price adjusted for decimals\n *\n * For delever, max repay is calculated as:\n * Collateral balance in base units * (net borrow limit in USD - existing borrow value in USD) / net borrow limit in USD\n *\n * Net borrow limit for levering is calculated as:\n * The collateral value in USD * Aave collateral factor * (1 - unutilized leverage %)\n *\n * Net repay limit for delevering is calculated as:\n * The collateral value in USD * Aave liquiditon threshold * (1 - unutilized leverage %)\n *\n * return uint256 Max borrow notional denominated in collateral asset\n */\n function _calculateMaxBorrowCollateral(ActionInfo memory _actionInfo, bool _isLever) internal view returns(uint256) {\n\n // Retrieve collateral factor and liquidation threshold for the collateral asset in precise units (1e16 = 1%)\n ( , uint256 maxLtvRaw, uint256 liquidationThresholdRaw, , , , , , ,) = strategy.aaveProtocolDataProvider.getReserveConfigurationData(address(strategy.collateralAsset));\n\n // Normalize LTV and liquidation threshold to precise units. LTV is measured in 4 decimals in Aave which is why we must multiply by 1e14\n // for example ETH has an LTV value of 8000 which represents 80%\n if (_isLever) {\n uint256 netBorrowLimit = _actionInfo.collateralValue\n .preciseMul(maxLtvRaw.mul(10 ** 14))\n .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));\n\n return netBorrowLimit\n .sub(_actionInfo.borrowValue)\n .preciseDiv(_actionInfo.collateralPrice);\n } else {\n uint256 netRepayLimit = _actionInfo.collateralValue\n .preciseMul(liquidationThresholdRaw.mul(10 ** 14))\n .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));\n\n return _actionInfo.collateralBalance\n .preciseMul(netRepayLimit.sub(_actionInfo.borrowValue))\n .preciseDiv(netRepayLimit);\n }\n }\n```\n
medium
```\nfunction transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {\n _transfer(sender, recipient, amount);\n _approve(sender,_msgSender(),_allowances[sender][_msgSender()].sub(amount,"ERC20: transfer amount exceeds allowance"));\n return true;\n}\n```\n
none
```\nif (sqrtRatioX96 <= sqrtRatioAX96) {\n amount0 = SafeCast.toUint256(\n SqrtPriceMath.getAmount0Delta(\n sqrtRatioAX96,\n sqrtRatioBX96,\n liquidity\n )\n );\n} \n```\n
medium
```\nfunction sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return sub(a, b, "SafeMath: subtraction overflow");\n}\n```\n
none
```\n function findOrderHintId(\n mapping(address => mapping(uint16 => STypes.Order)) storage orders,\n address asset,\n MTypes.OrderHint[] memory orderHintArray\n ) internal returns (uint16 hintId) {\n\n // more code\n\n // @audit if a reused order's prevOrderType is matched, returns HEAD\n\n if (hintOrderType == O.Cancelled || hintOrderType == O.Matched) {\n emit Events.FindOrderHintId(0);\n continue;\n } else if (\n orders[asset][orderHint.hintId].creationTime == orderHint.creationTime\n ) {\n emit Events.FindOrderHintId(1);\n return orderHint.hintId;\n } else if (orders[asset][orderHint.hintId].prevOrderType == O.Matched) {\n //@dev If hint was prev matched, it means that the hint was close to HEAD and therefore is reasonable to use HEAD\n emit Events.FindOrderHintId(2);\n return Constants.HEAD;\n }\n```\n
medium
```\nfunction _isLess(Queue storage self, uint256 i, uint256 j) private view returns (bool) {\n uint64 iId = self.bidIdList[i];\n uint64 jId = self.bidIdList[j];\n Bid memory bidI = self.idToBidMap[iId];\n Bid memory bidJ = self.idToBidMap[jId];\n uint256 relI = uint256(bidI.amountIn) * uint256(bidJ.minAmountOut);\n uint256 relJ = uint256(bidJ.amountIn) * uint256(bidI.minAmountOut);\n if (relI == relJ) {\n return iId > jId;\n }\n return relI < relJ;\n}\n```\n
high
```\nfunction setDepositExclusion(address \_deposit, bool \_excluded) external onlyGuardianOrGovernor {\n excludedDeposits[\_deposit] = \_excluded;\n}\n```\n
low
```\nfunction changeIsFeeExempt(address holder, bool exempt) external onlyOwner {\n isFeeExempt[holder] = exempt;\n}\n```\n
none
```\n function _redeem(\n ThreeTokenPoolContext memory poolContext,\n StrategyContext memory strategyContext,\n AuraStakingContext memory stakingContext,\n uint256 strategyTokens,\n uint256 minPrimary\n) internal returns (uint256 finalPrimaryBalance) {\n uint256 bptClaim = strategyContext._convertStrategyTokensToBPTClaim(strategyTokens);\n\n\n if (bptClaim == 0) return 0;\n\n\n finalPrimaryBalance = _unstakeAndExitPool({\n stakingContext: stakingContext,\n poolContext: poolContext,\n bptClaim: bptClaim,\n minPrimary: minPrimary\n });\n\n\n strategyContext.vaultState.totalBPTHeld -= bptClaim;\n strategyContext.vaultState.totalStrategyTokenGlobal -= strategyTokens.toUint80();\n strategyContext.vaultState.setStrategyVaultState(); \n}\n```\n
medium
```\n function getAccountPrimeDebtBalance(uint16 currencyId, address account) external view override returns (\n int256 debtBalance\n ) {\n mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();\n BalanceStorage storage balanceStorage = store[account][currencyId];\n int256 cashBalance = balanceStorage.cashBalance;\n\n // Only return cash balances less than zero\n debtBalance = cashBalance < 0 ? debtBalance : 0; //<------@audit wrong, Always return 0\n }\n```\n
medium
```\nFile: contracts\gas\GasUtils.sol\n function payExecutionFee(\n DataStore dataStore,\n EventEmitter eventEmitter,\n StrictBank bank,\n uint256 executionFee,\n uint256 startingGas,\n address keeper,\n address user\n ) external { // @audit external call is subject to EIP// Remove the line below\n150\n// Remove the line below\n uint256 gasUsed = startingGas // Remove the line below\n gasleft();\n// Add the line below\n uint256 gasUsed = startingGas // Remove the line below\n gasleft() * 64 / 63; // @audit the correct formula\n uint256 executionFeeForKeeper = adjustGasUsage(dataStore, gasUsed) * tx.gasprice;\n\n if (executionFeeForKeeper > executionFee) {\n executionFeeForKeeper = executionFee;\n }\n\n bank.transferOutNativeToken(\n keeper,\n executionFeeForKeeper\n );\n\n emitKeeperExecutionFee(eventEmitter, keeper, executionFeeForKeeper);\n\n uint256 refundFeeAmount = executionFee // Remove the line below\n executionFeeForKeeper;\n if (refundFeeAmount == 0) {\n return;\n }\n\n bank.transferOutNativeToken(\n user,\n refundFeeAmount\n );\n\n emitExecutionFeeRefund(eventEmitter, user, refundFeeAmount);\n }\n```\n
medium
```\nfunction allowance(address holder, address spender)\n external\n view\n override\n returns (uint256)\n{\n return _allowances[holder][spender];\n}\n```\n
none
```\n uint256 ohmWstethPrice = manager.getOhmTknPrice();\n uint256 ohmMintAmount = (amount_ * ohmWstethPrice) / _WSTETH_DECIMALS;\n\n // Block scope to avoid stack too deep\n {\n // Cache OHM-wstETH BPT before\n uint256 bptBefore = liquidityPool.balanceOf(address(this));\n\n // Transfer in wstETH\n wsteth.safeTransferFrom(msg.sender, address(this), amount_);\n\n // Mint OHM\n manager.mintOhmToVault(ohmMintAmount);\n\n // Join Balancer pool\n _joinBalancerPool(ohmMintAmount, amount_, minLpAmount_);\n```\n
high
```\nfunction decimals() public pure override returns (uint8) {\n return 6;\n}\n```\n
low
```\nSTATICCALL IchiLpOracle.getPrice(token=0xFCFE742e19790Dd67a627875ef8b45F17DB1DaC6) => (1101189125194558706411110851447)\n```\n
medium
```\n \*/\nfunction setIDOLContract(address contractAddress) public {\n require(address(\_IDOLContract) == address(0), "IDOL contract is already registered");\n \_setStableCoinContract(contractAddress);\n}\n```\n
high
```\nfunction verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n```\n
none
```\nfunction changeMintCost(uint256 mintCost) public onlyOwner {\n require(\n mintCost != _mintPrice,\n "DCBW721: mint Cost cannot be same as previous"\n );\n _mintPrice = mintCost;\n}\n```\n
none
```\n bytes memory encodedMessage = abi.encodePacked( LSP6_VERSION,\n block.chainid,\n nonce,\n msgValue,\n payload\n );\n```\n
low
```\n uint256 deltaExchangeRateMantissa = uint256(exchangeRateMantissa).sub(userState.lastExchangeRateMantissa);\n uint128 newTokens = FixedPoint.multiplyUintByMantissa(userMeasureBalance, deltaExchangeRateMantissa).toUint128();\n userStates[user] = UserState({\n lastExchangeRateMantissa: exchangeRateMantissa,\n balance: uint256(userState.balance).add(newTokens).toUint128()\n });\n```\n
low
```\nFile: LMPDebt.sol\n // Neither of these numbers include rewards from the DV\n if (currentDvDebtValue < updatedDebtBasis) {\n // We are currently sitting at a loss. Limit the value we can pull from\n // the destination vault\n currentDvDebtValue = currentDvDebtValue.mulDiv(userShares, totalVaultShares, Math.Rounding.Down);\n currentDvShares = currentDvShares.mulDiv(userShares, totalVaultShares, Math.Rounding.Down);\n }\n```\n
high
```\nfunction dividendOf(address _owner) public view override returns (uint256) {\n return withdrawableDividendOf(_owner);\n}\n```\n
none
```\nfunction updateSplit(\n address split,\n address[] calldata accounts,\n uint32[] calldata percentAllocations,\n uint32 distributorFee\n)\n external\n override\n onlySplitController(split)\n validSplit(accounts, percentAllocations, distributorFee)\n{\n _updateSplit(split, accounts, percentAllocations, distributorFee);\n}\n```\n
none
```\nuint256 cRatio = short.getCollateralRatioSpotPrice(LibOracle.getSavedOrSpotOraclePrice(asset));\n```\n
medium
```\nOracleVersion memory latestOracleVersion = market.oracle().latest();\nlatestPrice = latestOracleVersion.price;\nIPayoffProvider payoff = market.payoff();\nif (address(payoff) != address(0)) latestPrice = payoff.payoff(latestPrice);\n```\n
medium
```\nrocketMinipoolManager.setMinipoolWithdrawalBalances(\_minipoolAddress, \_stakingEndBalance, nodeAmount);\n// Apply node penalties by liquidating RPL stake\nif (\_stakingEndBalance < userDepositBalance) {\n RocketNodeStakingInterface rocketNodeStaking = RocketNodeStakingInterface(getContractAddress("rocketNodeStaking"));\n rocketNodeStaking.slashRPL(minipool.getNodeAddress(), userDepositBalance - \_stakingEndBalance);\n}\n```\n
high
```\nif (lockedUntil != 0 && lockedUntil <= now) {\n deposits[owner].withdrawalLockedUntil[token] = 0;\n\n address depositAccount = deposits[owner].account;\n uint256 depositValue;\n\n if (token == address(0)) {\n depositValue = depositAccount.balance;\n } else {\n depositValue = ERC20Token(token).balanceOf(depositAccount);\n }\n\n \_transferFromDeposit(\n depositAccount,\n owner,\n token,\n depositValue\n );\n\n emit DepositWithdrawn(\n depositAccount,\n owner,\n token,\n depositValue\n );\n} else {\n \_deployDepositAccount(owner);\n\n lockedUntil = now.add(depositWithdrawalLockPeriod);\n```\n
low
```\nFile: BondBaseOFDA.sol\n function _createMarket(MarketParams memory params_) internal returns (uint256) {\n..SNIP..\n // Calculate the maximum payout amount for this market\n uint256 capacity = params_.capacityInQuote\n ? params_.capacity.mulDiv(\n scale,\n price.mulDivUp(\n uint256(ONE_HUNDRED_PERCENT - params_.fixedDiscount),\n uint256(ONE_HUNDRED_PERCENT)\n )\n )\n : params_.capacity;\n market.maxPayout = capacity.mulDiv(uint256(params_.depositInterval), uint256(length));\n```\n
medium
```\nfunction distributeDividends() public payable override {\n require(totalSupply() > 0);\n\n if (msg.value > 0) {\n magnifiedDividendPerShare = magnifiedDividendPerShare.add(\n (msg.value).mul(magnitude) / totalSupply()\n );\n emit DividendsDistributed(msg.sender, msg.value);\n\n totalDividendsDistributed = totalDividendsDistributed.add(\n msg.value\n );\n }\n}\n```\n
none
```\nfunction removeAllFee() private {\n if (_taxFee == 0 && _teamFee == 0) return;\n _taxFee = 0;\n _teamFee = 0;\n}\n```\n
none
```\n (address[] memory tokens, uint256[] memory rewards) = IERC20Wrapper(\n pos.collToken\n ).pendingRewards(pos.collId, pos.collateralSize);\n for (uint256 i; i < tokens.length; i++) {\n rewardsValue += oracle.getTokenValue(tokens[i], rewards[i]);\n }\n```\n
medium
```\n struct PoolInfo {\n uint128 accRewardPerShare;\n uint64 lastRewardTime;\n uint64 allocPoint;\n```\n
medium
```\nfunction removeLimits() external onlyOwner returns (bool){\n limitsInEffect = false;\n return true;\n}\n```\n
none
```\nfunction reward(\n uint8 subjectType,\n uint256 subjectId,\n uint256 amount,\n uint256 epochNumber\n) external onlyRole(REWARDER\_ROLE) {\n if (subjectType != NODE\_RUNNER\_SUBJECT) revert InvalidSubjectType(subjectType);\n if (!\_subjectGateway.isRegistered(subjectType, subjectId)) revert RewardingNonRegisteredSubject(subjectType, subjectId);\n uint256 shareId = FortaStakingUtils.subjectToActive(getDelegatorSubjectType(subjectType), subjectId);\n \_rewardsPerEpoch[shareId][epochNumber] = amount;\n totalRewardsDistributed += amount;\n emit Rewarded(subjectType, subjectId, amount, epochNumber);\n}\n```\n
medium
```\nfunction _reflectFee(uint256 rFee, uint256 tFee) private {\n _rTotal = _rTotal - rFee;\n _tFeeTotal = _tFeeTotal + tFee;\n}\n```\n
none
```\nfunction removeBotFromBlacklist(address account) external onlyOwner() {\n require(_isBlackListedBot[account], "Account is not blacklisted");\n _isBlackListedBot[account] = false;\n}\n```\n
none
```\nbool isNative = LibAsset.isNativeAsset(assetId);\nif (!isNative) {\n LibAsset.increaseERC20Allowance(assetId, callTo, amount);\n}\n\n// Check if the callTo is a contract\nbool success;\nbytes memory returnData;\nif (Address.isContract(callTo)) {\n // Try to execute the callData\n // the low level call will return `false` if its execution reverts\n (success, returnData) = callTo.call{value: isNative ? amount : 0}(callData);\n}\n\n// Handle failure cases\nif (!success) {\n // If it fails, transfer to fallback\n LibAsset.transferAsset(assetId, fallbackAddress, amount);\n // Decrease allowance\n if (!isNative) {\n LibAsset.decreaseERC20Allowance(assetId, callTo, amount);\n }\n}\n```\n
low
```\n function currentRewardsPerToken() public view returns (uint256) {\n // Rewards do not accrue if the total balance is zero\n if (totalBalance == 0) return rewardsPerTokenStored;\n\n // @audit\n // loss of precision\n // The number of rewards to apply is based on the reward rate and the amount of time that has passed since the last reward update\n uint256 rewardsToApply = ((block.timestamp - lastRewardUpdate) * rewardRate) /\n REWARD_PERIOD;\n\n // The rewards per token is the current rewards per token plus the rewards to apply divided by the total staked balance\n return rewardsPerTokenStored + (rewardsToApply * 10 ** stakedTokenDecimals) / totalBalance;\n }\n```\n
medium
```\nfunction swapAndLiquify(uint256 tokens) private {\n uint256 half = tokens.div(2);\n uint256 otherHalf = tokens.sub(half);\n uint256 initialBalance = address(this).balance;\n swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered\n uint256 newBalance = address(this).balance.sub(initialBalance);\n addLiquidity(otherHalf, newBalance);\n emit SwapAndLiquify(half, newBalance, otherHalf);\n}\n```\n
none
```\nfunction commitCollateral(\n uint256 _bidId,\n Collateral[] calldata _collateralInfo\n) public returns (bool validation_) {\n address borrower = tellerV2.getLoanBorrower(_bidId);\n (validation_, ) = checkBalances(borrower, _collateralInfo); <- @audit-issue no access control\n\n if (validation_) {\n for (uint256 i; i < _collateralInfo.length; i++) {\n Collateral memory info = _collateralInfo[i];\n _commitCollateral(_bidId, info);\n }\n }\n}\n```\n
high
```\nif (address(quote.sellToken) != ETH) _transferFrom(permit, stake, stakeSize);\n if (address(quote.sellToken) != stake) _fillQuote(quote);\n```\n
medium
```\nfunction getWellPriceFromTwaReserves(address well) internal view returns (uint256 price) {\n AppStorage storage s = LibAppStorage.diamondStorage();\n // s.twaReserve[well] should be set prior to this function being called.\n // 'price' is in terms of reserve0:reserve1.\n if (s.twaReserves[well].reserve0 == 0) {\n price = 0;\n } else {\n price = s.twaReserves[well].reserve0.mul(1e18).div(s.twaReserves[well].reserve1);\n }\n}\n```\n
low
```\n function _poolRepayAll(address pool, address token) internal {\n .\n .\n info.totalBorrows = info.totalBorrows - amount;\n info.balance = info.balance - amount; // amount should be added here\n .\n .\n }\n```\n
high
```\n function externalSwap(\n address fromToken,\n address toToken,\n address approveTarget,\n address swapTarget,\n uint256 fromTokenAmount,\n uint256 minReturnAmount,\n bytes memory feeData,\n bytes memory callDataConcat,\n uint256 deadLine\n ) external payable judgeExpired(deadLine) returns (uint256 receiveAmount) { \n require(isWhiteListedContract[swapTarget], "DODORouteProxy: Not Whitelist Contract"); \n require(isApproveWhiteListedContract[approveTarget], "DODORouteProxy: Not Whitelist Appprove Contract"); \n\n // transfer in fromToken\n if (fromToken != _ETH_ADDRESS_) {\n // approve if needed\n if (approveTarget != address(0)) {\n IERC20(fromToken).universalApproveMax(approveTarget, fromTokenAmount);\n }\n\n IDODOApproveProxy(_DODO_APPROVE_PROXY_).claimTokens(\n fromToken,\n msg.sender,\n address(this),\n fromTokenAmount\n );\n }\n\n // swap\n uint256 toTokenOriginBalance;\n if(toToken != _ETH_ADDRESS_) {\n toTokenOriginBalance = IERC20(toToken).universalBalanceOf(address(this));\n } else {\n toTokenOriginBalance = IERC20(_WETH_).universalBalanceOf(address(this));\n }\n```\n
medium
```\nit('pending deposit pushed by 1 epoch causing shares difference', async () => {\n const smallDeposit = utils.parseEther('1000')\n const smallestDeposit = utils.parseEther('0.000001')\n\n await updateOracleEth() // epoch now stale\n // make a pending deposit\n await vault.connect(user).deposit(smallDeposit, user.address)\n await updateOracleBtc()\n await vault.sync()\n\n await updateOracleEth() // epoch now stale\n /* \n user2 deposits for user1, thereby pushing the pending deposit ahead and causing the \n global settlement flywheel and user settlement flywheel to get out of sync\n */\n await vault.connect(user2).deposit(smallestDeposit, user.address)\n await updateOracleBtc()\n await vault.sync()\n\n await updateOracle()\n // pending deposit for user1 is now processed in the user settlement flywheel\n await vault.syncAccount(user.address)\n\n const totalSupply = await vault.totalSupply()\n const balanceUser1 = await vault.balanceOf(user.address)\n const balanceUser2 = await vault.balanceOf(user2.address)\n\n /*\n totalSupply is bigger than the amount of shares of both users together\n this is because user1 loses out on some shares that he is entitled to\n -> loss of funds\n */\n console.log(totalSupply);\n console.log(balanceUser1.add(balanceUser2));\n\n})\n```\n
high
```\nfunction _fundPool(uint256 _amount, uint256 _poolId, IStrategy _strategy) internal {\n uint256 feeAmount;\n uint256 amountAfterFee = _amount;\n\n Pool storage pool = pools[_poolId];\n address _token = pool.token;\n\n if (percentFee > 0) {\n feeAmount = (_amount * percentFee) / getFeeDenominator();\n amountAfterFee -= feeAmount;\n\n _transferAmountFrom(_token, TransferData({from: msg.sender, to: treasury, amount: feeAmount}));\n }\n\n _transferAmountFrom(_token, TransferData({from: msg.sender, to: address(_strategy), amount: amountAfterFee}));\n _strategy.increasePoolAmount(amountAfterFee);\n\n emit PoolFunded(_poolId, amountAfterFee, feeAmount);\n }\n```\n
medium
```\ncontract Vault is IVault, ERC20, EpochControls, AccessControl, Pausable {\n```\n
medium
```\nfunction _qv_allocate(\n // rest of code\n ) internal onlyActiveAllocation {\n // rest of code\n uint256 creditsCastToRecipient = _allocator.voiceCreditsCastToRecipient[_recipientId];\n // rest of code\n // get the total credits and calculate the vote result\n uint256 totalCredits = _voiceCreditsToAllocate + creditsCastToRecipient;\n // rest of code\n //E update allocator mapping voice for this recipient\n _allocator.voiceCreditsCastToRecipient[_recipientId] += totalCredits; //E @question should be only _voiceCreditsToAllocate\n // rest of code\n }\n```\n
medium
```\nfunction _approve(address owner, address spender, uint256 amount) private {\n require(owner != address(0), "ERC20: approve from the zero address");\n require(spender != address(0), "ERC20: approve to the zero address");\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n}\n```\n
none
```\n\n```\n
medium
```\n uint96 prefundingRefund = routing.funding + payoutSent_ - sold_;\n unchecked {\n routing.funding -= prefundingRefund;\n }\n Transfer.transfer(\n routing.baseToken,\n _getAddressGivenCallbackBaseTokenFlag(routing.callbacks, routing.seller),\n prefundingRefund,\n false\n );\n```\n
high
```\nfunction setMaxTxPercent(uint256 maxTxPercent) external onlyOwner {\n _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**3);\n}\n```\n
none
```\nfunction tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n}\n```\n
none
```\nfunction calculatePrice() public view returns (uint256) {\n require(liquidity > 0, "No Liquidity");\n return liquidity / _balances[address(this)];\n}\n```\n
none
```\nmodifier onlyActiveState(address \_signer) {\n\n SignerInformation memory si = signerIndex[\_signer];\n require(si.stage == Stages.Active, "address is not an in3-signer");\n\n In3Node memory n = nodes[si.index];\n assert(nodes[si.index].signer == \_signer);\n \_;\n}\n```\n
low
```\nfunction restoreAllFee() private {\n _taxFee = _previousTaxFee;\n _liquidityFee = _previousLiquidityFee;\n}\n```\n
none
```\nuint256 cf = IUSSD(USSD).collateralFactor();\nuint256 flutter = 0;\nfor (flutter = 0; flutter < flutterRatios.length; flutter++) {\n if (cf < flutterRatios[flutter]) {\n break;\n }\n}\n```\n
medium
```\nfunction _getTValues(uint256 tAmount, uint256 taxFee, uint256 teamFee) private pure returns (uint256, uint256, uint256) {\n uint256 tFee = tAmount.mul(taxFee).div(100);\n uint256 tTeam = tAmount.mul(teamFee).div(100);\n uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);\n return (tTransferAmount, tFee, tTeam);\n}\n```\n
none
```\nfunction setCooldownEnabled(bool onoff) external onlyOwner() {\n cooldownEnabled = onoff;\n}\n```\n
none
```\nfunction mint(address to, uint256 _tokenId)\n external\n payable\n whenNotPaused\n requireState(DrawState.Closed)\n{\n uint256 received = msg.value;\n\n require(to != address(0), "DCBW721: Address cannot be 0");\n require(\n received == _mintPrice,\n "DCBW721: Ether sent mismatch with mint price"\n );\n\n validateTokenId(_tokenId);\n\n _safeMint(to, _tokenId);\n\n _forwardFunds(received);\n _updateReserves(_reserves.add(received.mul(_reservesRate).div(1000)));\n\n emit Minted(to, _tokenId);\n}\n```\n
none
```\n function initialize() external initializer {\n __Ownable_init();\n }\n```\n
low
```\n require(\n balance + tokenXAmount <= maxLiquidity,\n "Pool has already reached it's max limit"\n );\n```\n
medium
```\nfor (uint256 i = 0; i < \_toReset.length; i++) {\n require(\_tokenIsContractOrETH(\_toReset[i]), ERROR\_INVALID\_TOKENS);\n toReset.push(\_toReset[i]);\n}\n```\n
high
```\nfunction mul(uint256 a, uint256 b) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n uint256 c = a * b;\n require(c / a == b, "SafeMath: multiplication overflow");\n return c;\n}\n```\n
none
```\nrequire(\_startBlock > block.number, "Proposal start block must be in the future");\nrequire(\_durationBlocks > 0, "Proposal cannot have a duration of 0 blocks");\nrequire(\_expiresBlocks > 0, "Proposal cannot have a execution expiration of 0 blocks");\nrequire(\_votesRequired > 0, "Proposal cannot have a 0 votes required to be successful");\n```\n
high
```\nfunction viewRawAmount (address \_assim, int128 \_amt) internal returns (uint256 amount\_) {\n\n // amount\_ = IAssimilator(\_assim).viewRawAmount(\_amt); // for production\n\n bytes memory data = abi.encodeWithSelector(iAsmltr.viewRawAmount.selector, \_amt.abs()); // for development\n\n amount\_ = abi.decode(\_assim.delegate(data), (uint256)); // for development\n\n}\n```\n
medium
```\nfor (uint256 i = 0; i < epochNumbers.length; i++) {\n if (\_claimedRewardsPerEpoch[shareId][epochNumbers[i]][\_msgSender()]) revert AlreadyClaimed();\n \_claimedRewardsPerEpoch[shareId][epochNumbers[i]][\_msgSender()] = true;\n uint256 epochRewards = \_availableReward(shareId, isDelegator, epochNumbers[i], \_msgSender());\n SafeERC20.safeTransfer(rewardsToken, \_msgSender(), epochRewards);\n emit ClaimedRewards(subjectType, subjectId, \_msgSender(), epochNumbers[i], epochRewards);\n```\n
low
```\nl2Outputs.push(\n Types.OutputProposal({\n outputRoot: _outputRoot,\n timestamp: uint128(block.timestamp),\n l2BlockNumber: uint128(_l2BlockNumber)\n })\n );\n```\n
medium
```\nreceive() external payable {}\n```\n
none
```\nUFixed6 collateral = marketContext.currentPosition.maker\n .sub(marketContext.currentPosition.net().min(marketContext.currentPosition.maker)) // available maker\n .min(marketContext.closable.mul(StrategyLib.LEVERAGE_BUFFER)) // available closable\n .muldiv(marketContext.latestPrice.abs(), registration.leverage) // available collateral\n .muldiv(totalWeight, registration.weight); // collateral in market\n\nredemptionAssets = redemptionAssets.min(collateral);\n```\n
high
```\n function repay(uint256 repayAmount, uint256 _userLoanId) external {\n Loan memory userLoan = loans[msg.sender][_userLoanId];\n if(userLoan.borrowedAmount < repayAmount) revert ExcessiveRepay();\n if(block.timestamp > userLoan.endDate) revert LoanExpired();\n uint256 interestLoanRatio = FixedPointMathLib.divWad(userLoan.interest, userLoan.borrowedAmount);\n uint256 interest = FixedPointMathLib.mulWadUp(repayAmount, interestLoanRatio);\n outstandingDebt -= repayAmount - interest > outstandingDebt ? outstandingDebt : repayAmount - interest;\n loans[msg.sender][_userLoanId].borrowedAmount -= repayAmount;\n loans[msg.sender][_userLoanId].interest -= interest;\n poolSize += userLoan.interest * (1000 - (multisigShare + apdaoShare)) / 1000; //@audit should use interest instead of userLoan.interest\n// rest of code\n }\n```\n
high
```\nfunction deposit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n) external override {\n \_whenNotPaused();\n ReserveLogic.ReserveData storage reserve = \_reserves[asset];\n\n ValidationLogic.validateDeposit(reserve, amount);\n\n address aToken = reserve.aTokenAddress;\n\n reserve.updateState();\n reserve.updateInterestRates(asset, aToken, amount, 0);\n\n bool isFirstDeposit = IAToken(aToken).balanceOf(onBehalfOf) == 0;\n if (isFirstDeposit) {\n \_usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true);\n }\n\n IAToken(aToken).mint(onBehalfOf, amount, reserve.liquidityIndex);\n\n //transfer to the aToken contract\n IERC20(asset).safeTransferFrom(msg.sender, aToken, amount);\n\n emit Deposit(asset, msg.sender, onBehalfOf, amount, referralCode);\n}\n```\n
low
```\nFile: VaultValuation.sol\n // NOTE: deposit amount is always positive in this method\n if (depositUnderlyingInternal < maxLiquidatorDepositLocal) {\n // If liquidating past the debt outstanding above the min borrow, then the entire\n // debt outstanding must be liquidated.\n\n // (debtOutstanding - depositAmountUnderlying) is the post liquidation debt. As an\n // edge condition, when debt outstanding is discounted to present value, the account\n // may be liquidated to zero while their debt outstanding is still greater than the\n // min borrow size (which is normally enforced in notional terms -- i.e. non present\n // value). Resolving this would require additional complexity for not much gain. An\n // account within 20% of the minBorrowSize in a vault that has fCash discounting enabled\n // may experience a full liquidation as a result.\n require(\n h.debtOutstanding[currencyIndex].sub(depositUnderlyingInternal) < minBorrowSize,\n "Must Liquidate All Debt"\n );\n```\n
high
```\n for (uint256 i = 0; i < data.length; i++) {\n require(\n to[i] != address(0)\n );\n\n // solhint-disable-next-line avoid-low-level-calls\n (succeeded,) = to[i].call(abi.encodePacked(data[i], account, sender));\n\n require(\n succeeded\n );\n }\n}\n```\n
low
```\nFile:\n\n function consult(address token) public view whenNotPaused returns (int256, uint8) {\n address _feed = feeds[token];\n\n if (_feed == address(0)) revert Errors.NoTokenPriceFeedAvailable();\n\n ChainlinkResponse memory chainlinkResponse = _getChainlinkResponse(_feed);\n ChainlinkResponse memory prevChainlinkResponse = _getPrevChainlinkResponse(_feed, chainlinkResponse.roundId);//@audit incorrect way to get historical data\n if (_chainlinkIsFrozen(chainlinkResponse, token)) revert Errors.FrozenTokenPriceFeed();\n if (_chainlinkIsBroken(chainlinkResponse, prevChainlinkResponse, token)) revert Errors.BrokenTokenPriceFeed();\n\n return (chainlinkResponse.answer, chainlinkResponse.decimals);\n }\n```\n
medium
```\n function upgradeWalletType() external {\n if (!isWallet(msg.sender)) \n revert WalletDoesntExist(msg.sender); uint8 fromWalletType = _walletDataMap[msg.sender].walletType;\n _setWalletType(msg.sender, _upgradablePaths[fromWalletType]);\n emit WalletUpgraded(msg.sender, fromWalletType,\n _upgradablePaths[fromWalletType]);\n }\n```\n
medium
```\n// In the event that the majority/all of members go offline permanently and no more proposals could be passed, a current member or a regular node can 'challenge' a DAO members node to respond\n// If it does not respond in the given window, it can be removed as a member. The one who removes the member after the challenge isn't met, must be another node other than the proposer to provide some oversight\n// This should only be used in an emergency situation to recover the DAO. Members that need removing when consensus is still viable, should be done via the 'kick' method.\nfunction actionChallengeMake(address \_nodeAddress) override external onlyTrustedNode(\_nodeAddress) onlyRegisteredNode(msg.sender) onlyLatestContract("rocketDAONodeTrustedActions", address(this)) payable {\n // Load contracts\n RocketDAONodeTrustedInterface rocketDAONode = RocketDAONodeTrustedInterface(getContractAddress("rocketDAONodeTrusted"));\n RocketDAONodeTrustedSettingsMembersInterface rocketDAONodeTrustedSettingsMembers = RocketDAONodeTrustedSettingsMembersInterface(getContractAddress("rocketDAONodeTrustedSettingsMembers"));\n // Members can challenge other members for free, but for a regular bonded node to challenge a DAO member, requires non-refundable payment to prevent spamming\n if(rocketDAONode.getMemberIsValid(msg.sender) != true) require(msg.value == rocketDAONodeTrustedSettingsMembers.getChallengeCost(), "Non DAO members must pay ETH to challenge a members node");\n // Can't challenge yourself duh\n require(msg.sender != \_nodeAddress, "You cannot challenge yourself");\n // Is this member already being challenged?\n```\n
high
```\nfunction updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){\n require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");\n require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");\n swapTokensAtAmount = newAmount;\n return true;\n}\n```\n
none
```\nfunction swapToETH(uint256 _amount) internal {\n address[] memory path = new address[](2);\n path[0] = address(this);\n path[1] = uniswapRouter.WETH();\n _approve(address(this), address(uniswapRouter), _amount);\n uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(\n _amount,\n 0,\n path,\n address(this),\n block.timestamp\n );\n}\n```\n
none
```\nfunction _getRate() private view returns (uint256) {\n (uint256 rSupply, uint256 tSupply) = _getCurrentSupply();\n return rSupply.div(tSupply);\n}\n```\n
none
```\nFile: TwoTokenPoolUtils.sol\n /// @notice Returns parameters for joining and exiting Balancer pools\n function _getPoolParams(\n TwoTokenPoolContext memory context,\n uint256 primaryAmount,\n uint256 secondaryAmount,\n bool isJoin\n ) internal pure returns (PoolParams memory) {\n IAsset[] memory assets = new IAsset[](2);\n assets[context.primaryIndex] = IAsset(context.primaryToken);\n assets[context.secondaryIndex] = IAsset(context.secondaryToken);\n\n uint256[] memory amounts = new uint256[](2);\n amounts[context.primaryIndex] = primaryAmount;\n amounts[context.secondaryIndex] = secondaryAmount;\n\n uint256 msgValue;\n if (isJoin && assets[context.primaryIndex] == IAsset(Deployments.ETH_ADDRESS)) {\n msgValue = amounts[context.primaryIndex];\n }\n\n return PoolParams(assets, amounts, msgValue);\n }\n```\n
high
```\nrequire(\_isOperator(msg.sender, \_from), EC\_58\_INVALID\_OPERATOR);\n```\n
medium
```\nstruct SignerInformation {\n uint64 lockedTime; /// timestamp until the deposit of an in3-node can not be withdrawn after the node was removed\n address owner; /// the owner of the node\n\n Stages stage; /// state of the address\n\n uint depositAmount; /// amount of deposit to be locked, used only after a node had been removed\n\n uint index; /// current index-position of the node in the node-array\n}\n```\n
low
```\nfunction updateMaxWallet(uint256 newNum) external onlyOwner {\n require(\n newNum >= ((totalSupply() * 5) / 1000) / 1e18,\n "Cannot set maxWallet lower than 0.5%"\n );\n maxWallet = newNum * (10**18);\n}\n```\n
none
```\n require(msg.sender == txData.user || recoverSignature(txData.transactionId, relayerFee, "cancel", signature) == txData.user, "#C:022");\n\n Asset.transferAsset(txData.sendingAssetId, payable(msg.sender), relayerFee);\n }\n\n // Get the amount to refund the user\n uint256 toRefund;\n unchecked {\n toRefund = amount - relayerFee;\n }\n\n // Return locked funds to sending chain fallback\n if (toRefund > 0) {\n Asset.transferAsset(txData.sendingAssetId, payable(txData.sendingChainFallback), toRefund);\n }\n }\n\n} else {\n // Receiver side, router liquidity is returned\n if (txData.expiry >= block.timestamp) {\n // Timeout has not expired and tx may only be cancelled by user\n // Validate signature\n require(msg.sender == txData.user || recoverSignature(txData.transactionId, relayerFee, "cancel", signature) == txData.user, "#C:022");\n```\n
medium
```\nfunction processDepositCancellation(\n GMXTypes.Store storage self\n) external {\n GMXChecks.beforeProcessDepositCancellationChecks(self);\n // rest of code\n // Transfer requested withdraw asset to user\n IERC20(self.depositCache.depositParams.token).safeTransfer(\n self.depositCache.user,\n self.depositCache.depositParams.amt\n );\n // rest of code\n self.status = GMXTypes.Status.Open;\n\n emit DepositCancelled(self.depositCache.user);\n}\n```\n
medium
```\n function takeOverPool(GoatTypes.InitParams memory initParams) external {\n if (_vestingUntil != _MAX_UINT32) {\n revert GoatErrors.ActionNotAllowed();\n }\n\n GoatTypes.InitialLPInfo memory initialLpInfo = _initialLPInfo;\n\n GoatTypes.LocalVariables_TakeOverPool memory localVars;\n address to = msg.sender;\n localVars.virtualEthOld = _virtualEth;\n localVars.bootstrapEthOld = _bootstrapEth;\n localVars.initialTokenMatchOld = _initialTokenMatch;\n\n (localVars.tokenAmountForPresaleOld, localVars.tokenAmountForAmmOld) = _tokenAmountsForLiquidityBootstrap(\n localVars.virtualEthOld,\n localVars.bootstrapEthOld,\n initialLpInfo.initialWethAdded,\n localVars.initialTokenMatchOld\n );\n\n // new token amount for bootstrap if no swaps would have occured\n (localVars.tokenAmountForPresaleNew, localVars.tokenAmountForAmmNew) = _tokenAmountsForLiquidityBootstrap(\n initParams.virtualEth, initParams.bootstrapEth, initParams.initialEth, initParams.initialTokenMatch\n );\n\n // team needs to add min 10% more tokens than the initial lp to take over\n localVars.minTokenNeeded =\n ((localVars.tokenAmountForPresaleOld + localVars.tokenAmountForAmmOld) * 11000) / 10000;\n\n481 if ((localVars.tokenAmountForAmmNew + localVars.tokenAmountForPresaleNew) < localVars.minTokenNeeded) {\n revert GoatErrors.InsufficientTakeoverTokenAmount();\n }\n\n localVars.reserveEth = _reserveEth;\n\n // Actual token amounts needed if the reserves have updated after initial lp mint\n (localVars.tokenAmountForPresaleNew, localVars.tokenAmountForAmmNew) = _tokenAmountsForLiquidityBootstrap(\n initParams.virtualEth, initParams.bootstrapEth, localVars.reserveEth, initParams.initialTokenMatch\n );\n localVars.reserveToken = _reserveToken;\n\n // amount of tokens transferred by the new team\n uint256 tokenAmountIn = IERC20(_token).balanceOf(address(this)) - localVars.reserveToken;\n\n if (\n496 tokenAmountIn\n497 < (\n498 localVars.tokenAmountForPresaleOld + localVars.tokenAmountForAmmOld - localVars.reserveToken\n499 + localVars.tokenAmountForPresaleNew + localVars.tokenAmountForAmmNew\n500 )\n ) {\n revert GoatErrors.IncorrectTokenAmount();\n }\n\n localVars.pendingLiquidityFees = _pendingLiquidityFees;\n localVars.pendingProtocolFees = _pendingProtocolFees;\n\n // amount of weth transferred by the new team\n uint256 wethAmountIn = IERC20(_weth).balanceOf(address(this)) - localVars.reserveEth\n - localVars.pendingLiquidityFees - localVars.pendingProtocolFees;\n\n if (wethAmountIn < localVars.reserveEth) {\n revert GoatErrors.IncorrectWethAmount();\n }\n\n _handleTakeoverTransfers(\n IERC20(_weth), IERC20(_token), initialLpInfo.liquidityProvider, localVars.reserveEth, localVars.reserveToken\n );\n\n uint256 lpBalance = balanceOf(initialLpInfo.liquidityProvider);\n _burn(initialLpInfo.liquidityProvider, lpBalance);\n\n // new lp balance\n lpBalance = Math.sqrt(uint256(initParams.virtualEth) * initParams.initialTokenMatch) - MINIMUM_LIQUIDITY;\n _mint(to, lpBalance);\n\n _updateStateAfterTakeover(\n initParams.virtualEth,\n initParams.bootstrapEth,\n initParams.initialTokenMatch,\n wethAmountIn,\n tokenAmountIn,\n lpBalance,\n to,\n initParams.initialEth\n );\n }\n```\n
medium
```\n uint256 totalUserCollateral = totalCollateralValue(_collateralAddress, _loanHolder);\n uint256 proposedLiquidationAmount;\n { //scope block for liquidationAmount due to stack too deep\n uint256 liquidationAmount = viewLiquidatableAmount(totalUserCollateral, 1 ether, isoUSDBorrowed, liquidatableMargin);\n require(liquidationAmount > 0 , "Loan not liquidatable");\n proposedLiquidationAmount = _calculateProposedReturnedCapital(_collateralAddress, _loanNFTs, _partialPercentage);\n require(proposedLiquidationAmount <= liquidationAmount, "excessive liquidation suggested");\n }\n uint256 isoUSDreturning = proposedLiquidationAmount*LIQUIDATION_RETURN/LOAN_SCALE;\n if(proposedLiquidationAmount >= totalUserCollateral){\n //@audit bad debt cleared here\n }\n```\n
medium
```\nif (\_openDate != 0) {\n \_setOpenDate(\_openDate);\n}\n```\n
medium