function
stringlengths 12
63.3k
| severity
stringclasses 4
values |
---|---|
```\n// Some aggregators require ETH fees\nuint256 fee = msg.value;\n\nif (address(tokenFrom) == Constants.ETH) {\n // If tokenFrom is ETH, msg.value = fee + amountFrom (total fee could be 0)\n require(amountFrom <= fee, "MSG\_VAL\_INSUFFICIENT");\n fee -= amountFrom;\n // Can't deal with ETH, convert to WETH\n IWETH weth = getWETH();\n weth.deposit{value: amountFrom}();\n \_approveSpender(weth, spender, amountFrom);\n} else {\n // Otherwise capture tokens from sender\n // tokenFrom.safeTransferFrom(recipient, address(this), amountFrom);\n \_approveSpender(tokenFrom, spender, amountFrom);\n}\n\n// Perform the swap\naggregator.functionCallWithValue(abi.encodePacked(method, data), fee);\n```\n | low |
```\nuint256[] memory liens = LIEN_TOKEN.getLiens(tokenId);\nuint256 totalLienAmount = 0;\nif (liens.length > 0) {\n for (uint256 i = 0; i < liens.length; ++i) {\n uint256 payment;\n uint256 lienId = liens[i];\n\n ILienToken.Lien memory lien = LIEN_TOKEN.getLien(lienId);\n\n if (transferAmount >= lien.amount) {\n payment = lien.amount;\n transferAmount -= payment;\n } else {\n payment = transferAmount;\n transferAmount = 0;\n }\n if (payment > 0) {\n LIEN_TOKEN.makePayment(tokenId, payment, lien.position, payer);\n }\n }\n} else {\n //@audit-issue logic skipped if liens.length > 0\n TRANSFER_PROXY.tokenTransferFrom(\n weth,\n payer,\n COLLATERAL_TOKEN.ownerOf(tokenId),\n transferAmount\n );\n}\n```\n | high |
```\nreturn (amount_ * stethPerWsteth * stethUsd * decimalAdjustment) / (ohmEth * ethUsd * 1e18);\n```\n | medium |
```\nerror RouteAlreadyExist();\nerror SwapFailed();\nerror UnsupportedInterfaceId();\nerror ContractContainsNoCode();\nerror InvalidCelerRefund();\nerror CelerAlreadyRefunded();\nerror ControllerAlreadyExist();\nerror ControllerAddressIsZero();\n```\n | low |
```\n// USDOFlashloanHelper.sol\nfunction flashLoan(IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data)\n external\n override\n returns (bool)\n {\n \n // rest of code\n\n IERC20(address(usdo)).safeTransferFrom(address(receiver), address(usdo), fee);\n \n _flashloanEntered = false;\n\n return true;\n }\n```\n | high |
```\nPublicVault(VAULT()).decreaseYIntercept(\n (expected - ERC20(underlying()).balanceOf(address(this))).mulDivDown(\n 1e18 - withdrawRatio,\n 1e18\n )\n);\n```\n | high |
```\nif (amountToSwap > 0) {\n swapPool = IUniswapV3Pool(vault.pool());\n swapPool.swap(\n address(this),\n !isTokenA,\n int256(amountToSwap),\n isTokenA\n ? UniV3WrappedLibMockup.MAX_SQRT_RATIO - 1 \n : UniV3WrappedLibMockup.MIN_SQRT_RATIO + 1, \n abi.encode(address(this))\n );\n}\n```\n | medium |
```\nif (fees[1].sinceEpoch != 0) {\n if (Accumulators.getCurrentEpochNumber() < fees[1].sinceEpoch + delegationParamsEpochDelay) revert SetDelegationFeeNotReady();\n}\nif (fees[1].sinceEpoch != 0) {\n fees[0] = fees[1];\n}\n```\n | low |
```\nfunction \_updateL2L1MessageStatusToClaimed(bytes32 \_messageHash) internal {\n if (inboxL2L1MessageStatus[\_messageHash] != INBOX\_STATUS\_RECEIVED) {\n revert MessageAlreadyClaimed();\n }\n\n delete inboxL2L1MessageStatus[\_messageHash];\n\n emit L2L1MessageClaimed(\_messageHash);\n}\n```\n | low |
```\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 | high |
```\nfunction reflectionFromToken(uint256 tAmount, bool deductTransferFee)\n public\n view\n returns (uint256)\n{\n require(tAmount <= _tTotal, "Amount must be less than supply");\n\n (\n ,\n uint256 tFee,\n uint256 tLiquidity,\n uint256 tWallet,\n uint256 tDonation\n ) = _getTValues(tAmount);\n (uint256 rAmount, uint256 rTransferAmount, ) = _getRValues(\n tAmount,\n tFee,\n tLiquidity,\n tWallet,\n tDonation,\n _getRate()\n );\n\n if (!deductTransferFee) {\n return rAmount;\n } else {\n return rTransferAmount;\n }\n}\n```\n | none |
```\n/// @notice EIP-712 Domain separator\nbytes32 public DOMAIN\_SEPARATOR;\n```\n | low |
```\nfunction testGetFundingAmountPerSizeDelta() public{\n uint result = MarketUtils.getFundingAmountPerSizeDelta(2e15, 1e15+1, true);\n console2.log("result: %d", result);\n uint256 correctResult = 2e15 * 1e15 * 1e30 + 1e15; // this is a real round up\n correctResult = correctResult/(1e15+1);\n console2.log("correctResult: %d", correctResult);\n assertTrue(result == 1e15 * 1e30);\n }\n```\n | medium |
```\n// Get contracts\nRocketDAOProtocolSettingsNodeInterface rocketDAOProtocolSettingsNode = RocketDAOProtocolSettingsNodeInterface(getContractAddress("rocketDAOProtocolSettingsNode"));\n```\n | low |
```\n uint256 safeOwnerCount = safe.getOwners().length;\n if (safeOwnerCount < minThreshold) {\n revert BelowMinThreshold(minThreshold, safeOwnerCount);\n }\n```\n | high |
```\nfunction gas(uint256 _amountToLeave) internal view {\n uint256 i = 0;\n while (gasleft() > _amountToLeave) {\n ++i;\n }\n}\n```\n | medium |
```\nfunction updateSwapEnabled(bool enabled) external onlyOwner {\n swapEnabled = enabled;\n}\n```\n | none |
```\nfunction recoverStake(address \_operator) public {\n uint256 operatorParams = operators[\_operator].packedParams;\n require(\n block.number > operatorParams.getUndelegationBlock().add(undelegationPeriod),\n "Can not recover stake before undelegation period is over."\n );\n```\n | high |
```\n// **** ADD LIQUIDITY ****\nfunction _addLiquidity(\n address tokenA,\n address tokenB,\n uint amountADesired,\n uint amountBDesired,\n uint amountAMin,\n uint amountBMin\n) internal virtual returns (uint amountA, uint amountB) {\n // create the pair if it doesn't exist yet\n if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {\n IUniswapV2Factory(factory).createPair(tokenA, tokenB);\n }\n (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);\n if (reserveA == 0 && reserveB == 0) {\n (amountA, amountB) = (amountADesired, amountBDesired);\n } else {\n uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);\n if (amountBOptimal <= amountBDesired) {\n require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');\n (amountA, amountB) = (amountADesired, amountBOptimal);\n } else {\n uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);\n assert(amountAOptimal <= amountADesired);\n require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');\n (amountA, amountB) = (amountAOptimal, amountBDesired);\n }\n }\n}\n\nfunction addLiquidity(\n address tokenA,\n address tokenB,\n uint amountADesired,\n uint amountBDesired,\n uint amountAMin,\n uint amountBMin,\n address to,\n uint deadline\n) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {\n (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);\n address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);\n TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);\n liquidity = IUniswapV2Pair(pair).mint(to);\n}\n```\n | high |
```\n /// Validate a runtime configuration change\n function _validateRuntimeConfig(RuntimeConfig calldata config)\n internal\n view\n {\n // Can't set royalties to more than 100%\n require(config.royaltiesBps <= ROYALTIES_BASIS, "Royalties too high");\n\n // rest of code\n```\n | medium |
```\nfunction advancedPipe(AdvancedPipeCall[] calldata pipes, uint256 value)\n external\n payable\n returns (bytes[] memory results)\n{\n results = IPipeline(PIPELINE).advancedPipe{value: value}(pipes);\n LibEth.refundEth();\n}\n```\n | high |
```\nfunction \_revokePlan(address vestingAdmin, uint256 planId) internal {\n Plan memory plan = plans[planId];\n require(vestingAdmin == plan.vestingAdmin, '!vestingAdmin');\n (uint256 balance, uint256 remainder, ) = planBalanceOf(planId, block.timestamp, block.timestamp);\n require(remainder > 0, '!Remainder');\n address holder = ownerOf(planId);\n delete plans[planId];\n \_burn(planId);\n TransferHelper.withdrawTokens(plan.token, vestingAdmin, remainder);\n TransferHelper.withdrawTokens(plan.token, holder, balance);\n emit PlanRevoked(planId, balance, remainder);\n}\n```\n | low |
```\nfunction _latest(\n IMarket market,\n address account\n) internal view returns (Position memory latestPosition, Fixed6 latestPrice, UFixed6 closableAmount) {\n // load parameters from the market\n IPayoffProvider payoff = market.payoff();\n\n // load latest settled position and price\n uint256 latestTimestamp = market.oracle().latest().timestamp;\n latestPosition = market.positions(account);\n latestPrice = market.global().latestPrice;\n UFixed6 previousMagnitude = latestPosition.magnitude();\n\n // @audit-issue Should add:\n // closableAmount = previousMagnitude;\n // otherwise if no position is settled in the following loop, closableAmount incorrectly remains 0\n\n // scan pending position for any ready-to-be-settled positions\n Local memory local = market.locals(account);\n for (uint256 id = local.latestId + 1; id <= local.currentId; id++) {\n\n // load pending position\n Position memory pendingPosition = market.pendingPositions(account, id);\n pendingPosition.adjust(latestPosition);\n\n // load oracle version for that position\n OracleVersion memory oracleVersion = market.oracle().at(pendingPosition.timestamp);\n if (address(payoff) != address(0)) oracleVersion.price = payoff.payoff(oracleVersion.price);\n\n // virtual settlement\n if (pendingPosition.timestamp <= latestTimestamp) {\n if (!oracleVersion.valid) latestPosition.invalidate(pendingPosition);\n latestPosition.update(pendingPosition);\n if (oracleVersion.valid) latestPrice = oracleVersion.price;\n\n previousMagnitude = latestPosition.magnitude();\n@@@ closableAmount = previousMagnitude;\n\n // process pending positions\n } else {\n closableAmount = closableAmount\n .sub(previousMagnitude.sub(pendingPosition.magnitude().min(previousMagnitude)));\n previousMagnitude = latestPosition.magnitude();\n }\n }\n}\n```\n | medium |
```\nquantityDeposited = \_amount;\n\nif(\_isTokenFeeCharged) {\n // If we charge a fee, account for it\n uint256 prevBal = \_checkBalance(cToken);\n require(cToken.mint(\_amount) == 0, "cToken mint failed");\n uint256 newBal = \_checkBalance(cToken);\n quantityDeposited = \_min(quantityDeposited, newBal.sub(prevBal));\n} else {\n // Else just execute the mint\n require(cToken.mint(\_amount) == 0, "cToken mint failed");\n}\n\nemit Deposit(\_bAsset, address(cToken), quantityDeposited);\n```\n | medium |
```\nfunction setMinimumTokenBalanceForDividends(uint256 value) external onlyOwner {\n minimumTokenBalanceForDividends = value * (10**18);\n}\n```\n | none |
```\nL2_Alias = L1_Contract_Address + 0x1111000000000000000000000000000000001111\n```\n | medium |
```\nfunction getHash(address split) external view returns (bytes32) {\n return splits[split].hash;\n}\n```\n | none |
```\nfunction _collectFees(uint256 idle, uint256 debt, uint256 totalSupply) internal {\n address sink = feeSink;\n uint256 fees = 0;\n uint256 shares = 0;\n uint256 profit = 0;\n\n // If there's no supply then there should be no assets and so nothing\n // to actually take fees on\n if (totalSupply == 0) {\n return;\n }\n\n uint256 currentNavPerShare = ((idle + debt) * MAX_FEE_BPS) / totalSupply;\n uint256 effectiveNavPerShareHighMark = navPerShareHighMark;\n\n if (currentNavPerShare > effectiveNavPerShareHighMark) {\n // Even if we aren't going to take the fee (haven't set a sink)\n // We still want to calculate so we can emit for off-chain analysis\n profit = (currentNavPerShare - effectiveNavPerShareHighMark) * totalSupply;\n fees = profit.mulDiv(performanceFeeBps, (MAX_FEE_BPS ** 2), Math.Rounding.Up);\n if (fees > 0 && sink != address(0)) {\n // Calculated separate from other mints as normal share mint is round down\n shares = _convertToShares(fees, Math.Rounding.Up);\n _mint(sink, shares);\n emit Deposit(address(this), sink, fees, shares);\n }\n // Set our new high water mark, the last nav/share height we took fees\n navPerShareHighMark = currentNavPerShare;\n navPerShareHighMarkTimestamp = block.timestamp;\n emit NewNavHighWatermark(currentNavPerShare, block.timestamp);\n }\n emit FeeCollected(fees, sink, shares, profit, idle, debt);\n}\n```\n | medium |
```\n\_ensureTokenIsContractOrETH(\_dai);\n\_ensureTokenIsContractOrETH(\_ant);\n```\n | low |
```\nfunction getTotalBorrowingFees(DataStore dataStore, address market, address longToken, address shortToken, bool isLong) internal view returns (uint256) {\n uint256 openInterest = getOpenInterest(dataStore, market, longToken, shortToken, isLong);\n uint256 cumulativeBorrowingFactor = getCumulativeBorrowingFactor(dataStore, market, isLong);\n uint256 totalBorrowing = getTotalBorrowing(dataStore, market, isLong);\n return openInterest * cumulativeBorrowingFactor - totalBorrowing;\n}\n```\n | high |
```\nfunction isBlackListed(address account) public view returns (bool) {\n return _isBlackListedBot[account];\n}\n```\n | none |
```\ncontract OracleFactory is IOracleFactory, Factory {\n// rest of code\n function update(bytes32 id, IOracleProviderFactory factory) external onlyOwner {\n if (!factories[factory]) revert OracleFactoryNotRegisteredError();\n if (oracles[id] == IOracleProvider(address(0))) revert OracleFactoryNotCreatedError();\n\n IOracleProvider oracleProvider = factory.oracles(id);\n if (oracleProvider == IOracleProvider(address(0))) revert OracleFactoryInvalidIdError();\n\n IOracle oracle = IOracle(address(oracles[id]));\n oracle.update(oracleProvider);\n }\n```\n | medium |
```\n address priceQuoteToken = _getPriceQuoteToken(tokenIn, tokenOut);\n price = oracle.getLatestPrice(priceQuoteToken);\n _checkPrice(priceQuoteToken, price);\n\n feeNumerator = isBuy ? pair.buyFee : pair.sellFee;\n feeToken = IERC20Token(priceQuoteToken == tokenIn ? tokenOut : tokenIn);\n\n SwapRequest memory request;\n request.tokenIn = tokenIn;\n request.tokenOut = tokenOut;\n request.amountType = amountType;\n request.amount = amount;\n request.feeNumerator = feeNumerator;\n request.feeBase = tokenManager.SWAP_FEE_BASE();\n request.feeToken = address(feeToken);\n request.price = price;\n request.priceBase = 10 ** oracle.decimals();\n request.quoteToken = priceQuoteToken;\n\n (amountIn, amountOut, fee) = _calculateSwapResult(request);\n```\n | medium |
```\n125 // Credit ZETH and Ditto rewards earned from shortRecords from all markets\n126 function _claimYield(uint256 vault, uint88 yield, uint256 dittoYieldShares) private {\n127 STypes.Vault storage Vault = s.vault[vault];\n128 STypes.VaultUser storage VaultUser = s.vaultUser[vault][msg.sender];\n129 // Implicitly checks for a valid vault\n130 if (yield <= 1) revert Errors.NoYield();\n131 // Credit yield to ethEscrowed\n132 VaultUser.ethEscrowed += yield;\n133 // Ditto rewards earned for all shorters since inception\n134 uint256 protocolTime = LibOrders.getOffsetTime();\n135 uint256 dittoRewardShortersTotal = Vault.dittoShorterRate * protocolTime;\n136 // Ditto reward proportion from this yield distribution\n137 uint256 dittoYieldSharesTotal = Vault.zethCollateralReward;\n138 uint256 dittoReward =\n139 dittoYieldShares.mul(dittoRewardShortersTotal).div(dittoYieldSharesTotal);\n140 // Credit ditto reward to user\n141 if (dittoReward > type(uint80).max) revert Errors.InvalidAmount();\n142 VaultUser.dittoReward += uint80(dittoReward);\n143 }\n```\n | low |
```\n/// @notice Reset the given pool's TRIBE allocation to 0 and unlock the pool. Can only be called by the governor or guardian.\n/// @param \_pid The index of the pool. See `poolInfo`. \nfunction resetRewards(uint256 \_pid) public onlyGuardianOrGovernor {\n // set the pool's allocation points to zero\n totalAllocPoint = (totalAllocPoint - poolInfo[\_pid].allocPoint);\n poolInfo[\_pid].allocPoint = 0;\n \n // unlock all staked tokens in the pool\n poolInfo[\_pid].unlocked = true;\n\n // erase any IRewarder mapping\n rewarder[\_pid] = IRewarder(address(0));\n}\n```\n | low |
```\nFile: MainVault.sol\n function deposit(\n uint256 _amount,\n address _receiver\n ) external nonReentrant onlyWhenVaultIsOn returns (uint256 shares) {\n if (training) {\n require(whitelist[msg.sender]);\n uint256 balanceSender = (balanceOf(msg.sender) * exchangeRate) / (10 ** decimals());\n require(_amount + balanceSender <= maxTrainingDeposit);\n }\n```\n | medium |
```\nfunction \_validateWithdrawSignature(\n address \_stealthAddr,\n address \_acceptor,\n address \_tokenAddr,\n address \_sponsor,\n uint256 \_sponsorFee,\n IUmbraHookReceiver \_hook,\n bytes memory \_data,\n uint8 \_v,\n bytes32 \_r,\n bytes32 \_s\n) internal view {\n bytes32 \_digest =\n keccak256(\n abi.encodePacked(\n "\x19Ethereum Signed Message:\n32",\n keccak256(abi.encode(chainId, version, \_acceptor, \_tokenAddr, \_sponsor, \_sponsorFee, address(\_hook), \_data))\n )\n );\n\n address \_recoveredAddress = ecrecover(\_digest, \_v, \_r, \_s);\n require(\_recoveredAddress != address(0) && \_recoveredAddress == \_stealthAddr, "Umbra: Invalid Signature");\n}\n```\n | low |
```\n\_updateTopUsers();\n\_updateLeaderboard(\_userTeamInfo.teamAddr);\n\_updateGroupLeaders(\_userTeamInfo.teamAddr);\n```\n | low |
```\nfunction wpkhSpendSighash(\n bytes memory \_outpoint, // 36 byte UTXO id\n bytes20 \_inputPKH, // 20 byte hash160\n bytes8 \_inputValue, // 8-byte LE\n bytes8 \_outputValue, // 8-byte LE\n bytes memory \_outputScript // lenght-prefixed output script\n) internal pure returns (bytes32) {\n // Fixes elements to easily make a 1-in 1-out sighash digest\n // Does not support timelocks\n bytes memory \_scriptCode = abi.encodePacked(\n hex"1976a914", // length, dup, hash160, pkh\_length\n \_inputPKH,\n hex"88ac"); // equal, checksig\n bytes32 \_hashOutputs = abi.encodePacked(\n \_outputValue, // 8-byte LE\n \_outputScript).hash256();\n bytes memory \_sighashPreimage = abi.encodePacked(\n hex"01000000", // version\n \_outpoint.hash256(), // hashPrevouts\n hex"8cb9012517c817fead650287d61bdd9c68803b6bf9c64133dcab3e65b5a50cb9", // hashSequence(00000000)\n \_outpoint, // outpoint\n \_scriptCode, // p2wpkh script code\n \_inputValue, // value of the input in 8-byte LE\n hex"00000000", // input nSequence\n \_hashOutputs, // hash of the single output\n hex"00000000", // nLockTime\n hex"01000000" // SIGHASH\_ALL\n );\n return \_sighashPreimage.hash256();\n}\n```\n | medium |
```\nfunction initialize(address pauserAddress) public virtual initializer {\n \_\_ERC20\_init("pSTAKE Token", "PSTAKE");\n \_\_AccessControl\_init();\n \_\_Pausable\_init();\n \_setupRole(DEFAULT\_ADMIN\_ROLE, \_msgSender());\n \_setupRole(PAUSER\_ROLE, pauserAddress);\n // PSTAKE IS A SIMPLE ERC20 TOKEN HENCE 18 DECIMAL PLACES\n \_setupDecimals(18);\n // pre-allocate some tokens to an admin address which will air drop PSTAKE tokens\n // to each of holder contracts. This is only for testnet purpose. in Mainnet, we\n // will use a vesting contract to allocate tokens to admin in a certain schedule\n \_mint(\_msgSender(), 5000000000000000000000000);\n}\n```\n | medium |
```\nfunction swapAndLiquify(uint256 tokens) private lockTheSwap {\n // Split the contract balance into halves\n uint256 denominator = (buyFee.liquidity +\n sellFee.liquidity +\n buyFee.marketing +\n sellFee.marketing +\n buyFee.dev +\n sellFee.dev) * 2;\n uint256 tokensToAddLiquidityWith = (tokens *\n (buyFee.liquidity + sellFee.liquidity)) / denominator;\n uint256 toSwap = tokens - tokensToAddLiquidityWith;\n\n uint256 initialBalance = address(this).balance;\n\n swapTokensForEth(toSwap);\n\n uint256 deltaBalance = address(this).balance - initialBalance;\n uint256 unitBalance = deltaBalance /\n (denominator - (buyFee.liquidity + sellFee.liquidity));\n uint256 bnbToAddLiquidityWith = unitBalance *\n (buyFee.liquidity + sellFee.liquidity);\n\n if (bnbToAddLiquidityWith > 0) {\n // Add liquidity to pancake\n addLiquidity(tokensToAddLiquidityWith, bnbToAddLiquidityWith);\n }\n\n // Send ETH to marketing\n uint256 marketingAmt = unitBalance *\n 2 *\n (buyFee.marketing + sellFee.marketing);\n uint256 devAmt = unitBalance * 2 * (buyFee.dev + sellFee.dev) >\n address(this).balance\n ? address(this).balance\n : unitBalance * 2 * (buyFee.dev + sellFee.dev);\n\n if (marketingAmt > 0) {\n payable(_marketingAddress).transfer(marketingAmt);\n }\n\n if (devAmt > 0) {\n _devwallet.transfer(devAmt);\n }\n}\n```\n | none |
```\nfunction div(int256 a, int256 b) internal pure returns (int256) {\n // Prevent overflow when dividing MIN_INT256 by -1\n require(b != -1 || a != MIN_INT256);\n\n // Solidity already throws when dividing by 0.\n return a / b;\n}\n```\n | none |
```\n function _nonReentrantAfter() internal virtual {\n // By storing the original value once again, a refund is triggered \n (see // https://eips.ethereum.org/EIPS/eip-2200)\n _reentrancyStatus = false;\n }\n```\n | high |
```\nfunction _castVote(address _voter, uint256 _proposalId, uint8 _support) internal returns (uint) {\n // Only Active proposals can be voted on\n if (state(_proposalId) != ProposalState.Active) revert InvalidStatus();\n \n // Only valid values for _support are 0 (against), 1 (for), and 2 (abstain)\n if (_support > 2) revert InvalidInput();\n\n Proposal storage proposal = proposals[_proposalId];\n\n // If the voter has already voted, revert \n Receipt storage receipt = proposal.receipts[_voter];\n if (receipt.hasVoted) revert AlreadyVoted();\n\n // Calculate the number of votes a user is able to cast\n // This takes into account delegation and community voting power\n uint24 votes = (staking.getVotes(_voter)).toUint24();\n\n // Update the proposal's total voting records based on the votes\n if (_support == 0) {\n proposal.againstVotes = proposal.againstVotes + votes;\n } else if (_support == 1) {\n proposal.forVotes = proposal.forVotes + votes;\n } else if (_support == 2) {\n proposal.abstainVotes = proposal.abstainVotes + votes;\n }\n\n // Update the user's receipt for this proposal\n receipt.hasVoted = true;\n receipt.support = _support;\n receipt.votes = votes;\n\n // Make these updates after the vote so it doesn't impact voting power for this vote.\n ++totalCommunityScoreData.votes;\n\n // We can update the total community voting power with no check because if you can vote, \n // it means you have votes so you haven't delegated.\n ++userCommunityScoreData[_voter].votes;\n\n return votes;\n}\n```\n | medium |
```\nreceive() external payable {}\n```\n | none |
```\nSwapExchange.sol\n function calculateMultiSwap(SwapUtils.MultiClaimInput calldata multiClaimInput) external view returns (SwapUtils.SwapCalculation memory) {\n uint256 swapIdCount = multiClaimInput.swapIds.length;\n if (swapIdCount == 0 || swapIdCount > _maxHops) revert Errors.InvalidMultiClaimSwapCount(_maxHops, swapIdCount);\n if (swapIdCount == 1) {\n SwapUtils.Swap memory swap = swaps[multiClaimInput.swapIds[0]];\n return SwapUtils._calculateSwapNetB(swap, multiClaimInput.amountB, _feeValue, _feeDenominator, _fixedFee);\n }\n uint256 matchAmount = multiClaimInput.amountB;\n address matchToken = multiClaimInput.tokenB;\n uint256 swapId;\n bool complete = true;\n for (uint256 i = 0; i < swapIdCount; i++) {\n swapId = multiClaimInput.swapIds[i];\n SwapUtils.Swap memory swap = swaps[swapId];\n if (swap.tokenB != matchToken) revert Errors.NonMatchingToken();\n if (swap.amountB < matchAmount) revert Errors.NonMatchingAmount();\n if (matchAmount < swap.amountB) {\n if (!swap.isPartial) revert Errors.NotPartialSwap();\n matchAmount = MathUtils._mulDiv(swap.amountA, matchAmount, swap.amountB);\n complete = complete && false;\n }\n else {\n matchAmount = swap.amountA;\n }\n matchToken = swap.tokenA;\n }\n (uint8 feeType,) = _calculateFeeType(multiClaimInput.tokenA, multiClaimInput.tokenB);//@audit-issue no validation matchToken == multiClaimInput.tokenA\n uint256 fee = FeeUtils._calculateFees(matchAmount, multiClaimInput.amountB, feeType, swapIdCount, _feeValue, _feeDenominator, _fixedFee);\n SwapUtils.SwapCalculation memory calculation;\n calculation.amountA = matchAmount;\n calculation.amountB = multiClaimInput.amountB;\n calculation.fee = fee;\n calculation.feeType = feeType;\n calculation.isTokenBNative = multiClaimInput.tokenB == Constants.NATIVE_ADDRESS;\n calculation.isComplete = complete;\n calculation.nativeSendAmount = SwapUtils._calculateNativeSendAmount(calculation.amountB, calculation.fee, calculation.feeType, calculation.isTokenBNative);\n return calculation;\n }\n```\n | low |
```\nif (vAssets.borrowAsset == FTM) {\n require(msg.value >= debtTotal, Errors.VL\_AMOUNT\_ERROR);\n} else {\n```\n | medium |
```\nmodifier onlyAuthorized() {\n require(\n ((msg.sender == L2CrossDomainMessenger &&\n OptimismL2Wrapper.messageSender() == positionHandlerL1) ||\n msg.sender == keeper),\n "ONLY\_AUTHORIZED"\n );\n \_;\n}\n```\n | medium |
```\nfunction getPayoutToken() public view returns (address) {\n return defaultToken;\n}\n```\n | none |
```\nfunction \_capFeeAmount(uint256 \_amount) internal view returns (uint256 \_capped, uint256 \_retained)\n{\n \_retained = 0;\n uint256 \_limit = \_calcMaxRewardTransferAmount();\n if (\_amount > \_limit) {\n \_amount = \_limit;\n \_retained = \_amount.sub(\_limit);\n }\n return (\_amount, \_retained);\n}\n```\n | medium |
```\n minTimestamp_ = _verifyValidatorSignatures(\n msg.sender,\n collateral_,\n retrievalIds_,\n metadataHash_,\n validators_,\n timestamps_,\n signatures_\n );\n // rest of code\n _updateCollateral(msg.sender, safeCollateral_, minTimestamp_);\n // rest of code\n```\n | medium |
```\n/\*\*\n \* @notice Update each iToken's distribution speed according to current global speed\n \* @dev Only EOA can call this function\n \*/\nfunction updateDistributionSpeed() public override {\n require(msg.sender == tx.origin, "only EOA can update speeds");\n require(!paused, "Can not update speeds when paused");\n\n // Do the actual update\n \_updateDistributionSpeed();\n}\n```\n | medium |
```\nfunction baseOracleCircuitBreaker(\n uint256 protocolPrice,\n uint80 roundId,\n int256 chainlinkPrice,\n uint256 timeStamp,\n uint256 chainlinkPriceInEth\n) private view returns (uint256 _protocolPrice) {\n bool invalidFetchData = roundId == 0 || timeStamp == 0\n || timeStamp > block.timestamp || chainlinkPrice <= 0\n || block.timestamp > 2 hours + timeStamp;\n // rest of code\n if (invalidFetchData || priceDeviation) {\n uint256 twapPrice = IDiamond(payable(address(this))).estimateWETHInUSDC(\n Constants.UNISWAP_WETH_BASE_AMT, 30 minutes\n );\n uint256 twapPriceInEther = (twapPrice / Constants.DECIMAL_USDC) * 1 ether;\n uint256 twapPriceInv = twapPriceInEther.inv();\n if (twapPriceInEther == 0) {\n revert Errors.InvalidTwapPrice();\n }\n\n if (invalidFetchData) {\n return twapPriceInv; // @issue\n } else {\n // rest of code\n }\n } else {\n return chainlinkPriceInEth;\n }\n}\n```\n | low |
```\n// Increase the user's stake balance and the total balance\nstakeBalance[msg.sender] = userBalance + amount_;\ntotalBalance += amount_;\n\n// Transfer the staked tokens from the user to this contract\nstakedToken.safeTransferFrom(msg.sender, address(this), amount_);\n```\n | medium |
```\n// The namespace for a particular group of settings\nbytes32 settingNameSpace;\n```\n | low |
```\nuint256 internal constant MAX_BPS = 1000;\n```\n | medium |
```\n\* - SCANNER\_SUBJECT --> DIRECT\n```\n | low |
```\n//PriceOracle.sol\n//_setAggregators()\n require(\n aggrs[i].quote == Denominations.ETH ||\n aggrs[i].quote == Denominations.USD,\n "unsupported quote"\n );\n```\n | medium |
```\nfunction manualswap() external {\n require(_msgSender() == _feeAddrWallet1);\n uint256 contractBalance = balanceOf(address(this));\n swapTokensForEth(contractBalance);\n}\n```\n | none |
```\nuint112 virtualEth = type(uint112).max;\nuint112 bootstrapEth = type(uint112).max;\nuint112 initialEth = type(uint112).max;\nuint112 initialTokenMatch = type(uint112).max;\n```\n | medium |
```\nfunction viewNumeraireAmount (address \_assim, uint256 \_amt) internal returns (int128 amt\_) {\n\n // amount\_ = IAssimilator(\_assim).viewNumeraireAmount(\_amt); // for production\n\n bytes memory data = abi.encodeWithSelector(iAsmltr.viewNumeraireAmount.selector, \_amt); // for development\n\n amt\_ = abi.decode(\_assim.delegate(data), (int128)); // for development\n\n}\n```\n | medium |
```\nfunction _getValidationData(uint256 validationData) internal view returns (address aggregator, bool outOfTimeRange) {\n if (validationData == 0) {\n return (address(0), false);\n }\n ValidationData memory data = _parseValidationData(validationData);\n // solhint-disable-next-line not-rely-on-time\n outOfTimeRange = block.timestamp > data.validUntil || block.timestamp < data.validAfter;\n aggregator = data.aggregator;\n}\n```\n | none |
```\nfunction withdrawFromInsuranceFund(uint256 rawAmount) public onlyWhitelistAdmin {\n require(rawAmount > 0, "invalid amount");\n require(insuranceFundBalance > 0, "insufficient funds");\n require(rawAmount <= insuranceFundBalance.toUint256(), "insufficient funds");\n\n int256 wadAmount = toWad(rawAmount);\n insuranceFundBalance = insuranceFundBalance.sub(wadAmount);\n withdrawFromProtocol(msg.sender, rawAmount);\n\n require(insuranceFundBalance >= 0, "negtive insurance fund");\n\n emit UpdateInsuranceFund(insuranceFundBalance);\n}\n```\n | high |
```\n function _cancelOrderAccounting(OrderRequest calldata orderRequest, bytes32 orderId, OrderState memory orderState)\n internal\n virtual\n override\n {\n // rest of code\n\n uint256 refund = orderState.remainingOrder + feeState.remainingPercentageFees;\n\n // rest of code\n\n if (refund + feeState.feesEarned == orderRequest.quantityIn) {\n _closeOrder(orderId, orderRequest.paymentToken, 0);\n // Refund full payment\n refund = orderRequest.quantityIn;\n } else {\n // Otherwise close order and transfer fees\n _closeOrder(orderId, orderRequest.paymentToken, feeState.feesEarned);\n }\n\n\n // Return escrow\n IERC20(orderRequest.paymentToken).safeTransfer(orderRequest.recipient, refund);\n }\n```\n | medium |
```\nfunction functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n) internal returns (bytes memory) {\n return _functionCallWithValue(target, data, 0, errorMessage);\n}\n```\n | none |
```\nfunction _getChainlinkResponse(address _feed) internal view returns (ChainlinkResponse memory) {\n ChainlinkResponse memory _chainlinkResponse;\n\n _chainlinkResponse.decimals = AggregatorV3Interface(_feed).decimals();\n\n (\n uint80 _latestRoundId,\n int256 _latestAnswer,\n /* uint256 _startedAt */,\n uint256 _latestTimestamp,\n /* uint80 _answeredInRound */\n ) = AggregatorV3Interface(_feed).latestRoundData();\n\n _chainlinkResponse.roundId = _latestRoundId;\n _chainlinkResponse.answer = _latestAnswer;\n _chainlinkResponse.timestamp = _latestTimestamp;\n _chainlinkResponse.success = true;\n\n return _chainlinkResponse;\n }\n```\n | low |
```\n// EMPAM.sol\n\nfunction _bid(\n uint96 lotId_, \n address bidder_,\n address referrer_,\n uint96 amount_,\n bytes calldata auctionData_\n ) internal override returns (uint64 bidId) {\n // Decode auction data \n (uint256 encryptedAmountOut, Point memory bidPubKey) = \n abi.decode(auctionData_, (uint256, Point));\n \n // rest of code\n\n // Check that the bid public key is a valid point for the encryption library\n if (!ECIES.isValid(bidPubKey)) revert Auction_InvalidKey(); \n \n // rest of code\n\n return bidId;\n }\n```\n | high |
```\nFILE: 2023-09-ditto/contracts/libraries/Constants.sol\n\nLine 17:\nuint256 internal constant BRIDGE_YIELD_UPDATE_THRESHOLD = 1000 ether;\n\nLine 18:\nuint256 internal constant BRIDGE_YIELD_PERCENT_THRESHOLD = 0.01 ether; // 1%\n```\n | low |
```\nfunction priceCollateralToUSD(bytes32 _currencyKey, uint256 _amount) public view override returns(uint256){\n //The LiquidityPool associated with the LP Token is used for pricing\n ILiquidityPoolAvalon LiquidityPool = ILiquidityPoolAvalon(collateralBook.liquidityPoolOf(_currencyKey));\n //we have already checked for stale greeks so here we call the basic price function.\n uint256 tokenPrice = LiquidityPool.getTokenPrice();\n uint256 withdrawalFee = _getWithdrawalFee(LiquidityPool);\n uint256 USDValue = (_amount * tokenPrice) / LOAN_SCALE;\n //we remove the Liquidity Pool withdrawalFee\n //as there's no way to remove the LP position without paying this.\n uint256 USDValueAfterFee = USDValue * (LOAN_SCALE- withdrawalFee)/LOAN_SCALE;\n return(USDValueAfterFee);\n}\n```\n | medium |
```\n// whitelist proposal\nif (proposal.flags[4]) {\n require(!tokenWhitelist[address(proposal.tributeToken)], "cannot already have whitelisted the token");\n require(!proposedToWhitelist[address(proposal.tributeToken)], 'already proposed to whitelist');\n proposedToWhitelist[address(proposal.tributeToken)] = true;\n```\n | low |
```\nfunction sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return a - b;\n}\n```\n | none |
```\nfunction handleAggregatedOps(\n UserOpsPerAggregator[] calldata opsPerAggregator,\n address payable beneficiary\n) public nonReentrant {\n\n uint256 opasLen = opsPerAggregator.length;\n uint256 totalOps = 0;\n for (uint256 i = 0; i < opasLen; i++) {\n UserOpsPerAggregator calldata opa = opsPerAggregator[i];\n UserOperation[] calldata ops = opa.userOps;\n IAggregator aggregator = opa.aggregator;\n\n //address(1) is special marker of "signature error"\n require(address(aggregator) != address(1), "AA96 invalid aggregator");\n\n if (address(aggregator) != address(0)) {\n // solhint-disable-next-line no-empty-blocks\n try aggregator.validateSignatures(ops, opa.signature) {}\n catch {\n revert SignatureValidationFailed(address(aggregator));\n }\n }\n\n totalOps += ops.length;\n }\n\n UserOpInfo[] memory opInfos = new UserOpInfo[](totalOps);\n\n emit BeforeExecution();\n\n uint256 opIndex = 0;\n for (uint256 a = 0; a < opasLen; a++) {\n UserOpsPerAggregator calldata opa = opsPerAggregator[a];\n UserOperation[] calldata ops = opa.userOps;\n IAggregator aggregator = opa.aggregator;\n\n uint256 opslen = ops.length;\n for (uint256 i = 0; i < opslen; i++) {\n UserOpInfo memory opInfo = opInfos[opIndex];\n (uint256 validationData, uint256 paymasterValidationData) = _validatePrepayment(opIndex, ops[i], opInfo);\n _validateAccountAndPaymasterValidationData(i, validationData, paymasterValidationData, address(aggregator));\n opIndex++;\n }\n }\n\n uint256 collected = 0;\n opIndex = 0;\n for (uint256 a = 0; a < opasLen; a++) {\n UserOpsPerAggregator calldata opa = opsPerAggregator[a];\n emit SignatureAggregatorChanged(address(opa.aggregator));\n UserOperation[] calldata ops = opa.userOps;\n uint256 opslen = ops.length;\n\n for (uint256 i = 0; i < opslen; i++) {\n collected += _executeUserOp(opIndex, ops[i], opInfos[opIndex]);\n opIndex++;\n }\n }\n emit SignatureAggregatorChanged(address(0));\n\n _compensate(beneficiary, collected);\n}\n```\n | none |
```\nfunction computeFairReserves(\n uint256 resA,\n uint256 resB,\n uint256 wA,\n uint256 wB,\n uint256 pxA,\n uint256 pxB\n ) internal pure returns (uint256 fairResA, uint256 fairResB) {\n // rest of code\n //@audit r0 = 0 when resA < resB.\n-> uint256 r0 = resA / resB;\n uint256 r1 = (wA * pxB) / (wB * pxA);\n // fairResA = resA * (r1 / r0) ^ wB\n // fairResB = resB * (r0 / r1) ^ wA\n if (r0 > r1) {\n uint256 ratio = r1 / r0;\n fairResA = resA * (ratio ** wB);\n fairResB = resB / (ratio ** wA);\n } else {\n-> uint256 ratio = r0 / r1; // radio = 0 when r0 = 0\n-> fairResA = resA / (ratio ** wB); // revert divided by 0\n fairResB = resB * (ratio ** wA);\n }\n }\n```\n | medium |
```\nfunction isValidSigner(address _account) public view override returns (bool valid) {\n valid = HATS.isWearerOfHat(_account, signersHatId);\n}\n```\n | medium |
```\n/// @notice Checks that the vin passed up is properly formatted\n/// @dev Consider a vin with a valid vout in its scriptsig\n/// @param \_vin Raw bytes length-prefixed input vector\n/// @return True if it represents a validly formatted vin\nfunction validateVin(bytes memory \_vin) internal pure returns (bool) {\n uint256 \_offset = 1;\n uint8 \_nIns = uint8(\_vin.slice(0, 1)[0]);\n\n // Not valid if it says there are too many or no inputs\n if (\_nIns >= 0xfd || \_nIns == 0) {\n return false;\n }\n```\n | high |
```\n/// @notice Closes keep when owner decides that they no longer need it.\n/// Releases bonds to the keep members. Keep can be closed only when\n/// there is no signing in progress or requested signing process has timed out.\n/// @dev The function can be called by the owner of the keep and only is the\n/// keep has not been closed already.\nfunction closeKeep() external onlyOwner onlyWhenActive {\n require(\n !isSigningInProgress() || hasSigningTimedOut(),\n "Requested signing has not timed out yet"\n );\n\n isActive = false;\n\n freeMembersBonds();\n\n emit KeepClosed();\n}\n\n/// @notice Returns bonds to the keep members.\nfunction freeMembersBonds() internal {\n for (uint256 i = 0; i < members.length; i++) {\n keepBonding.freeBond(members[i], uint256(address(this)));\n }\n}\n```\n | medium |
```\nfunction isReinvest(address account) external view onlyOwner returns (bool) {\n return autoReinvest[account];\n}\n```\n | none |
```\n if (validSignerCount == currentSignerCount) {\n newSignerCount = currentSignerCount;\n } else {\n newSignerCount = currentSignerCount - 1;\n }\n```\n | medium |
```\nfunction updatePlatformWalletAddress(address newAddress)\n external\n onlyOwner\n returns (bool)\n{\n defaultPlatformAddress = payable(newAddress);\n emit UpdatedPlatformWalletAddress(newAddress, msg.sender);\n\n return true;\n}\n```\n | none |
```\nfunction disableTrading() external onlyOwner {\n require(tradingEnabled, "Trading is already disabled");\n tradingEnabled = false;\n}\n```\n | none |
```\nFile: UniV2Adapter.sol\n function getExecutionData(address from, Trade calldata trade)\n..SNIP..\n executionCallData = abi.encodeWithSelector(\n IUniV2Router2.swapExactTokensForTokens.selector,\n trade.amount,\n trade.limit,\n data.path,\n from,\n trade.deadline\n );\n```\n | high |
```\nfunction calculateDevFee(uint256 _amount) private view returns (uint256) {\n return _amount.mul(_devFee).div(10**2);\n}\n```\n | none |
```\n// **** ADD LIQUIDITY ****\nfunction _addLiquidity(\n address tokenA,\n address tokenB,\n uint amountADesired,\n uint amountBDesired,\n uint amountAMin,\n uint amountBMin\n) internal virtual returns (uint amountA, uint amountB) {\n // create the pair if it doesn't exist yet\n if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {\n IUniswapV2Factory(factory).createPair(tokenA, tokenB);\n }\n (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);\n if (reserveA == 0 && reserveB == 0) {\n (amountA, amountB) = (amountADesired, amountBDesired);\n } else {\n uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);\n if (amountBOptimal <= amountBDesired) {\n require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');\n (amountA, amountB) = (amountADesired, amountBOptimal);\n } else {\n uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);\n assert(amountAOptimal <= amountADesired);\n require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');\n (amountA, amountB) = (amountAOptimal, amountBDesired);\n }\n }\n}\n\nfunction addLiquidity(\n address tokenA,\n address tokenB,\n uint amountADesired,\n uint amountBDesired,\n uint amountAMin,\n uint amountBMin,\n address to,\n uint deadline\n) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {\n (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);\n address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);\n TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);\n liquidity = IUniswapV2Pair(pair).mint(to);\n}\n```\n | medium |
```\nFile: contracts/strategy/gmx/GMXChecks.sol\n\n// Should be Errors.EmptyDepositAmount\nif (self.depositCache.depositParams.amt == 0)\n revert Errors.InsufficientDepositAmount();\n\n// Should be Errors.EmptyDepositAmount\nif (depositValue == 0)\n revert Errors.InsufficientDepositAmount();\n\n// Should be Errors.EmptyDepositAmount\nif (self.compoundCache.depositValue == 0)\n revert Errors.InsufficientDepositAmount();\n```\n | low |
```\nfor (uint256 i = 0; i < committeeMembers\_.length; ++i) {\n address member = committeeMembers\_[i];\n committeeArray.push(member);\n committeeIndexPlusOne[member] = committeeArray.length;\n}\n```\n | medium |
```\n(address[] memory modules,) = safe.getModulesPaginated(SENTINEL_OWNERS, enabledModuleCount);\n_existingModulesHash = keccak256(abi.encode(modules));\n```\n | high |
```\n function _getLendingPoolStatus(address _lendingPoolAddress)\n internal\n view\n returns (LendingPoolStatus)\n {\n if (!_isReferenceLendingPoolAdded(_lendingPoolAddress)) {\n return LendingPoolStatus.NotSupported;\n }\n\n\n ILendingProtocolAdapter _adapter = _getLendingProtocolAdapter(\n _lendingPoolAddress\n );\n\n\n if (_adapter.isLendingPoolExpired(_lendingPoolAddress)) {\n return LendingPoolStatus.Expired;\n }\n\n\n if (\n _adapter.isLendingPoolLateWithinGracePeriod(\n _lendingPoolAddress,\n Constants.LATE_PAYMENT_GRACE_PERIOD_IN_DAYS\n )\n ) {\n return LendingPoolStatus.LateWithinGracePeriod;\n }\n\n\n if (_adapter.isLendingPoolLate(_lendingPoolAddress)) {\n return LendingPoolStatus.Late;\n }\n\n\n return LendingPoolStatus.Active;\n }\n```\n | high |
```\nfunction commit(address from, address to, uint amount) external override onlyGenesisPeriod {\n burnFrom(from, amount);\n\n committedFGEN[to] = amount;\n totalCommittedFGEN += amount;\n\n emit Commit(from, to, amount);\n}\n```\n | high |
```\nfunction setCanTransferBefore(address wallet, bool enable) external onlyOwner {\n canTransferBeforeTradingIsEnabled[wallet] = enable;\n}\n```\n | none |
```\nfunction blacklistAccount (address account, bool isBlacklisted) public onlyOwner {\n _blacklist[account] = isBlacklisted;\n}\n```\n | none |
```\nfunction mod(uint256 a, uint256 b) internal pure returns (uint256) {\n return a % b;\n}\n```\n | none |
```\nFile: BondBaseSDA.sol\n function marketPrice(uint256 id_) public view override returns (uint256) {\n uint256 price = currentControlVariable(id_).mulDivUp(currentDebt(id_), markets[id_].scale);\n\n return (price > markets[id_].minPrice) ? price : markets[id_].minPrice;\n }\n```\n | medium |
```\n address creditor = underlyingPositionManager.ownerOf(loan.tokenId);\n // Increase liquidity and transfer liquidity owner reward\n _increaseLiquidity(cache.saleToken, cache.holdToken, loan, amount0, amount1);\n uint256 liquidityOwnerReward = FullMath.mulDiv(\n params.totalfeesOwed,\n cache.holdTokenDebt,\n params.totalBorrowedAmount\n ) / Constants.COLLATERAL_BALANCE_PRECISION;\n\n Vault(VAULT_ADDRESS).transferToken(cache.holdToken, creditor, liquidityOwnerReward);\n```\n | medium |
```\n(bool status, ) = payable(receiver).call{value: amount}("");\nrequire(status, "Gov: failed to send eth");\n```\n | low |
```\nfunction upgradeAgent(\n address agent\n) external returns (address newAgent) {\n IAgent oldAgent = IAgent(agent);\n address owner = IAuth(address(oldAgent)).owner();\n uint256 agentId = agents[agent];\n // only the Agent's owner can upgrade, and only a registered agent can be upgraded\n if (owner != msg.sender || agentId == 0) revert Unauthorized();\n // deploy a new instance of Agent with the same ID and auth\n newAgent = GetRoute.agentDeployer(router).deploy(\n router,\n agentId,\n owner,\n IAuth(address(oldAgent)).operator()\n );\n // Register the new agent and unregister the old agent\n agents[newAgent] = agentId;\n // transfer funds from old agent to new agent and mark old agent as decommissioning\n oldAgent.decommissionAgent(newAgent);\n // delete the old agent from the registry\n agents[agent] = 0;\n}\n```\n | medium |
```\nfunction approve(address spender, uint256 amount) public override returns (bool) {\n _approve(_msgSender(), spender, amount);\n return true;\n}\n```\n | none |
```\n function storePriceAndRewards(uint256 _totalUnderlying, uint256 _protocolId) internal {\n uint256 currentPrice = price(_protocolId);\n if (lastPrices[_protocolId] == 0) {\n lastPrices[_protocolId] = currentPrice;\n return;\n }\n\n\n int256 priceDiff = int256(currentPrice - lastPrices[_protocolId]);\n int256 nominator = (int256(_totalUnderlying * performanceFee) * priceDiff);\n int256 totalAllocatedTokensRounded = totalAllocatedTokens / 1E18;\n int256 denominator = totalAllocatedTokensRounded * int256(lastPrices[_protocolId]) * 100; // * 100 cause perfFee is in percentages\n\n\n if (totalAllocatedTokensRounded == 0) {\n rewardPerLockedToken[rebalancingPeriod][_protocolId] = 0;\n } else {\n rewardPerLockedToken[rebalancingPeriod][_protocolId] = nominator / denominator;\n }\n\n\n lastPrices[_protocolId] = currentPrice;\n }\n```\n | medium |
```\nfunction ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a / b + (a % b == 0 ? 0 : 1);\n}\n```\n | none |
```\nfunction borrow(VerifiableCredential memory vc) external isOpen subjectIsAgentCaller(vc) {\n // 1e18 => 1 FIL, can't borrow less than 1 FIL\n if (vc.value < WAD) revert InvalidParams();\n // can't borrow more than the pool has\n if (totalBorrowableAssets() < vc.value) revert InsufficientLiquidity();\n Account memory account = \_getAccount(vc.subject);\n // fresh account, set start epoch and epochsPaid to beginning of current window\n if (account.principal == 0) {\n uint256 currentEpoch = block.number;\n account.startEpoch = currentEpoch;\n account.epochsPaid = currentEpoch;\n GetRoute.agentPolice(router).addPoolToList(vc.subject, id);\n }\n\n account.principal += vc.value;\n account.save(router, vc.subject, id);\n\n totalBorrowed += vc.value;\n\n emit Borrow(vc.subject, vc.value);\n\n // interact - here `msg.sender` must be the Agent bc of the `subjectIsAgentCaller` modifier\n asset.transfer(msg.sender, vc.value);\n}\n```\n | high |
```\nfunction setMinimumForDiamondHands (uint256 value) external onlyOwner {\n value = value * (10**18);\n require(value <= _totalSupply / 2000, "cannot be set to more than 0.05%");\n minimumForDiamondHands = value;\n}\n```\n | none |
Subsets and Splits