function
stringlengths
12
63.3k
severity
stringclasses
4 values
```\nfunction \_claim(address from, address to) internal returns (uint256) {\n (uint256 amountReward, uint256 amountPool) = redeemableReward(from);\n require(amountPool != 0, "Pool: User has no redeemable pool tokens");\n\n \_burnFrom(from, amountPool);\n \_incrementClaimed(amountReward);\n\n rewardToken.transfer(to, amountReward);\n return amountReward;\n}\n```\n
low
```\nfunction takeFee(address sender, uint amount) internal returns (uint) {\n uint feeAmount = (amount * fee) / 100 / 2;\n balanceOf[address(this)] = balanceOf[address(this)] + feeAmount;\n\n emit Transfer(sender, address(this), feeAmount);\n\n return amount - feeAmount;\n}\n```\n
none
```\nstakingContext.auraRewardPool.withdrawAndUnwrap(bptClaim, false);\n```\n
medium
```\n function getEthPrice() internal view returns (uint) {\n (, int answer,, uint updatedAt,) =\n ethUsdPriceFeed.latestRoundData();\n\n if (block.timestamp - updatedAt >= 86400)\n revert Errors.StalePrice(address(0), address(ethUsdPriceFeed));\n\n if (answer <= 0)\n revert Errors.NegativePrice(address(0), address(ethUsdPriceFeed));\n\n return uint(answer);\n }\n```\n
medium
```\nfunction getCurrentNFTMintingPrice() public view returns (uint256) {\n if (block.timestamp < defaultSaleStartTime) return DEFAULT_NFT_PRICE;\n\n uint256 calculateTimeDifference = block.timestamp -\n defaultSaleStartTime;\n\n uint256 calculateIntervals = calculateTimeDifference /\n DEFAULT_TIME_INTERVAL;\n\n if (calculateIntervals >= MAX_DECREASE_ITERATIONS) {\n uint256 calculatePrice = (DEFAULT_NFT_PRICE -\n (DEFAULT_DECREASE_NFT_PRICE_AFTER_TIME_INTERVAL *\n MAX_DECREASE_ITERATIONS));\n\n return calculatePrice;\n } else {\n uint256 calculatePrice = (DEFAULT_NFT_PRICE -\n (DEFAULT_DECREASE_NFT_PRICE_AFTER_TIME_INTERVAL *\n calculateIntervals));\n\n return calculatePrice;\n }\n}\n```\n
none
```\nfunction getMultiplier(address account) private view returns (uint256) {\n uint256 multiplier;\n if (_multiplier[account] && block.timestamp > _holderFirstBuyTimestamp[account] + 1 weeks && \n block.timestamp < _holderFirstBuyTimestamp[account] + 2 weeks) {\n multiplier = balanceOf(account).mul(3);\n }\n else if (_multiplier[account] && block.timestamp > _holderFirstBuyTimestamp[account] + 2 weeks && \n block.timestamp < _holderFirstBuyTimestamp[account] + 3 weeks) {\n multiplier = balanceOf(account).mul(5);\n }\n else if (_multiplier[account] && block.timestamp > _holderFirstBuyTimestamp[account] + 3 weeks) {\n multiplier = balanceOf(account).mul(7);\n }\n else {\n multiplier = balanceOf(account);\n }\n \n return\n multiplier;\n}\n```\n
none
```\nFile: contracts\OperatorTokenomics\SponsorshipPolicies\VoteKickPolicy.sol\n function _endVote(address target) internal {\n address flagger = flaggerAddress[target];\n bool flaggerIsGone = stakedWei[flagger] == 0;\n bool targetIsGone = stakedWei[target] == 0;\n uint reviewerCount = reviewers[target].length;\n // release stake locks before vote resolution so that slashings and kickings during resolution aren't affected\n // if either the flagger or the target has forceUnstaked or been kicked, the lockedStakeWei was moved to forfeitedStakeWei\n if (flaggerIsGone) {\n forfeitedStakeWei -= flagStakeWei[target];\n } else {\n lockedStakeWei[flagger] -= flagStakeWei[target];\n }\n if (targetIsGone) {\n forfeitedStakeWei -= targetStakeAtRiskWei[target];\n } else {\n lockedStakeWei[target] -= targetStakeAtRiskWei[target]; //@audit revert after forceUnstake() => stake() again\n }\n```\n
high
```\nfunction matchOrders(\n LibOrder.Order memory leftOrder,\n LibOrder.Order memory rightOrder,\n bytes memory leftSignature,\n bytes memory rightSignature\n)\n```\n
medium
```\n2. Multisig. Trusted with essentially everything but user collateral. \n```\n
medium
```\nfunction maxTxValues()\n external\n view\n returns (\n bool _limitsEnabled,\n bool _transferDelayEnabled,\n uint256 _maxWallet,\n uint256 _maxTx\n )\n{\n _limitsEnabled = limitsEnabled;\n _transferDelayEnabled = transferDelayEnabled;\n _maxWallet = maxWallet;\n _maxTx = maxTx;\n}\n```\n
none
```\nfunction \_beforeTokenTransfer(\n address operator,\n address from,\n address to,\n uint256[] memory ids,\n uint256[] memory amounts,\n bytes memory data\n) internal virtual override {\n for (uint256 i = 0; i < ids.length; i++) {\n if (FortaStakingUtils.isActive(ids[i])) {\n uint8 subjectType = FortaStakingUtils.subjectTypeOfShares(ids[i]);\n if (subjectType == DELEGATOR\_NODE\_RUNNER\_SUBJECT && to != address(0) && from != address(0)) {\n \_allocator.didTransferShares(ids[i], subjectType, from, to, amounts[i]);\n }\n```\n
high
```\nfunction _domainSeparatorV4() internal view returns (bytes32) {\n if (address(this) == _cachedThis && block.chainid == _cachedChainId) {\n return _cachedDomainSeparator;\n } else {\n return _buildDomainSeparator();\n }\n}\n```\n
none
```\nfunction startBridge() external onlyRole(BRIDGE_MANAGER) {\n active = true;\n}\n```\n
none
```\ncontract Rewards is IRewards, OwnablePausableUpgradeable, ReentrancyGuardUpgradeable {\n```\n
medium
```\nfunction bootstrapNewToken(\n address inputToken,\n uint256 maxInputAmount,\n address outputToken\n) public override returns (uint64 fractionBootstrapped) {\n // Check whether the valid token is being bootstrapped\n TokenSettings memory tokenToList = listedTokens[inputToken];\n require(\n tokenToList.state == State.PreListing,\n "DFP: Wrong token"\n );\n\n // Calculate how many tokens to actually take in (clamp at max available)\n uint256 initialInputBalance = IERC20(inputToken).balanceOf(address(this));\n uint256 availableAmount;\n\n // Intentionally underflow (zero clamping) is the cheapest way to gracefully prevent failing when target is already met\n unchecked { availableAmount = tokenToList.listingTarget - initialInputBalance; }\n if (initialInputBalance >= tokenToList.listingTarget) { availableAmount = 1; }\n uint256 actualInputAmount = maxInputAmount > availableAmount ? availableAmount : maxInputAmount;\n\n // Actually pull the tokens in\n IERC20(inputToken).safeTransferFrom(msg.sender, address(this), actualInputAmount);\n\n // Check whether the output token requested is indeed being delisted\n TokenSettings memory tokenToDelist = listedTokens[outputToken];\n require(\n tokenToDelist.state == State.Delisting,\n "DFP: Wrong token"\n );\n\n // Check how many of the output tokens should be given out and transfer those\n uint256 initialOutputBalance = IERC20(outputToken).balanceOf(address(this));\n uint256 outputAmount = actualInputAmount * initialOutputBalance / availableAmount;\n IERC20(outputToken).safeTransfer(msg.sender, outputAmount);\n fractionBootstrapped = uint64((actualInputAmount << 64) / tokenToList.listingTarget);\n\n // Emit event for better governance decisions\n emit Bootstrapped(\n msg.sender,\n inputToken,\n actualInputAmount,\n outputToken,\n outputAmount\n );\n\n // If the input token liquidity is now at the target we complete the (de)listing\n if (actualInputAmount == availableAmount) {\n tokenToList.state = State.Listed;\n listedTokens[inputToken] = tokenToList;\n delete listedTokens[outputToken];\n delete listingUpdate;\n DFPconfig.delistingBonus = 0;\n emit BootstrapCompleted(outputToken, inputToken);\n }\n}\n```\n
none
```\nfunction owner() public view returns (address) {\n return _owner;\n}\n```\n
none
```\n for (uint256 i = 0; i < rewardTokens.length; i++) {\n uint256 rewards = _doCutRewardsFee(rewardTokens[i]);\n _ensureApprove(rewardTokens[i], address(swapRouter), rewards);\n swapRouter.swapExactTokensForTokens(\n rewards,\n 0,\n swapPath[i],\n address(this),\n type(uint256).max\n );\n }\n```\n
medium
```\nfunction _swapPTsForTarget(\n address adapter,\n uint256 maturity,\n uint256 ptBal,\n PermitData calldata permit\n) internal returns (uint256 tBal) {\n _transferFrom(permit, divider.pt(adapter, maturity), ptBal);\n\n if (divider.mscale(adapter, maturity) > 0) {\n tBal = divider.redeem(adapter, maturity, ptBal); <- @audit-issue always tries to redeem even if restricted\n } else {\n tBal = _balancerSwap(\n divider.pt(adapter, maturity),\n Adapter(adapter).target(),\n ptBal,\n BalancerPool(spaceFactory.pools(adapter, maturity)).getPoolId(),\n 0,\n payable(address(this))\n );\n }\n}\n```\n
medium
```\nconstructor() {\n address msgSender = _msgSender();\n _owner = msgSender;\n emit OwnershipTransferred(address(0), msgSender);\n}\n```\n
none
```\n for (uint256 i = 0; i < rewardTokens.length; i++) {\n uint256 rewards = _doCutRewardsFee(rewardTokens[i]);\n _ensureApprove(rewardTokens[i], address(swapRouter), rewards);\n swapRouter.swapExactTokensForTokens(\n rewards,\n 0,\n swapPath[i],\n address(this),\n type(uint256).max\n );\n }\n```\n
high
```\nfunction maxWithdraw(address owner) public view returns (uint256) {\n return convertToAssets(liquidStakingToken.balanceOf(owner));\n}\n```\n
low
```\nfunction setVerifierAddress(address \_newVerifierAddress, uint256 \_proofType) external onlyRole(DEFAULT\_ADMIN\_ROLE) {\n if (\_newVerifierAddress == address(0)) {\n revert ZeroAddressNotAllowed();\n }\n verifiers[\_proofType] = \_newVerifierAddress;\n}\n```\n
high
```\nfunction owner() public view returns (address) {\n return _owner;\n}\n```\n
none
```\n // Generate executable to initiate swap on DCACoWAutomation return Types.Executable({\n callType: Types.CallType.DELEGATECALL, target: dcaCoWAutomation,\n value: 0,\n data: abi.encodeCall( DCACoWAutomation.initiateSwap,\n (params.tokenIn, params.tokenOut, swapRecipient, amountIn, minAmountOut, swapFee)\n )\n });\n```\n
low
```\n/// @dev Only allow access from the owning node address\nmodifier onlyMinipoolOwner() {\n // Only the node operator can upgrade\n address withdrawalAddress = rocketStorage.getNodeWithdrawalAddress(nodeAddress);\n require(msg.sender == nodeAddress || msg.sender == withdrawalAddress, "Only the node operator can access this method");\n \_;\n}\n```\n
low
```\nfunction disableTransferDelay() external onlyOwner {\n transferDelayEnabled = false;\n emit DisabledTransferDelay(block.timestamp);\n}\n```\n
none
```\nfunction sendFrom(address _from, uint16 _dstChainId, bytes calldata _toAddress, uint _amount, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) public payable virtual override {\n _send(_from, _dstChainId, _toAddress, _amount, _refundAddress, _zroPaymentAddress, _adapterParams);\n}\n```\n
high
```\n/\*\*\n \* @dev returns true if the converter is active, false otherwise\n \*\n \* @return true if the converter is active, false otherwise\n\*/\nfunction isActive() public view virtual override returns (bool) {\n return anchor.owner() == address(this);\n}\n```\n
medium
```\n bool isToken0Weth;\n _permit2Add(params_, amount0, amount1, token0, token1);\n\n _addLiquidity(\n params_.addData.vault,\n amount0,\n amount1,\n sharesReceived,\n params_.addData.gauge,\n params_.addData.receiver,\n token0,\n token1\n );\n\n if (msg.value > 0) {\n if (isToken0Weth && msg.value > amount0) {\n payable(msg.sender).sendValue(msg.value - amount0);\n } else if (!isToken0Weth && msg.value > amount1) {\n payable(msg.sender).sendValue(msg.value - amount1);\n }\n }\n```\n
high
```\nfunction firstPublicSaleBatchMint(uint256 tokenCount)\n external\n payable\n returns (bool)\n{\n if (\n (block.timestamp >= defaultSaleStartTime) &&\n (block.timestamp <\n defaultSaleStartTime + DEFAULT_INITIAL_PUBLIC_SALE)\n ) {\n if (tokenCount == 0) revert InvalidTokenCountZero();\n\n uint256 getPriceOFNFT = getCurrentNFTMintingPrice();\n\n if ((getPriceOFNFT * tokenCount) != msg.value)\n revert InvalidBuyNFTPrice(\n (getPriceOFNFT * tokenCount),\n msg.value\n );\n\n if (\n firstPublicSale[msg.sender] + tokenCount >\n LIMIT_IN_PUBLIC_SALE_PER_WALLET\n ) revert MaximumMintLimitReachedByUser();\n\n firstPublicSale[msg.sender] =\n firstPublicSale[msg.sender] +\n tokenCount;\n\n uint256[] memory newIDs = new uint256[](tokenCount);\n uint256[] memory newAmounts = new uint256[](tokenCount);\n\n if (_tokenIds + tokenCount > DEFAULT_MAX_FIRST_PUBLIC_SUPPLY)\n revert MaximumPublicMintSupplyReached();\n\n dutchAuctionLastPrice = getPriceOFNFT;\n\n for (uint256 i = 0; i < tokenCount; i++) {\n _tokenIds++;\n\n newIDs[i] = _tokenIds;\n newAmounts[i] = 1;\n }\n\n emit NewNFTBatchMintedOnFirstPublicSale(\n newIDs,\n msg.sender,\n msg.value\n );\n\n _mintBatch(msg.sender, newIDs, newAmounts, "");\n\n return true;\n } else {\n revert UnAuthorizedRequest();\n }\n}\n```\n
none
```\nif (\_isPurchased[delegationId]) {\n address holder = delegation.holder;\n \_totalDelegated[holder] += delegation.amount;\n if (\_totalDelegated[holder] >= \_purchased[holder]) {\n purchasedToUnlocked(holder);\n }\n```\n
high
```\n function getSellRate(address \_srcAddr, address \_destAddr, uint \_srcAmount, bytes memory) public override view returns (uint rate) {\n (rate, ) = KyberNetworkProxyInterface(KYBER\_INTERFACE)\n .getExpectedRate(IERC20(\_srcAddr), IERC20(\_destAddr), \_srcAmount);\n\n // multiply with decimal difference in src token\n rate = rate \* (10\*\*(18 - getDecimals(\_srcAddr)));\n // divide with decimal difference in dest token\n rate = rate / (10\*\*(18 - getDecimals(\_destAddr)));\n }\n\n /// @notice Return a rate for which we can buy an amount of tokens\n /// @param \_srcAddr From token\n /// @param \_destAddr To token\n /// @param \_destAmount To amount\n /// @return rate Rate\n function getBuyRate(address \_srcAddr, address \_destAddr, uint \_destAmount, bytes memory \_additionalData) public override view returns (uint rate) {\n uint256 srcRate = getSellRate(\_destAddr, \_srcAddr, \_destAmount, \_additionalData);\n uint256 srcAmount = wmul(srcRate, \_destAmount);\n\n rate = getSellRate(\_srcAddr, \_destAddr, srcAmount, \_additionalData);\n\n // increase rate by 3% too account for inaccuracy between sell/buy conversion\n rate = rate + (rate / 30);\n }\n```\n
low
```\nfunction _getSum(uint32[] memory numbers) internal pure returns (uint32 sum) {\n // overflow should be impossible in for-loop index\n uint256 numbersLength = numbers.length;\n for (uint256 i = 0; i < numbersLength; ) {\n sum += numbers[i];\n unchecked {\n // overflow should be impossible in for-loop index\n ++i;\n }\n }\n}\n```\n
none
```\nFile: wfCashLogic.sol\n /// @dev Sells an fCash share back on the Notional AMM\n function _sellfCash(\n address receiver,\n uint256 fCashToSell,\n uint32 maxImpliedRate\n ) private returns (uint256 tokensTransferred) {\n (IERC20 token, bool isETH) = getToken(true); \n uint256 balanceBefore = isETH ? WETH.balanceOf(address(this)) : token.balanceOf(address(this)); \n uint16 currencyId = getCurrencyId(); \n\n (uint256 initialCashBalance, uint256 fCashBalance) = getBalances(); \n bool hasInsufficientfCash = fCashBalance < fCashToSell; \n\n uint256 primeCashToWithdraw; \n if (hasInsufficientfCash) {\n // If there is insufficient fCash, calculate how much prime cash would be purchased if the\n // given fCash amount would be sold and that will be how much the wrapper will withdraw and\n // send to the receiver. Since fCash always sells at a discount to underlying prior to maturity,\n // the wrapper is guaranteed to have sufficient cash to send to the account.\n (/* */, primeCashToWithdraw, /* */, /* */) = NotionalV2.getPrincipalFromfCashBorrow( \n currencyId,\n fCashToSell, \n getMaturity(),\n 0, \n block.timestamp\n ); \n // If this is zero then it signifies that the trade will fail.\n require(primeCashToWithdraw > 0, "Redeem Failed"); \n\n // Re-write the fCash to sell to the entire fCash balance.\n fCashToSell = fCashBalance;\n }\n```\n
medium
```\nfunction autoBurnLiquidityPairTokens() internal returns (bool){\n\n lastLpBurnTime = block.timestamp;\n\n uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);\n\n uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);\n\n if (amountToBurn > 0){\n super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);\n }\n\n IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);\n pair.sync();\n emit AutoNukeLP();\n return true;\n}\n```\n
none
```\n// LibTransfer::transferToken\nif (fromMode == From.EXTERNAL && toMode == To.EXTERNAL) {\n uint256 beforeBalance = token.balanceOf(recipient);\n token.safeTransferFrom(sender, recipient, amount);\n return token.balanceOf(recipient).sub(beforeBalance);\n}\namount = receiveToken(token, amount, sender, fromMode);\nsendToken(token, amount, recipient, toMode);\nreturn amount;\n```\n
medium
```\nfunction _transfer(address from, address to, uint256 amount) internal override {\n require(from != address(0), "ERC20: transfer from the zero address");\n require(to != address(0), "ERC20: transfer to the zero address");\n uint256 RewardsFee;\n uint256 deadFees;\n uint256 marketingFees;\n uint256 liquidityFee;\n\n if (!canTransferBeforeTradingIsEnabled[from]) {\n require(tradingEnabled, "Trading has not yet been enabled");\n }\n if (amount == 0) {\n super._transfer(from, to, 0);\n return;\n } \n\n if (_isVesting[from]) {\n if (block.timestamp < _vestingTimestamp[from] + 5 minutes) {\n require(balanceOf(from) - amount >= tokensVesting[from], "cant sell vested tokens");\n }\n else {\n tokensVesting[from] = 0;\n _isVesting[from] = false;\n }\n }\n\n \n else if (!swapping && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {\n bool isSelling = automatedMarketMakerPairs[to];\n bool isBuying = automatedMarketMakerPairs[from];\n\n if (!isBuying && !isSelling) {\n if (!_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {\n uint256 tFees = amount.mul(transferFee).div(100);\n amount = amount.sub(tFees);\n super._transfer(from, address(this), tFees);\n super._transfer(from, to, amount);\n dividendTracker.setBalance(from, getMultiplier(from));\n dividendTracker.setBalance(to, getMultiplier(to));\n _diamondHands[from] = false;\n _multiplier[from] = false;\n _holderFirstBuyTimestamp[from] = block.timestamp;\n return;\n }\n else {\n super._transfer(from, to, amount);\n dividendTracker.setBalance(from, getMultiplier(from));\n dividendTracker.setBalance(to, getMultiplier(to));\n _diamondHands[from] = false;\n _multiplier[from] = false;\n _holderFirstBuyTimestamp[from] = block.timestamp;\n return;\n }\n }\n\n else if (isSelling) {\n if (amount >= minimumForDiamondHands) {\n RewardsFee = 8;\n }\n else {\n RewardsFee = sellRewardsFee;\n }\n deadFees = sellDeadFees;\n marketingFees = sellMarketingFees;\n liquidityFee = sellLiquidityFee;\n\n if (limitsInEffect) {\n require(block.timestamp >= _holderLastTransferTimestamp[from] + cooldowntimer,\n "cooldown period active");\n require(amount <= maxTX,"above max transaction limit");\n _holderLastTransferTimestamp[from] = block.timestamp;\n\n }\n _diamondHands[from] = false;\n _multiplier[from] = false;\n _holderFirstBuyTimestamp[from] = block.timestamp;\n\n\n } else if (isBuying) {\n\n if (_diamondHands[to]) {\n if (block.timestamp >= _holderBuy1Timestamp[to] + 1 days && balanceOf(to) >= minimumForDiamondHands) {\n super._transfer(from, to, amount);\n dividendTracker.setBalance(from, getMultiplier(from));\n dividendTracker.setBalance(to, getMultiplier(to));\n return;\n }\n }\n\n if (!_multiplier[to]) {\n _multiplier[to] = true;\n _holderFirstBuyTimestamp[to] = block.timestamp;\n }\n\n if (!_diamondHands[to]) {\n _diamondHands[to] = true;\n _holderBuy1Timestamp[to] = block.timestamp;\n }\n\n RewardsFee = buyRewardsFee;\n deadFees = buyDeadFees;\n marketingFees = buyMarketingFees;\n liquidityFee = buyLiquidityFee;\n\n if (limitsInEffect) {\n require(block.timestamp > launchtimestamp + delay,"you shall not pass");\n require(tx.gasprice <= gasPriceLimit,"Gas price exceeds limit.");\n require(_holderLastTransferBlock[to] != block.number,"Too many TX in block");\n require(amount <= maxTX,"above max transaction limit");\n _holderLastTransferBlock[to] = block.number;\n }\n\n uint256 contractBalanceRecipient = balanceOf(to);\n require(contractBalanceRecipient + amount <= maxWallet,"Exceeds maximum wallet token amount." );\n }\n\n uint256 totalFees = RewardsFee.add(liquidityFee + marketingFees);\n\n uint256 contractTokenBalance = balanceOf(address(this));\n\n bool canSwap = contractTokenBalance >= swapTokensAtAmount;\n\n if (canSwap && isSelling) {\n swapping = true;\n\n if (swapAndLiquifyEnabled && liquidityFee > 0 && totalBuyFees > 0) {\n uint256 totalBuySell = buyAmount.add(sellAmount);\n uint256 swapAmountBought = contractTokenBalance.mul(buyAmount).div(totalBuySell);\n uint256 swapAmountSold = contractTokenBalance.mul(sellAmount).div(totalBuySell);\n uint256 swapBuyTokens = swapAmountBought.mul(liquidityFee).div(totalBuyFees);\n uint256 swapSellTokens = swapAmountSold.mul(liquidityFee).div(totalSellFees);\n uint256 swapTokens = swapSellTokens.add(swapBuyTokens);\n\n swapAndLiquify(swapTokens);\n }\n\n uint256 remainingBalance = balanceOf(address(this));\n swapAndSendDividends(remainingBalance);\n buyAmount = 1;\n sellAmount = 1;\n swapping = false;\n }\n\n uint256 fees = amount.mul(totalFees).div(100);\n uint256 burntokens;\n\n if (deadFees > 0) {\n burntokens = amount.mul(deadFees) / 100;\n super._transfer(from, DEAD, burntokens);\n _totalSupply = _totalSupply.sub(burntokens);\n\n }\n\n amount = amount.sub(fees + burntokens);\n\n if (isSelling) {\n sellAmount = sellAmount.add(fees);\n } \n else {\n buyAmount = buyAmount.add(fees);\n }\n\n super._transfer(from, address(this), fees);\n\n uint256 gas = gasForProcessing;\n\n try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) {\n emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas);\n } catch {}\n }\n\n super._transfer(from, to, amount);\n dividendTracker.setBalance(from, getMultiplier(from));\n dividendTracker.setBalance(to, getMultiplier(to));\n}\n```\n
none
```\n// If subsidy pool is non-empty, distribute the value to signers but\n// never distribute more than the payment for opening a keep.\nuint256 signerSubsidy = subsidyPool < msg.value\n ? subsidyPool\n : msg.value;\nif (signerSubsidy > 0) {\n subsidyPool -= signerSubsidy;\n keep.distributeETHToMembers.value(signerSubsidy)();\n}\n```\n
medium
```\n // 2. Get the time passed since the last interest accrual\n uint _timeDelta = block.timestamp - _lastAccrueInterestTime;\n \n // 3. If the time passed is 0, return the current values\n if(_timeDelta == 0) return (_currentTotalSupply, _accruedFeeShares, _currentCollateralRatioMantissa, _currentTotalDebt);\n \n // 4. Calculate the supplied value\n uint _supplied = _totalDebt + _loanTokenBalance;\n // 5. Calculate the utilization\n uint _util = getUtilizationMantissa(_totalDebt, _supplied);\n\n // 6. Calculate the collateral ratio\n _currentCollateralRatioMantissa = getCollateralRatioMantissa(\n _util,\n _lastAccrueInterestTime,\n block.timestamp,\n _lastCollateralRatioMantissa,\n COLLATERAL_RATIO_FALL_DURATION,\n COLLATERAL_RATIO_RECOVERY_DURATION,\n MAX_COLLATERAL_RATIO_MANTISSA,\n SURGE_MANTISSA\n );\n\n // 7. If there is no debt, return the current values\n if(_totalDebt == 0) return (_currentTotalSupply, _accruedFeeShares, _currentCollateralRatioMantissa, _currentTotalDebt);\n\n // 8. Calculate the borrow rate\n uint _borrowRate = getBorrowRateMantissa(_util, SURGE_MANTISSA, MIN_RATE, SURGE_RATE, MAX_RATE);\n // 9. Calculate the interest\n uint _interest = _totalDebt * _borrowRate * _timeDelta / (365 days * 1e18); // does the optimizer optimize this? or should it be a constant?\n // 10. Update the total debt\n _currentTotalDebt += _interest;\n```\n
medium
```\n if (obtainedPremium > premium) {\n baseToken.safeTransferFrom(address(this), msg.sender, obtainedPremium - premium);\n }\n```\n
medium
```\ncurrentL2BlockNumber = \_finalizationData.finalBlockNumber;\n```\n
high
```\nfunction geUnlockTime() public view returns (uint256) {\n return _lockTime;\n}\n```\n
none
```\nfunction importScore(address \_worker)\nexternal override\n{\n require(!m\_v3\_scoreImported[\_worker], "score-already-imported");\n m\_workerScores[\_worker] = m\_workerScores[\_worker].max(m\_v3\_iexecHub.viewScore(\_worker));\n m\_v3\_scoreImported[\_worker] = true;\n}\n```\n
medium
```\nfunction updateGasForProcessing(uint256 newValue) public onlyOwner {\n require(newValue >= 200000 && newValue <= 5000000);\n emit GasForProcessingUpdated(newValue, gasForProcessing);\n gasForProcessing = newValue;\n}\n```\n
none
```\nself.\_validators[\_pk].state == 2;\n```\n
medium
```\nrouter = ISwapRouter(\_router);\nuint256 amountOut;\nuint256 swap;\nif(swapAmount < 0) {\n //swap token1 for token0\n\n swap = uint256(swapAmount \* -1);\n IHypervisor(pos).token1().transferFrom(msg.sender, address(this), deposit1+swap);\n amountOut = router.exactInput(\n ISwapRouter.ExactInputParams(\n path,\n address(this),\n block.timestamp + swapLife,\n swap,\n deposit0\n )\n );\n}\nelse{\n //swap token1 for token0\n swap = uint256(swapAmount);\n IHypervisor(pos).token0().transferFrom(msg.sender, address(this), deposit0+swap);\n\n amountOut = router.exactInput(\n ISwapRouter.ExactInputParams(\n path,\n address(this),\n block.timestamp + swapLife,\n swap,\n deposit1\n )\n ); \n}\n```\n
high
```\nfunction updateliquidityWallet(address newliquidityWallet) external onlyOwner {\n emit liquidityWalletUpdated(newliquidityWallet, liquidityWallet);\n liquidityWallet = newliquidityWallet;\n}\n```\n
none
```\nfunction sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return sub(a, b, "SafeMath: subtraction overflow");\n}\n```\n
none
```\nfunction mul(uint256 a, uint256 b) internal pure returns (uint256) {\n return a * b;\n}\n```\n
none
```\n\_addL2MerkleRoots(\_finalizationData.l2MerkleRoots, \_finalizationData.l2MerkleTreesDepth);\n\_anchorL2MessagingBlocks(\_finalizationData.l2MessagingBlocksOffsets, lastFinalizedBlock);\n```\n
high
```\nfunction min(int256 a, int256 b) internal pure returns (int256) {\n return a < b ? a : b;\n}\n```\n
none
```\nfunction div(\n uint256 a,\n uint256 b,\n string memory errorMessage\n) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n uint256 c = a / b;\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n\n return c;\n}\n```\n
none
```\nfunction _transferFromExcluded(\n address sender,\n address recipient,\n uint256 tAmount\n) private {\n (\n uint256 tTransferAmount,\n uint256 tFee,\n uint256 tLiquidity,\n uint256 tWallet,\n uint256 tDonation\n ) = _getTValues(tAmount);\n (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(\n tAmount,\n tFee,\n tLiquidity,\n tWallet,\n tDonation,\n _getRate()\n );\n\n _tOwned[sender] = _tOwned[sender].sub(tAmount);\n _rOwned[sender] = _rOwned[sender].sub(rAmount);\n _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);\n _takeLiquidity(tLiquidity);\n _takeWalletFee(tWallet);\n _takeDonationFee(tDonation);\n _reflectFee(rFee, tFee);\n emit Transfer(sender, recipient, tTransferAmount);\n}\n```\n
none
```\nfunction setSwapBackSettings(\n bool _enabled,\n uint256 _min,\n uint256 _max\n) external onlyOwner {\n require(\n _min >= 1,\n "Swap amount cannot be lower than 0.01% total supply."\n );\n require(_max >= _min, "maximum amount cant be higher than minimum");\n\n swapbackEnabled = _enabled;\n swapBackValueMin = (totalSupply() * _min) / 10000;\n swapBackValueMax = (totalSupply() * _max) / 10000;\n emit SwapbackSettingsUpdated(_enabled, _min, _max);\n}\n```\n
none
```\nif (to != address(this)) {\n _updateFeeRewards(to);\n}\n```\n
high
```\ncontract LybraWstETHVault is LybraPeUSDVaultBase {\n Ilido immutable lido;\n //WstETH = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0;\n //Lido = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84;\n constructor(address \_lido, address \_asset, address \_oracle, address \_config) LybraPeUSDVaultBase(\_asset, \_oracle, \_config) {\n lido = Ilido(\_lido);\n }\n\n function depositEtherToMint(uint256 mintAmount) external payable override {\n require(msg.value >= 1 ether, "DNL");\n uint256 sharesAmount = lido.submit{value: msg.value}(address(configurator));\n require(sharesAmount != 0, "ZERO\_DEPOSIT");\n lido.approve(address(collateralAsset), msg.value);\n uint256 wstETHAmount = IWstETH(address(collateralAsset)).wrap(msg.value);\n depositedAsset[msg.sender] += wstETHAmount;\n if (mintAmount > 0) {\n \_mintPeUSD(msg.sender, msg.sender, mintAmount, getAssetPrice());\n }\n emit DepositEther(msg.sender, address(collateralAsset), msg.value,wstETHAmount, block.timestamp);\n }\n```\n
high
```\nfunction governorAddPoolMultiplier(\n uint256 \_pid,\n uint64 lockLength,\n uint64 newRewardsMultiplier\n) external onlyGovernor {\n PoolInfo storage pool = poolInfo[\_pid];\n uint256 currentMultiplier = rewardMultipliers[\_pid][lockLength];\n // if the new multplier is less than the current multiplier,\n // then, you need to unlock the pool to allow users to withdraw\n if (newRewardsMultiplier < currentMultiplier) {\n pool.unlocked = true;\n }\n rewardMultipliers[\_pid][lockLength] = newRewardsMultiplier;\n\n emit LogPoolMultiplier(\_pid, lockLength, newRewardsMultiplier);\n}\n```\n
medium
```\nFile: Curve2TokenConvexHelper.sol\n function _executeSettlement(\n StrategyContext calldata strategyContext,\n Curve2TokenPoolContext calldata poolContext,\n uint256 maturity,\n uint256 poolClaimToSettle,\n uint256 redeemStrategyTokenAmount,\n RedeemParams memory params\n ) private {\n (uint256 spotPrice, uint256 oraclePrice) = poolContext._getSpotPriceAndOraclePrice(strategyContext);\n\n /// @notice params.minPrimary and params.minSecondary are not required to be passed in by the caller\n /// for this strategy vault\n (params.minPrimary, params.minSecondary) = poolContext.basePool._getMinExitAmounts({\n strategyContext: strategyContext,\n oraclePrice: oraclePrice,\n spotPrice: spotPrice,\n poolClaim: poolClaimToSettle\n });\n```\n
high
```\nfor (uint256 i = 0; i < leaderboard.length; i++) {\n```\n
low
```\nFile: VaultAccountAction.sol\n function exitVault(\n address account,\n address vault,\n address receiver,\n uint256 vaultSharesToRedeem,\n uint256 lendAmount,\n uint32 minLendRate,\n bytes calldata exitVaultData\n ) external payable override nonReentrant returns (uint256 underlyingToReceiver) {\n..SNIP..\n // If insufficient strategy tokens are redeemed (or if it is set to zero), then\n // redeem with debt repayment will recover the repayment from the account's wallet\n // directly.\n underlyingToReceiver = underlyingToReceiver.add(vaultConfig.redeemWithDebtRepayment(\n vaultAccount, receiver, vaultSharesToRedeem, exitVaultData\n ));\n```\n
medium
```\nfunction setMaxGauges(uint256 newMax) external requiresAuth {\n uint256 oldMax = maxGauges;\n maxGauges = newMax;\n\n emit MaxGaugesUpdate(oldMax, newMax);\n}\n```\n
low
```\n// Sanity check that refund balance is zero\nrequire(nodeRefundBalance == 0, "Refund balance not zero");\n```\n
medium
```\nTransferUtils.sol\n function _transferERC20(address token, address to, uint256 amount) internal {\n IERC20 erc20 = IERC20(token);\n require(erc20 != IERC20(address(0)), "Token Address is not an ERC20");\n uint256 initialBalance = erc20.balanceOf(to);\n require(erc20.transfer(to, amount), "ERC20 Transfer failed");//@audit-issue will revert for USDT\n uint256 balance = erc20.balanceOf(to);\n require(balance >= (initialBalance + amount), "ERC20 Balance check failed");\n }\n```\n
medium
```\nbytes4 constant WITHDRAWCLAIM = 0x00ebf5dd;\n```\n
medium
```\nfunction enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyOwner {\n trustedValidators[validatorId] = true;\n}\n\nfunction disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyOwner {\n trustedValidators[validatorId] = false;\n}\n```\n
medium
```\n function mint(address r, uint256 s) external override returns (uint256) {\n if (block.timestamp > maturity) {\n revert Exception(\n 21,\n block.timestamp,\n maturity,\n address(0),\n address(0)\n );\n }\n uint128 assets = Cast.u128(previewMint(s));\n Safe.transferFrom(\n IERC20(underlying),\n msg.sender,\n address(this),\n assets\n );\n // consider the hardcoded slippage limit, 4626 compliance requires no minimum param.\n uint128 returned = IMarketPlace(marketplace).sellUnderlying(\n underlying,\n maturity,\n assets,\n assets - (assets / 100)\n );\n _transfer(address(this), r, returned);\n return returned;\n }\n```\n
medium
```\nlibrary SafeERC20Arithmetic {\n```\n
medium
```\nfunction withdrawFromGauge(uint256 _NFTId, address[] memory _tokens) public {\n uint256 amount = depositReceipt.pooledTokens(_NFTId);\n depositReceipt.burn(_NFTId);\n gauge.getReward(address(this), _tokens);\n gauge.withdraw(amount);\n //AMMToken adheres to ERC20 spec meaning it reverts on failure, no need to check return\n //slither-disable-next-line unchecked-transfer\n AMMToken.transfer(msg.sender, amount);\n}\n```\n
high
```\ndef lp_price() -> uint256:\n """\n Approximate LP token price\n """\n return 2 * self.virtual_price * self.sqrt_int(self.internal_price_oracle()) / 10**18\n```\n
high
```\naddress public tbtcSystem;\n```\n
low
```\nfunction min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n}\n```\n
none
```\n// Set the current transaction signer\naddress signerAddress = transaction.signerAddress;\n\_setCurrentContextAddressIfRequired(signerAddress, signerAddress);\n```\n
medium
```\n function cancel(uint256 proposalId) external {\n if(_getProposalState(proposalId) == ProposalState.Executed) revert InvalidProposalState();\n Proposal storage proposal = proposals[proposalId];\n if(msg.sender != proposal.proposer) revert NotProposer();\n if(GovLocks(govlocks).getPriorVotes(proposal.proposer, block.number - 1) > proposalThreshold) revert AboveThreshold(); //@audit incorrect\n proposal.cancelled = true;\n uint256 targetsLength = proposal.targets.length;\n for (uint256 i = 0; i < targetsLength; i++) {\n Timelock(timelock).cancelTransaction(proposal.targets[i], proposal.eta, proposal.values[i], proposal.calldatas[i], proposal.signatures[i]);\n }\n emit ProposalCanceled(proposalId);\n }\n```\n
medium
```\nFile: LiquidationFacetImpl.sol\n function liquidatePositionsPartyA(\n address partyA,\n uint256[] memory quoteIds\n ) internal returns (bool) {\n..SNIP..\n (bool hasMadeProfit, uint256 amount) = LibQuote.getValueOfQuoteForPartyA(\n accountLayout.symbolsPrices[partyA][quote.symbolId].price,\n LibQuote.quoteOpenAmount(quote),\n quote\n );\n..SNIP..\n if (\n accountLayout.liquidationDetails[partyA].liquidationType == LiquidationType.NORMAL\n ) {\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] += quote\n .lockedValues\n .cva;\n if (hasMadeProfit) {\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] -= amount;\n } else {\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] += amount;\n }\n } else if (\n accountLayout.liquidationDetails[partyA].liquidationType == LiquidationType.LATE\n ) {\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] +=\n quote.lockedValues.cva -\n ((quote.lockedValues.cva * accountLayout.liquidationDetails[partyA].deficit) /\n accountLayout.lockedBalances[partyA].cva);\n if (hasMadeProfit) {\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] -= amount;\n } else {\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] += amount;\n }\n } else if (\n accountLayout.liquidationDetails[partyA].liquidationType == LiquidationType.OVERDUE\n ) {\n if (hasMadeProfit) {\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] -= amount;\n } else {\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] +=\n amount -\n ((amount * accountLayout.liquidationDetails[partyA].deficit) /\n uint256(-accountLayout.liquidationDetails[partyA].totalUnrealizedLoss));\n }\n }\n```\n
high
```\n function rebase(uint32 _l2Gas) external {\n inflationMultiplier = IECO(l1Eco).getPastLinearInflation(block.number);\n```\n
high
```\nfunction isExcludedFromReward(address account) public view returns (bool) {\n return _isExcluded[account];\n}\n```\n
none
```\nconstructor() ERC20("ZOOK PROTOCOL", "ZOOK") {\n IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(uniV2router); \n\n excludeFromMaxTransaction(address(_uniswapV2Router), true);\n uniswapV2Router = _uniswapV2Router;\n\n uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());\n excludeFromMaxTransaction(address(uniswapV2Pair), true);\n _setAutomatedMarketMakerPair(address(uniswapV2Pair), true);\n\n // launch buy fees\n uint256 _buyLiquidityFee = 10;\n uint256 _buyDevelopmentFee = 10;\n uint256 _buyMarketingFee = 10;\n \n // launch sell fees\n uint256 _sellLiquidityFee = 10;\n uint256 _sellDevelopmentFee = 40;\n uint256 _sellMarketingFee = 30;\n\n\n uint256 totalSupply = 100_000_000 * 1e18;\n\n maxTransaction = 1000_000 * 1e18; // 1% max transaction at launch\n maxWallet = 1000_000 * 1e18; // 1% max wallet at launch\n swapTokensAtAmount = (totalSupply * 5) / 10000; // 0.05% swap wallet\n\n\n buyLiquidityFee = _buyLiquidityFee;\n buyDevelopmentFee = _buyDevelopmentFee;\n buyMarketingFee = _buyMarketingFee;\n buyTotalFees = buyLiquidityFee + buyDevelopmentFee + buyMarketingFee ;\n\n sellLiquidityFee = _sellLiquidityFee;\n sellDevelopmentFee = _sellDevelopmentFee;\n sellMarketingFee = _sellMarketingFee;\n sellTotalFees = sellLiquidityFee + sellDevelopmentFee + sellMarketingFee ;\n\n developmentWallet = address(0x4860da3d48EF5c82c269eE185Dc27Aa9DAfDC1d9); \n liquidityWallet = address(0x897B2fFCeE9a9611BF465866fD293d9dD931a230); \n marketingWallet = address(0x2Cec118b9749a659b851cecbe1b5a8c0C417773f);\n\n // exclude from paying fees or having max transaction amount\n excludeFromFees(owner(), true);\n excludeFromFees(address(this), true);\n excludeFromFees(address(0xdead), true);\n\n excludeFromMaxTransaction(owner(), true);\n excludeFromMaxTransaction(address(this), true);\n excludeFromMaxTransaction(address(0xdead), true);\n\n _mint(msg.sender, totalSupply);\n}\n```\n
none
```\ncontract SingleRandomWinner is PeriodicPrizeStrategy {\n function \_distribute(uint256 randomNumber) internal override {\n uint256 prize = prizePool.captureAwardBalance();\n address winner = ticket.draw(randomNumber);\n if (winner != address(0)) {\n \_awardTickets(winner, prize);\n \_awardAllExternalTokens(winner);\n }\n }\n}\n```\n
low
```\nint256 internal constant INTERNAL_TOKEN_PRECISION = 1e8;\nuint256 internal constant BALANCER_PRECISION = 1e18;\n```\n
high
```\nit('panprog liquidate unsuspecting user / self in 1 transaction', async () => {\n\n function setupOracle(price: string, timestamp : number, nextTimestamp : number) {\n const oracleVersion = {\n price: parse6decimal(price),\n timestamp: timestamp,\n valid: true,\n }\n oracle.at.whenCalledWith(oracleVersion.timestamp).returns(oracleVersion)\n oracle.status.returns([oracleVersion, nextTimestamp])\n oracle.request.returns()\n }\n\n var riskParameter = {\n maintenance: parse6decimal('0.2'),\n takerFee: parse6decimal('0.00'),\n takerSkewFee: 0,\n takerImpactFee: 0,\n makerFee: parse6decimal('0.00'),\n makerImpactFee: 0,\n makerLimit: parse6decimal('1000'),\n efficiencyLimit: parse6decimal('0.2'),\n liquidationFee: parse6decimal('0.50'),\n minLiquidationFee: parse6decimal('10'),\n maxLiquidationFee: parse6decimal('1000'),\n utilizationCurve: {\n minRate: parse6decimal('0.0'),\n maxRate: parse6decimal('1.00'),\n targetRate: parse6decimal('0.10'),\n targetUtilization: parse6decimal('0.50'),\n },\n pController: {\n k: parse6decimal('40000'),\n max: parse6decimal('1.20'),\n },\n minMaintenance: parse6decimal('10'),\n virtualTaker: parse6decimal('0'),\n staleAfter: 14400,\n makerReceiveOnly: false,\n }\n var marketParameter = {\n fundingFee: parse6decimal('0.0'),\n interestFee: parse6decimal('0.0'),\n oracleFee: parse6decimal('0.0'),\n riskFee: parse6decimal('0.0'),\n positionFee: parse6decimal('0.0'),\n maxPendingGlobal: 5,\n maxPendingLocal: 3,\n settlementFee: parse6decimal('0'),\n makerRewardRate: parse6decimal('0'),\n longRewardRate: parse6decimal('0'),\n shortRewardRate: parse6decimal('0'),\n makerCloseAlways: false,\n takerCloseAlways: false,\n closed: false,\n }\n \n await market.connect(owner).updateRiskParameter(riskParameter);\n await market.connect(owner).updateParameter(marketParameter);\n\n setupOracle('100', TIMESTAMP, TIMESTAMP + 100);\n\n var collateral = parse6decimal('1000')\n dsu.transferFrom.whenCalledWith(userB.address, market.address, collateral.mul(1e12)).returns(true)\n await market.connect(userB).update(userB.address, parse6decimal('10.000'), 0, 0, collateral, false)\n\n var collateral = parse6decimal('100')\n dsu.transferFrom.whenCalledWith(user.address, market.address, collateral.mul(1e12)).returns(true)\n await market.connect(user).update(user.address, 0, parse6decimal('1.000'), 0, collateral, false)\n\n // settle\n setupOracle('100', TIMESTAMP + 100, TIMESTAMP + 200);\n await market.connect(userB).update(userB.address, parse6decimal('10.000'), 0, 0, 0, false)\n await market.connect(user).update(user.address, 0, parse6decimal('1.000'), 0, 0, false)\n\n // withdraw\n var collateral = parse6decimal('800')\n dsu.transfer.whenCalledWith(userB.address, collateral.mul(1e12)).returns(true)\n await market.connect(userB).update(userB.address, parse6decimal('2.000'), 0, 0, collateral.mul(-1), false)\n\n // liquidate unsuspecting user\n setupOracle('100.01', TIMESTAMP + 150, TIMESTAMP + 200);\n const EXPECTED_LIQUIDATION_FEE = parse6decimal('100.01')\n dsu.transfer.whenCalledWith(liquidator.address, EXPECTED_LIQUIDATION_FEE.mul(1e12)).returns(true)\n dsu.balanceOf.whenCalledWith(market.address).returns(COLLATERAL.mul(1e12))\n await market.connect(liquidator).update(userB.address, 0, 0, 0, EXPECTED_LIQUIDATION_FEE.mul(-1), true)\n\n setupOracle('100.01', TIMESTAMP + 200, TIMESTAMP + 300);\n await market.connect(userB).update(userB.address, 0, 0, 0, 0, false)\n\n var info = await market.locals(userB.address);\n var pos = await market.positions(userB.address);\n console.log("Liquidated maker: collateral = " + info.collateral + " maker = " + pos.maker);\n\n})\n```\n
medium
```\nfunction sub(\n uint256 a,\n uint256 b,\n string memory errorMessage\n) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n uint256 c = a - b;\n\n return c;\n}\n```\n
none
```\nfunction _validateAccountPrepayment(uint256 opIndex, UserOperation calldata op, UserOpInfo memory opInfo, uint256 requiredPrefund)\ninternal returns (uint256 gasUsedByValidateAccountPrepayment, uint256 validationData) {\nunchecked {\n uint256 preGas = gasleft();\n MemoryUserOp memory mUserOp = opInfo.mUserOp;\n address sender = mUserOp.sender;\n _createSenderIfNeeded(opIndex, opInfo, op.initCode);\n address paymaster = mUserOp.paymaster;\n numberMarker();\n uint256 missingAccountFunds = 0;\n if (paymaster == address(0)) {\n uint256 bal = balanceOf(sender);\n missingAccountFunds = bal > requiredPrefund ? 0 : requiredPrefund - bal;\n }\n try IAccount(sender).validateUserOp{gas : mUserOp.verificationGasLimit}(op, opInfo.userOpHash, missingAccountFunds)\n returns (uint256 _validationData) {\n validationData = _validationData;\n } catch Error(string memory revertReason) {\n revert FailedOp(opIndex, string.concat("AA23 reverted: ", revertReason));\n } catch {\n revert FailedOp(opIndex, "AA23 reverted (or OOG)");\n }\n if (paymaster == address(0)) {\n DepositInfo storage senderInfo = deposits[sender];\n uint256 deposit = senderInfo.deposit;\n if (requiredPrefund > deposit) {\n revert FailedOp(opIndex, "AA21 didn't pay prefund");\n }\n senderInfo.deposit = uint112(deposit - requiredPrefund);\n }\n gasUsedByValidateAccountPrepayment = preGas - gasleft();\n}\n}\n```\n
none
```\nFile: BondBaseCallback.sol\n /* ========== WHITELISTING ========== */\n\n /// @inheritdoc IBondCallback\n function whitelist(address teller_, uint256 id_) external override onlyOwner {\n // Check that the market id is a valid, live market on the aggregator\n try _aggregator.isLive(id_) returns (bool live) {\n if (!live) revert Callback_MarketNotSupported(id_);\n } catch {\n revert Callback_MarketNotSupported(id_);\n }\n\n // Check that the provided teller is the teller for the market ID on the stored aggregator\n // We could pull the teller from the aggregator, but requiring the teller to be passed in\n // is more explicit about which contract is being whitelisted\n if (teller_ != address(_aggregator.getTeller(id_))) revert Callback_TellerMismatch();\n\n approvedMarkets[teller_][id_] = true;\n }\n```\n
medium
```\nfunction toDataWithIntendedValidatorHash(\n address validator,\n bytes memory data\n) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked("\x19\x00", validator, data));\n}\n```\n
none
```\nfunction addStake(uint32 unstakeDelaySec) public payable {\n DepositInfo storage info = deposits[msg.sender];\n require(unstakeDelaySec > 0, "must specify unstake delay");\n require(unstakeDelaySec >= info.unstakeDelaySec, "cannot decrease unstake time");\n uint256 stake = info.stake + msg.value;\n require(stake > 0, "no stake specified");\n require(stake <= type(uint112).max, "stake overflow");\n deposits[msg.sender] = DepositInfo(\n info.deposit,\n true,\n uint112(stake),\n unstakeDelaySec,\n 0\n );\n emit StakeLocked(msg.sender, stake, unstakeDelaySec);\n}\n```\n
none
```\npriceShift = current price - last price\npriceShift = $600 - $1000 = -$400\n\nprofitLossTotal = (globalPosition.sizeOpenedTotal * priceShift) / current price\nprofitLossTotal = (12 ETH * -$400) / $600\nprofitLossTotal = -8 ETH\n```\n
medium
```\n// SPDX-License-Identifier: MIT\npragma solidity 0.8.18;\n\nimport "forge-std/Test.sol";\nimport "../../lib/utils/VyperDeployer.sol";\n\nimport "../IVault.sol";\nimport "../IAlchemistV2.sol";\nimport "../MintableERC721.sol";\nimport "openzeppelin/token/ERC20/IERC20.sol";\n\ncontract VaultTest is Test {\n ///@notice create a new instance of VyperDeployer\n VyperDeployer vyperDeployer = new VyperDeployer();\n\n FairFundingToken nft;\n IVault vault;\n address vaultAdd;\n IAlchemistV2 alchemist = IAlchemistV2(0x062Bf725dC4cDF947aa79Ca2aaCCD4F385b13b5c);\n IWhitelist whitelist = IWhitelist(0xA3dfCcbad1333DC69997Da28C961FF8B2879e653);\n address yieldToken = 0xa258C4606Ca8206D8aA700cE2143D7db854D168c;\n IERC20 weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);\n // pranking from big WETH holder\n address admin = 0x2fEb1512183545f48f6b9C5b4EbfCaF49CfCa6F3;\n address user1 = address(0x123);\n address user2 = address(0x456);\n \n function setUp() public {\n vm.startPrank(admin);\n nft = new FairFundingToken();\n /// @notice: I modified vault to take in admin as a parameter\n /// because of pranking issues => setting permissions\n vault = IVault(\n vyperDeployer.deployContract("Vault", abi.encode(address(nft), admin))\n );\n // to avoid having to repeatedly cast to address\n vaultAdd = address(vault);\n vault.set_alchemist(address(alchemist));\n\n // whitelist vault and users in Alchemist system, otherwise will run into permission issues\n vm.stopPrank();\n vm.startPrank(0x9e2b6378ee8ad2A4A95Fe481d63CAba8FB0EBBF9);\n whitelist.add(vaultAdd);\n whitelist.add(admin);\n whitelist.add(user1);\n whitelist.add(user2);\n vm.stopPrank();\n\n vm.startPrank(admin);\n\n // add depositors\n vault.add_depositor(admin);\n vault.add_depositor(user1);\n vault.add_depositor(user2);\n\n // check yield token is whitelisted\n assert(alchemist.isSupportedYieldToken(yieldToken));\n\n // mint NFTs to various parties\n nft.mint(admin, 1);\n nft.mint(user1, 2);\n nft.mint(user2, 3);\n \n\n // give max WETH approval to vault & alchemist\n weth.approve(vaultAdd, type(uint256).max);\n weth.approve(address(alchemist), type(uint256).max);\n\n // send some WETH to user1 & user2\n weth.transfer(user1, 10e18);\n weth.transfer(user2, 10e18);\n\n // users give WETH approval to vault and alchemist\n vm.stopPrank();\n vm.startPrank(user1);\n weth.approve(vaultAdd, type(uint256).max);\n weth.approve(address(alchemist), type(uint256).max);\n vm.stopPrank();\n vm.startPrank(user2);\n weth.approve(vaultAdd, type(uint256).max);\n weth.approve(address(alchemist), type(uint256).max);\n vm.stopPrank();\n\n // by default, msg.sender will be admin\n vm.startPrank(admin);\n }\n\n function testVaultLiquidationAfterRepayment() public {\n uint256 depositAmt = 1e18;\n // admin does a deposit\n vault.register_deposit(1, depositAmt);\n vm.stopPrank();\n\n // user1 does a deposit too\n vm.prank(user1);\n vault.register_deposit(2, depositAmt);\n\n // simulate yield: someone does partial manual repayment\n vm.prank(user2);\n alchemist.repay(address(weth), 0.1e18, vaultAdd);\n\n // mark it as claimable (burn a little bit more shares because of rounding)\n vault.withdraw_underlying_to_claim(\n alchemist.convertUnderlyingTokensToShares(yieldToken, 0.01e18) + 100,\n 0.01e18\n );\n\n vm.stopPrank();\n\n // user1 performs liquidation, it's fine\n vm.prank(user1);\n vault.liquidate(2, 0);\n\n // assert that admin has more shares than what the vault holds\n (uint256 shares, ) = alchemist.positions(vaultAdd, yieldToken);\n IVault.Position memory adminPosition = vault.positions(1);\n assertGt(adminPosition.sharesOwned, shares);\n\n vm.prank(admin);\n // now admin is unable to liquidate because of contract doesn't hold sufficient shares\n // expect Arithmetic over/underflow error\n vm.expectRevert(stdError.arithmeticError);\n vault.liquidate(1, 0);\n }\n}\n```\n
high
```\nfunction refund(\n uint256 policyIndex\_,\n uint256 week\_,\n address who\_\n) external noReenter {\n Coverage storage coverage = coverageMap[policyIndex\_][week\_][who\_];\n\n require(!coverage.refunded, "Already refunded");\n\n uint256 allCovered = coveredMap[policyIndex\_][week\_];\n uint256 amountToRefund = refundMap[policyIndex\_][week\_].mul(\n coverage.amount).div(allCovered);\n coverage.amount = coverage.amount.mul(\n coverage.premium.sub(amountToRefund)).div(coverage.premium);\n coverage.refunded = true;\n\n IERC20(baseToken).safeTransfer(who\_, amountToRefund);\n\n if (eventAggregator != address(0)) {\n IEventAggregator(eventAggregator).refund(\n policyIndex\_,\n week\_,\n who\_,\n amountToRefund\n );\n }\n}\n```\n
high
```\n} else if (key == "emaAlpha") {\n require(value > 0, "alpha should be > 0");\n governance.emaAlpha = value;\n emaAlpha2 = 10\*\*18 - governance.emaAlpha;\n emaAlpha2Ln = emaAlpha2.wln();\n```\n
medium
```\n// Call `init()` on the staking contract to initialize storage.\n(bool didInitSucceed, bytes memory initReturnData) = stakingContract.delegatecall(\n abi.encodeWithSelector(IStorageInit(0).init.selector)\n);\nif (!didInitSucceed) {\n assembly {\n revert(add(initReturnData, 0x20), mload(initReturnData))\n }\n}\n \n// Assert initialized storage values are valid\n\_assertValidStorageParams();\n```\n
medium
```\nfunction _calcQuoteAmountSellBase(\n address baseToken,\n uint256 baseAmount,\n IWooracleV2.State memory state\n ) private view returns (uint256 quoteAmount, uint256 newPrice) {\n require(state.woFeasible, "WooPPV2: !ORACLE_FEASIBLE");\n\n DecimalInfo memory decs = decimalInfo(baseToken);\n\n // gamma = k * price * base_amount; and decimal 18\n uint256 gamma;\n {\n uint256 notionalSwap = (baseAmount * state.price * decs.quoteDec) / decs.baseDec / decs.priceDec;\n require(notionalSwap <= tokenInfos[baseToken].maxNotionalSwap, "WooPPV2: !maxNotionalValue");\n\n gamma = (baseAmount * state.price * state.coeff) / decs.priceDec / decs.baseDec;\n require(gamma <= tokenInfos[baseToken].maxGamma, "WooPPV2: !gamma");\n\n // Formula: quoteAmount = baseAmount * oracle.price * (1 - oracle.k * baseAmount * oracle.price - oracle.spread)\n quoteAmount =\n (((baseAmount * state.price * decs.quoteDec) / decs.priceDec) *\n (uint256(1e18) - gamma - state.spread)) /\n 1e18 /\n decs.baseDec;\n }\n\n // newPrice = oracle.price * (1 - k * oracle.price * baseAmount)\n newPrice = ((uint256(1e18) - gamma) * state.price) / 1e18;\n }\n```\n
medium
```\nfunction contribute(address \_contributor, uint256 \_value) external payable nonReentrant auth(CONTRIBUTE\_ROLE) {\n require(state() == State.Funding, ERROR\_INVALID\_STATE);\n\n if (contributionToken == ETH) {\n require(msg.value == \_value, ERROR\_INVALID\_CONTRIBUTE\_VALUE);\n } else {\n require(msg.value == 0, ERROR\_INVALID\_CONTRIBUTE\_VALUE);\n }\n```\n
medium
```\nfunction _getTValues(uint256 tAmount)\n private\n view\n returns (\n uint256,\n uint256,\n uint256,\n uint256,\n uint256\n )\n{\n uint256 tFee = calculateTaxFee(tAmount);\n uint256 tLiquidity = calculateLiquidityFee(tAmount);\n uint256 tWallet = calculateMarketingFee(tAmount) +\n calculateDevFee(tAmount);\n uint256 tDonation = calculateDonationFee(tAmount);\n uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);\n tTransferAmount = tTransferAmount.sub(tWallet);\n tTransferAmount = tTransferAmount.sub(tDonation);\n\n return (tTransferAmount, tFee, tLiquidity, tWallet, tDonation);\n}\n```\n
none
```\nfunction getCErc20Price(ICToken cToken, address underlying) internal view returns (uint) {\n /*\n cToken Exchange rates are scaled by 10^(18 - 8 + underlying token decimals) so to scale\n the exchange rate to 18 decimals we must multiply it by 1e8 and then divide it by the\n number of decimals in the underlying token. Finally to find the price of the cToken we\n must multiply this value with the current price of the underlying token\n */\n return cToken.exchangeRateStored()\n .mulDivDown(1e8 , IERC20(underlying).decimals())\n .mulWadDown(oracle.getPrice(underlying));\n}\n```\n
high
```\nfunction changeTaxDistribution(\n uint256 newteamShare,\n uint256 newtreasuryShare\n) external onlyOwner {\n require(\n newteamShare + newtreasuryShare == SHAREDIVISOR,\n "Sum of shares must be 100"\n );\n\n teamShare = newteamShare;\n treasuryShare = newtreasuryShare;\n}\n```\n
none
```\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
```\nfunction deposit(\n address asset,\n uint256 amount\n) external onlyController returns (uint256) {\n if (asset == assetToken) {\n _depositAsset(amount);\n (, uint256 quoteAmount) = _openShort(amount);\n return quoteAmount; // @audit this mint UXD equivalent to the amount of vUSD gained\n } else if (asset == quoteToken) {\n return _processQuoteMint(amount);\n } else {\n revert UnsupportedAsset(asset);\n }\n}\n```\n
medium
```\n// If the message is version 0, then it's a migrated legacy withdrawal. We therefore need\n// to check that the legacy version of the message has not already been relayed.\nif (version == 0) {\n bytes32 oldHash = Hashing.hashCrossDomainMessageV0(_target, _sender, _message, _nonce);\n require(\n successfulMessages[oldHash] == false,\n "CrossDomainMessenger: legacy withdrawal already relayed"\n );\n}\n```\n
high
```\nrecord.amount = borrows - debtToCover;\n```\n
high
```\n\_bufferStored = \_bufferCap;\n```\n
low