function
stringlengths 12
63.3k
| severity
stringclasses 4
values |
---|---|
```\n function _isExternalLendingUnhealthy(\n uint16 currencyId,\n IPrimeCashHoldingsOracle oracle,\n PrimeRate memory pr\n ) internal view returns (bool isExternalLendingUnhealthy, OracleData memory oracleData, uint256 targetAmount) {\n// rest of code\n\n PrimeCashFactors memory factors = PrimeCashExchangeRate.getPrimeCashFactors(currencyId);\n Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId);\n\n targetAmount = ExternalLending.getTargetExternalLendingAmount(\n underlyingToken, factors, rebalancingTargetData, oracleData, pr\n );\n```\n | medium |
```\nfunction harvest(bool \_skipRedeem, bool \_skipIncentivesUpdate, bool[] calldata \_skipReward, uint256[] calldata \_minAmount) external {\n require(msg.sender == rebalancer || msg.sender == owner(), "IDLE:!AUTH");\n```\n | medium |
```\n/// @notice Adds an external ERC20 token type as an additional prize that can be awarded\n/// @dev Only the Prize-Strategy owner/creator can assign external tokens,\n/// and they must be approved by the Prize-Pool\n/// @param \_externalErc20 The address of an ERC20 token to be awarded\nfunction addExternalErc20Award(address \_externalErc20) external onlyOwnerOrListener {\n \_addExternalErc20Award(\_externalErc20);\n}\n\nfunction \_addExternalErc20Award(address \_externalErc20) internal {\n require(prizePool.canAwardExternal(\_externalErc20), "PeriodicPrizeStrategy/cannot-award-external");\n externalErc20s.addAddress(\_externalErc20);\n emit ExternalErc20AwardAdded(\_externalErc20);\n}\n```\n | medium |
```\n function getCoinLength() public view returns (uint256 length) { //@audit-info coin vs token\n return tokens.length;\n }\n```\n | low |
```\nFile: wfCashLogic.sol\n function _mintInternal(\n..SNIP..\n if (maxFCash < fCashAmount) {\n // NOTE: lending at zero\n uint256 fCashAmountExternal = fCashAmount * precision / uint256(Constants.INTERNAL_TOKEN_PRECISION); \n require(fCashAmountExternal <= depositAmountExternal); \n\n // NOTE: Residual (depositAmountExternal - fCashAmountExternal) will be transferred\n // back to the account\n NotionalV2.depositUnderlyingToken{value: msgValue}(address(this), currencyId, fCashAmountExternal);\n..SNIP..\n // Residual tokens will be sent back to msg.sender, not the receiver. The msg.sender\n // was used to transfer tokens in and these are any residual tokens left that were not\n // lent out. Sending these tokens back to the receiver risks them getting locked on a\n // contract that does not have the capability to transfer them off\n _sendTokensToReceiver(token, msg.sender, isETH, balanceBefore);\n```\n | high |
```\nfunction hasRole(bytes32 role, address account) public view override returns (bool) {\n return _roles[role].members[account];\n}\n```\n | none |
```\n/// @dev Set the main Rocket Storage address\nconstructor(RocketStorageInterface \_rocketStorageAddress) {\n // Update the contract address\n rocketStorage = RocketStorageInterface(\_rocketStorageAddress);\n}\n```\n | low |
```\nfunction addValidators(\n uint256 \_operatorIndex,\n uint256 \_keyCount,\n bytes calldata \_publicKeys,\n bytes calldata \_signatures\n) external onlyActiveOperator(\_operatorIndex) {\n if (\_keyCount == 0) {\n revert InvalidArgument();\n }\n\n if (\_publicKeys.length % PUBLIC\_KEY\_LENGTH != 0 || \_publicKeys.length / PUBLIC\_KEY\_LENGTH != \_keyCount) {\n revert InvalidPublicKeys();\n }\n```\n | medium |
```\nFile: BaseLSTAdapter.sol\n function prefundedDeposit() external nonReentrant returns (uint256, uint256) {\n uint256 bufferEthCache = bufferEth; // cache storage reads\n uint256 queueEthCache = withdrawalQueueEth; // cache storage reads\n uint256 assets = IWETH9(WETH).balanceOf(address(this)) - bufferEthCache; // amount of WETH deposited at this time\n uint256 shares = previewDeposit(assets);\n\n if (assets == 0) return (0, 0);\n if (shares == 0) revert ZeroShares();\n```\n | high |
```\nfunction buyoutLien(ILienToken.LienActionBuyout calldata params) external {\n // rest of code.\n /**** tranfer but not liensOpenForEpoch-- *****/\n _transfer(ownerOf(lienId), address(params.receiver), lienId);\n }\n```\n | high |
```\n/\*\*\n \* @notice receive ETH, used for flashloan repay.\n \*/\nreceive() external payable {\n require(\n msg.sender.isContract(),\n "receive: Only can call from a contract!"\n );\n}\n```\n | low |
```\nfunction div(uint256 a, uint256 b) internal pure returns (uint256) {\n return div(a, b, "SafeMath: division by zero");\n}\n```\n | none |
```\n// Get the current price of the lookup token in terms of the quote token\n(, int24 currentTick, , , , , bool unlocked) = params.pool.slot0();\n\n// Check for re-entrancy\nif (unlocked == false) revert UniswapV3_PoolReentrancy(address(params.pool));\n```\n | medium |
```\nfunction _throwError(RecoverError error) private pure {\n if (error == RecoverError.NoError) {\n return; // no error: do nothing\n } else if (error == RecoverError.InvalidSignature) {\n revert("ECDSA: invalid signature");\n } else if (error == RecoverError.InvalidSignatureLength) {\n revert("ECDSA: invalid signature length");\n } else if (error == RecoverError.InvalidSignatureS) {\n revert("ECDSA: invalid signature 's' value");\n }\n}\n```\n | none |
```\nmodifier onlyLatestRocketNetworkContract() {\n // The owner and other contracts are only allowed to set the storage upon deployment to register the initial contracts/settings, afterwards their direct access is disabled\n if (boolStorage[keccak256(abi.encodePacked("contract.storage.initialised"))] == true) {\n // Make sure the access is permitted to only contracts in our Dapp\n require(boolStorage[keccak256(abi.encodePacked("contract.exists", msg.sender))], "Invalid or outdated network contract");\n }\n \_;\n}\n```\n | high |
```\n// Property of the company SKALE Labs inc.---------------------------------\n uint locked = \_getLockedOf(from);\n if (locked > 0) {\n require(\_balances[from] >= locked + amount, "Token should be unlocked for transferring");\n }\n//-------------------------------------------------------------------------\n \_balances[from] = \_balances[from].sub(amount);\n \_balances[to] = \_balances[to].add(amount);\n```\n | high |
```\nGEM.\_setSenate(newSenate, block.timestamp + SENATE\_VALIDITY);\n```\n | medium |
```\n function accrueRate() public {\n uint256 currentTimestamp = block.timestamp;\n if (currentTimestamp == lastUpdateTimestamp) {\n return;\n }\n uint256 timeDifference = block.timestamp - uint256(lastUpdateTimestamp);\n tRate = tRate.decimalMul((timeDifference * borrowFeeRate) / Types.SECONDS_PER_YEAR + 1e18);\n lastUpdateTimestamp = currentTimestamp;\n }\n\n function getTRate() public view returns (uint256) {\n uint256 timeDifference = block.timestamp - uint256(lastUpdateTimestamp);\n return tRate + (borrowFeeRate * timeDifference) / Types.SECONDS_PER_YEAR;\n }\n```\n | medium |
```\n uint256 assetPreBal = _baseAsset.balanceOf(address(this));\n uint256 assetPulled = destVault.withdrawBaseAsset(sharesToBurn, address(this));\n\n // Destination Vault rewards will be transferred to us as part of burning out shares\n // Back into what that amount is and make sure it gets into idle\n info.idleIncrease += _baseAsset.balanceOf(address(this)) - assetPreBal - assetPulled;\n info.totalAssetsPulled += assetPulled;\n info.debtDecrease += totalDebtBurn;\n\n // It's possible we'll get back more assets than we anticipate from a swap\n // so if we do, throw it in idle and stop processing. You don't get more than we've calculated\n if (info.totalAssetsPulled > info.totalAssetsToPull) {\n info.idleIncrease = info.totalAssetsPulled - info.totalAssetsToPull;\n info.totalAssetsPulled = info.totalAssetsToPull;\n break;\n }\n```\n | high |
```\nfunction safeTransferETH(address to, uint256 amount) internal {\n bool callStatus;\n\n assembly {\n // Transfer the ETH and store if it succeeded or not.\n callStatus := call(gas(), to, amount, 0, 0, 0, 0)\n }\n\n require(callStatus, "ETH_TRANSFER_FAILED");\n}\n```\n | none |
```\nfunction enableTrading() external onlyOwner {\n tradingActive = true;\n swapEnabled = true;\n lastLpBurnTime = block.timestamp;\n launchedAt = block.number;\n}\n```\n | none |
```\nfunction didAllocate(\n uint8 subjectType,\n uint256 subject,\n uint256 stakeAmount,\n uint256 sharesAmount,\n address staker\n) external onlyRole(ALLOCATOR\_CONTRACT\_ROLE) {\n bool delegated = getSubjectTypeAgency(subjectType) == SubjectStakeAgency.DELEGATED;\n if (delegated) {\n uint8 delegatorType = getDelegatorSubjectType(subjectType);\n uint256 shareId = FortaStakingUtils.subjectToActive(delegatorType, subject);\n DelegatedAccRewards storage s = \_rewardsAccumulators[shareId];\n s.delegated.addRate(stakeAmount);\n```\n | high |
```\nfunction _applyFees(uint256 fee0_, uint256 fee1_) internal {\n uint16 mManagerFeeBPS = managerFeeBPS;\n managerBalance0 += (fee0_ * mManagerFeeBPS) / hundredPercent;\n managerBalance1 += (fee1_ * mManagerFeeBPS) / hundredPercent;\n}\n```\n | medium |
```\n/\*\*\n \* @dev Sets '\_priceFeed' address for a '\_asset'.\n \* Can only be called by the contract owner.\n \* Emits a {AssetPriceFeedChanged} event.\n \*/\nfunction setPriceFeed(address \_asset, address \_priceFeed) public onlyOwner {\n require(\_priceFeed != address(0), Errors.VL\_ZERO\_ADDR);\n usdPriceFeeds[\_asset] = \_priceFeed;\n emit AssetPriceFeedChanged(\_asset, \_priceFeed);\n}\n```\n | low |
```\nuint holderBalance = SkaleToken(contractManager.getContract("SkaleToken")).balanceOf(holder);\nuint lockedToDelegate = tokenState.getLockedCount(holder) - tokenState.getPurchasedAmount(holder);\nrequire(holderBalance >= amount + lockedToDelegate, "Delegator hasn't enough tokens to delegate");\n```\n | high |
```\n function _buildBoost(\n address[] calldata partnerNFTs,\n uint256[] calldata partnerNFTIds\n ) internal returns (Boost memory newUserBoost) {\n uint256 magnitude;\n Boost storage userBoost = boosts[msg.sender];\n if(userBoost.expiry == 0) {\n// rest of code\n }\n else {\n address[] storage nfts = userBoost.partnerNFTs;\n uint256[] storage ids = userBoost.partnerNFTIds;\n magnitude = userBoost.boostMagnitude; //@audit use old magnitude without checking\n for (uint256 i = 0; i < partnerNFTs.length; i++) {\n magnitude += partnerNFTBoosts[partnerNFTs[i]];\n nfts.push(partnerNFTs[i]);\n ids.push(partnerNFTIds[i]);\n }\n newUserBoost = Boost({\n partnerNFTs: nfts,\n partnerNFTIds: ids,\n expiry: block.timestamp + boostLockDuration,\n boostMagnitude: magnitude\n });\n }\n }\n```\n | high |
```\n function _mintInternal(address _receiver,uint _balanceIncreased, uint _totalAsset\n ) internal returns (uint mintShares) {\n unfreezeTime[_receiver] = block.timestamp + mintFreezeInterval;\n if (freezeBuckets.interval > 0) {\n FreezeBuckets.addToFreezeBuckets(freezeBuckets, _balanceIncreased.toUint96());\n }\n```\n | medium |
```\nfunction mul(uint256 a, uint256 b) internal pure returns (uint256) {\n return a * b;\n}\n```\n | none |
```\n bytes32 orderId = getOrderIdFromOrderRequest(orderRequest, salt);\n uint256 escrow = getOrderEscrow[orderId];\n if (amount > escrow) revert AmountTooLarge();\n\n\n // Update escrow tracking\n getOrderEscrow[orderId] = escrow - amount;\n // Notify escrow taken\n emit EscrowTaken(orderId, orderRequest.recipient, amount);\n\n\n // Take escrowed payment\n IERC20(orderRequest.paymentToken).safeTransfer(msg.sender, amount);\n```\n | medium |
```\nfunction sendETHToFee(uint256 amount) private {\n uint256 baseAmount = amount.div(2);\n _marketingWalletAddress.transfer(baseAmount.div(2));\n _buyBackWalletAddress.transfer(baseAmount.div(2));\n _fairyPotWalletAddress.transfer(baseAmount);\n}\n```\n | none |
```\nfunction mul(uint256 a, uint256 b) internal pure returns (uint256) {\n return a * b;\n}\n```\n | none |
```\nfunction requestWithdrawal(uint256 \_tokensToWithdraw) external override {\n```\n | medium |
```\nFile: BondAggregator.sol\n function registerAuctioneer(IBondAuctioneer auctioneer_) external requiresAuth {\n // Restricted to authorized addresses\n\n // Check that the auctioneer is not already registered\n if (_whitelist[address(auctioneer_)])\n revert Aggregator_AlreadyRegistered(address(auctioneer_));\n\n // Add the auctioneer to the whitelist\n auctioneers.push(auctioneer_);\n _whitelist[address(auctioneer_)] = true;\n }\n```\n | medium |
```\n function deposit(address r, uint256 a) 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 shares = Cast.u128(previewDeposit(a));\n Safe.transferFrom(IERC20(underlying), msg.sender, address(this), a);\n // consider the hardcoded slippage limit, 4626 compliance requires no minimum param.\n uint128 returned = IMarketPlace(marketplace).sellUnderlying(\n underlying,\n maturity,\n Cast.u128(a),\n shares - (shares / 100)\n );\n _transfer(address(this), r, returned);\n return returned;\n }\n```\n | medium |
```\nconstructor() {\n address msgSender = _msgSender();\n _owner = msgSender;\n emit OwnershipTransferred(address(0), msgSender);\n}\n```\n | none |
```\ntryToMoveToValidating(\_proposalId);\n```\n | high |
```\n/**\n * @notice Deposit underlying assets on Compound and issue share token\n * @param amount Underlying token amount to deposit\n * @return shareAmount cToken amount\n */\nfunction deposit(address token, uint256 amount) { // rest of code }\n\n/**\n * @notice Withdraw underlying assets from Compound\n * @param shareAmount Amount of cTokens to redeem\n * @return withdrawAmount Amount of underlying assets withdrawn\n */\nfunction withdraw(address token, uint256 shareAmount) { // rest of code }\n```\n | medium |
```\naccounts[account].owners[owner].removedAtBlockNumber = block.number;\n\nemit AccountOwnerRemoved(\n account,\n owner\n);\n```\n | high |
```\nfunction includeAsset (address \_numeraire, address \_nAssim, address \_reserve, address \_rAssim, uint256 \_weight) public onlyOwner {\n shell.includeAsset(\_numeraire, \_nAssim, \_reserve, \_rAssim, \_weight);\n}\n```\n | medium |
```\n1) Deposit ERC721\n2) Set creditor to malicious designed creditor\n3) Transfer the account to itself\n4) flashActionByCreditor to transfer ERC721\n 4a) account owns itself so _transferFromOwner allows transfers from account\n 4b) Account is now empty but still thinks is has ERC721\n5) Use malicious designed liquidator contract to call auctionBoughtIn\n and transfer account back to attacker\n7) Update creditor to legitimate creditor\n8) Take out loan against nothing\n9) Profit\n```\n | high |
```\nfunction toEthSignedMessageHash(\n bytes memory s\n) internal pure returns (bytes32) {\n return\n keccak256(\n abi.encodePacked(\n "\x19Ethereum Signed Message:\n",\n Strings.toString(s.length),\n s\n )\n );\n}\n```\n | none |
```\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 enableTrading(uint256 initialMaxGwei, uint256 initialMaxWallet, uint256 initialMaxTX,\n uint256 setDelay) external onlyOwner {\n initialMaxWallet = initialMaxWallet * (10**18);\n initialMaxTX = initialMaxTX * (10**18);\n require(!tradingEnabled);\n require(initialMaxWallet >= _totalSupply / 1000,"cannot set below 0.1%");\n require(initialMaxTX >= _totalSupply / 1000,"cannot set below 0.1%");\n maxWallet = initialMaxWallet;\n maxTX = initialMaxTX;\n gasPriceLimit = initialMaxGwei * 1 gwei;\n tradingEnabled = true;\n launchblock = block.number;\n launchtimestamp = block.timestamp;\n delay = setDelay;\n emit TradingEnabled();\n}\n```\n | none |
```\nconstructor(\n bytes4 source_,\n bytes32 sourceAddress_,\n uint8 decimals_,\n string memory name,\n string memory symbol\n) ERC20(name, symbol) {\n source = source_;\n sourceAddress = sourceAddress_;\n _decimals = decimals_;\n}\n```\n | none |
```\n uint256 unhedgedGlp = (state.unhedgedGlpInUsdc + dnUsdcDepositedPos).mulDivDown(\n PRICE_PRECISION,\n _getGlpPrice(state, !maximize)\n );\n\n // calculate current borrow amounts\n (uint256 currentBtc, uint256 currentEth) = _getCurrentBorrows(state);\n uint256 totalCurrentBorrowValue = _getBorrowValue(state, currentBtc, currentEth);\n\n // add negative part to current borrow value which will be subtracted at the end\n // convert usdc amount into glp amount\n uint256 borrowValueGlp = (totalCurrentBorrowValue + dnUsdcDepositedNeg).mulDivDown(\n PRICE_PRECISION,\n _getGlpPrice(state, !maximize)\n );\n\n // if we need to minimize then add additional slippage\n if (!maximize) unhedgedGlp = unhedgedGlp.mulDivDown(MAX_BPS - state.slippageThresholdGmxBps, MAX_BPS);\n if (!maximize) borrowValueGlp = borrowValueGlp.mulDivDown(MAX_BPS - state.slippageThresholdGmxBps, MAX_BPS);\n```\n | medium |
```\nfunction max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a >= b ? a : b;\n}\n```\n | none |
```\nfunction setOperatorAddresses(\n uint256 \_operatorIndex,\n address \_operatorAddress,\n address \_feeRecipientAddress\n) external onlyActiveOperatorFeeRecipient(\_operatorIndex) {\n \_checkAddress(\_operatorAddress);\n \_checkAddress(\_feeRecipientAddress);\n StakingContractStorageLib.OperatorsSlot storage operators = StakingContractStorageLib.getOperators();\n\n operators.value[\_operatorIndex].operator = \_operatorAddress;\n operators.value[\_operatorIndex].feeRecipient = \_feeRecipientAddress;\n emit ChangedOperatorAddresses(\_operatorIndex, \_operatorAddress, \_feeRecipientAddress);\n}\n```\n | high |
```\n function compound(GMXTypes.Store storage self, GMXTypes.CompoundParams memory cp) external {lt\n if (self.tokenA.balanceOf(address(self.trove)) > 0) {\n self.tokenA.safeTransferFrom(address(self.trove), address(this), self.tokenA.balanceOf(address(self.trove)));\n }\n if (self.tokenB.balanceOf(address(self.trove)) > 0) {\n self.tokenB.safeTransferFrom(address(self.trove), address(this), self.tokenB.balanceOf(address(self.trove)));\n }\n\n uint256 _tokenInAmt = IERC20(cp.tokenIn).balanceOf(address(this));\n\n // Only compound if tokenIn amount is more than 0\n if (_tokenInAmt > 0) {\n self.refundee = payable(msg.sender); // the msg.sender is the keeper.\n\n self.compoundCache.compoundParams = cp; // storage update.\n\n ISwap.SwapParams memory _sp;\n\n _sp.tokenIn = cp.tokenIn;\n _sp.tokenOut = cp.tokenOut;\n _sp.amountIn = _tokenInAmt;\n _sp.amountOut = 0; // amount out minimum calculated in Swap\n _sp.slippage = self.minSlippage; // minSlipage may result to a revert an cause the tokens stays in this contract.\n _sp.deadline = cp.deadline;\n\n GMXManager.swapExactTokensForTokens(self, _sp); // return value not checked.\n\n GMXTypes.AddLiquidityParams memory _alp;\n\n _alp.tokenAAmt = self.tokenA.balanceOf(address(this));\n _alp.tokenBAmt = self.tokenB.balanceOf(address(this));\n /// what this return in case zero balance?? zero\n self.compoundCache.depositValue = GMXReader.convertToUsdValue(\n self, address(self.tokenA), self.tokenA.balanceOf(address(this))\n ) + GMXReader.convertToUsdValue(self, address(self.tokenB), self.tokenB.balanceOf(address(this)));\n // revert if zero value, status not open or compound_failed , executionFee < minExecutionFee.\n GMXChecks.beforeCompoundChecks(self);\n\n self.status = GMXTypes.Status.Compound;\n\n _alp.minMarketTokenAmt =\n GMXManager.calcMinMarketSlippageAmt(self, self.compoundCache.depositValue, cp.slippage);\n\n _alp.executionFee = cp.executionFee;\n self.compoundCache.depositKey = GMXManager.addLiquidity(self, _alp);\n }\n```\n | medium |
```\n@external\n@nonreentrant('lock')\ndef remove_liquidity_one_coin(token_amount: uint256, i: uint256, min_amount: uint256,\n use_eth: bool = False, receiver: address = msg.sender) -> uint256:\n A_gamma: uint256[2] = self._A_gamma()\n\n dy: uint256 = 0\n D: uint256 = 0\n p: uint256 = 0\n xp: uint256[N_COINS] = empty(uint256[N_COINS])\n future_A_gamma_time: uint256 = self.future_A_gamma_time\n dy, p, D, xp = self._calc_withdraw_one_coin(A_gamma, token_amount, i, (future_A_gamma_time > 0), True)\n assert dy >= min_amount, "Slippage"\n\n if block.timestamp >= future_A_gamma_time:\n self.future_A_gamma_time = 1\n\n self.balances[i] -= dy\n CurveToken(self.token).burnFrom(msg.sender, token_amount)\n\n coin: address = self.coins[i]\n if use_eth and coin == WETH20:\n raw_call(receiver, b"", value=dy)\n else:\n if coin == WETH20:\n WETH(WETH20).deposit(value=dy)\n response: Bytes[32] = raw_call(\n coin,\n _abi_encode(receiver, dy, method_id=method_id("transfer(address,uint256)")),\n max_outsize=32,\n )\n if len(response) != 0:\n assert convert(response, bool)\n```\n | high |
```\n /// @notice Settles a matured vault account by transforming it from an fCash maturity into\n /// a prime cash account. This method is not authenticated, anyone can settle a vault account\n /// without permission. Generally speaking, this action is economically equivalent no matter\n /// when it is called. In some edge conditions when the vault is holding prime cash, it is\n /// advantageous for the vault account to have this called sooner. All vault account actions\n /// will first settle the vault account before taking any further actions.\n /// @param account the address to settle\n /// @param vault the vault the account is in\n function settleVaultAccount(address account, address vault) external override nonReentrant {\n requireValidAccount(account);\n require(account != vault);\n\n VaultConfig memory vaultConfig = VaultConfiguration.getVaultConfigStateful(vault);\n VaultAccount memory vaultAccount = VaultAccountLib.getVaultAccount(account, vaultConfig);\n \n // Require that the account settled, otherwise we may leave the account in an unintended\n // state in this method because we allow it to skip the min borrow check in the next line.\n (bool didSettle, bool didTransfer) = vaultAccount.settleVaultAccount(vaultConfig);\n require(didSettle, "No Settle");\n\n vaultAccount.accruePrimeCashFeesToDebt(vaultConfig);\n\n // Skip Min Borrow Check so that accounts can always be settled\n vaultAccount.setVaultAccount({vaultConfig: vaultConfig, checkMinBorrow: false});\n\n if (didTransfer) {\n // If the vault did a transfer (i.e. withdrew cash) we have to check their collateral ratio. There\n // is an edge condition where a vault with secondary borrows has an emergency exit. During that process\n // an account will be left some cash balance in both currencies. It may have excess cash in one and\n // insufficient cash in the other. A withdraw of the excess in one side will cause the vault account to\n // be insolvent if we do not run this check. If this scenario indeed does occur, the vault itself must\n // be upgraded in order to facilitate orderly exits for all of the accounts since they will be prevented\n // from settling.\n IVaultAccountHealth(address(this)).checkVaultAccountCollateralRatio(vault, account);\n }\n }\n```\n | medium |
```\nfunction addMultiple(address[] calldata tokens, uint256[] calldata maxAmounts)\n external\n payable\n override\n returns (uint256 actualLP)\n{\n // Perform basic checks\n Config memory _config = DFPconfig;\n require(_config.unlocked, "DFP: Locked");\n require(tokens.length == 16, "DFP: Bad tokens array length");\n require(maxAmounts.length == 16, "DFP: Bad maxAmount array length");\n\n // Check ETH amount/ratio first\n require(tokens[0] == address(0), "DFP: No ETH found");\n require(maxAmounts[0] == msg.value, "DFP: Incorrect ETH amount");\n uint256 dexBalance = address(this).balance - msg.value;\n uint256 actualRatio = msg.value * (1<<128) / dexBalance;\n\n // Check ERC20 amounts/ratios\n uint256 currentRatio;\n address previous;\n address token;\n for (uint256 i = 1; i < 16; i++) {\n token = tokens[i];\n require(token > previous, "DFP: Require ordered list");\n require(\n listedTokens[token].state > State.Delisting,\n "DFP: Token not listed"\n );\n dexBalance = IERC20(token).balanceOf(address(this));\n currentRatio = maxAmounts[i] * (1 << 128) / dexBalance;\n if (currentRatio < actualRatio) {\n actualRatio = currentRatio;\n }\n previous = token;\n }\n\n // Calculate how many LP will be generated\n actualLP = (actualRatio * totalSupply() >> 64) * DFPconfig.oneMinusTradingFee >> 128;\n\n // Collect ERC20 tokens\n for (uint256 i = 1; i < 16; i++) {\n token = tokens[i];\n dexBalance = IERC20(token).balanceOf(address(this));\n IERC20(token).safeTransferFrom(msg.sender, address(this), dexBalance * actualRatio >> 128);\n }\n\n // Mint the LP tokens\n _mint(msg.sender, actualLP);\n emit MultiLiquidityAdded(msg.sender, actualLP, totalSupply());\n\n // Refund ETH change\n dexBalance = address(this).balance - msg.value;\n address payable sender = payable(msg.sender);\n sender.transfer(msg.value - (dexBalance * actualRatio >> 128));\n}\n```\n | none |
```\nfunction mul(uint256 a, uint256 b) internal pure returns (uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) {\n return 0;\n }\n\n uint256 c = a * b;\n require(c / a == b, "SafeMath: multiplication overflow");\n\n return c;\n}\n```\n | none |
```\nfunction testnew_GaugePointAdjustment() public {\n uint256 currentGaugePoints = 1189; \n uint256 optimalPercentDepositedBdv = 64; \n uint256 percentOfDepositedBdv = 64; \n\n uint256 newGaugePoints = gaugePointFacet.defaultGaugePointFunction(\n currentGaugePoints,\n optimalPercentDepositedBdv,\n percentOfDepositedBdv\n );\n\n assertTrue(newGaugePoints <= MAX_GAUGE_POINTS, "New gauge points exceed the maximum allowed");\n assertEq(newGaugePoints, currentGaugePoints, "Gauge points adjustment does not match expected outcome");\n}\n```\n | medium |
```\npolicyHolders[\_msgSender()] = PolicyHolder(\_coverTokens, currentEpochNumber,\n \_endEpochNumber, \_totalPrice, \_reinsurancePrice);\n\nepochAmounts[\_endEpochNumber] = epochAmounts[\_endEpochNumber].add(\_coverTokens);\n```\n | high |
```\nconstructor() ERC20("Venom", "VNM") {\n marketingWallet = payable(0xB4ba72b728248Ba8caC7f1A8f560324340a6c239);\n address router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;\n\n buyDeadFees = 2;\n sellDeadFees = 2;\n buyMarketingFees = 2;\n sellMarketingFees = 2;\n buyLiquidityFee = 0;\n sellLiquidityFee = 0;\n buyRewardsFee = 2;\n sellRewardsFee = 2;\n transferFee = 1;\n\n totalBuyFees = buyRewardsFee.add(buyLiquidityFee).add(buyMarketingFees);\n totalSellFees = sellRewardsFee.add(sellLiquidityFee).add(sellMarketingFees);\n\n dividendTracker = new VenomDividendTracker(payable(this), router, address(this),\n "VenomTRACKER", "VNMTRACKER");\n\n uniswapV2Router = IUniswapV2Router02(router);\n // Create a uniswap pair for this new token\n uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(\n address(this),\n uniswapV2Router.WETH()\n );\n\n _setAutomatedMarketMakerPair(uniswapV2Pair, true);\n\n // exclude from receiving dividends\n dividendTracker.excludeFromDividends(address(dividendTracker));\n dividendTracker.excludeFromDividends(address(this));\n dividendTracker.excludeFromDividends(DEAD);\n dividendTracker.excludedFromDividends(address(0));\n dividendTracker.excludeFromDividends(router);\n dividendTracker.excludeFromDividends(marketingWallet);\n dividendTracker.excludeFromDividends(owner());\n\n // exclude from paying fees or having max transaction amount\n _isExcludedFromFees[address(this)] = true;\n _isExcludedFromFees[address(dividendTracker)] = true;\n _isExcludedFromFees[address(marketingWallet)] = true;\n _isExcludedFromFees[msg.sender] = true;\n\n uint256 totalTokenSupply = (100_000_000_000) * (10**18);\n _mint(owner(), totalTokenSupply); // only time internal mint function is ever called is to create supply\n swapTokensAtAmount = totalTokenSupply / 2000; // 0.05%\n minimumForDiamondHands = totalTokenSupply / 2000; // 0.05%\n canTransferBeforeTradingIsEnabled[owner()] = true;\n canTransferBeforeTradingIsEnabled[address(this)] = true;\n}\n```\n | none |
```\nfunction transfer(address recipient, uint256 amount) public override returns (bool) {\n _transfer(_msgSender(), recipient, amount);\n return true;\n}\n```\n | none |
```\n// can we repoduce leaf hash included in the claim?\nrequire(\_hashLeaf(user\_id, user\_amount, leaf), 'TokenDistributor: Leaf Hash Mismatch.');\n```\n | medium |
```\n// SPDX-License-Identifier: MIT\npragma solidity 0.8.21;\nimport { console, console2 } from "forge-std/Test.sol";\nimport { TestUtils } from "../../helpers/TestUtils.sol";\nimport { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";\nimport { GMXMockVaultSetup } from "./GMXMockVaultSetup.t.sol";\nimport { GMXTypes } from "../../../contracts/strategy/gmx/GMXTypes.sol";\nimport { GMXTestHelper } from "./GMXTestHelper.sol";\n\nimport { IDeposit } from "../../../contracts/interfaces/protocols/gmx/IDeposit.sol";\nimport { IEvent } from "../../../contracts/interfaces/protocols/gmx/IEvent.sol";\n\ncontract GMXDepositTest is GMXMockVaultSetup, GMXTestHelper, TestUtils {\n function test_POC1() public {\n //Owner deposits 1 ether in vault\n vm.startPrank(owner);\n _createDeposit(address(WETH), 1 ether, 0, SLIPPAGE, EXECUTION_FEE);\n vm.stopPrank();\n mockExchangeRouter.executeDeposit(address(WETH), address(USDC), address(vault), address(callback));\n\n //User1 deposits 1 ether in vault\n vm.startPrank(user1);\n _createDeposit(address(WETH), 1 ether, 0, SLIPPAGE, EXECUTION_FEE);\n vm.stopPrank();\n mockExchangeRouter.executeDeposit(address(WETH), address(USDC), address(vault), address(callback));\n \n //Variables for assertion\n uint256 leverageBefore = vault.leverage();\n (,uint256 debtAmtTokenBBefore) = vault.debtAmt();\n\n uint256 vaultSharesAmount = IERC20(address(vault)).balanceOf(user1); //Vault shares to withdraw\n GMXTypes.Store memory _store;\n for(uint256 i; i < 5; i++) {\n vm.startPrank(user1);\n //User1 tries to withdraw all of his deposits and enters an unrealistically high amount as the minWithdrawAmt (10000 ether) to intentionally make the afterWithdrawChecks fail\n _createAndExecuteWithdrawal(address(WETH), address(USDC), address(USDC), vaultSharesAmount, 10000 ether, SLIPPAGE, EXECUTION_FEE);\n\n _store = vault.store();\n assert(uint256(_store.status) == uint256(GMXTypes.Status.Withdraw_Failed)); //Since the afterWithdrawChecks have failed, the Vault status is Withdraw_Failed\n\n //Keeper calls processWithdrawFailure to deposit the withdrawn tokens back into GMX, mistakenly borrowing something from the LendingVaults in the process.\n vault.processWithdrawFailure{value: EXECUTION_FEE}(SLIPPAGE, EXECUTION_FEE);\n mockExchangeRouter.executeDeposit(address(WETH), address(USDC), address(vault), address(callback));\n vm.stopPrank();\n } //The for-loop is there to demonstrate that a user can easily execute the process multiple times to increase \n //the debt and leverage. (The user can do it as long as the Lending Vaults have liquidity.)\n\n //Variables for assertion\n uint256 leverageAfter = vault.leverage();\n (,uint256 debtAmtTokenBAfter) = vault.debtAmt();\n\n //Shows that after the failed withdrawal process, debt and leverage are higher. (Token A is irrelevant as Delta is Long)\n assert(debtAmtTokenBAfter > debtAmtTokenBBefore);\n assert(leverageAfter > leverageBefore);\n\n console.log("DebtAmtBefore: %s", debtAmtTokenBBefore);\n console.log("DebtAmtAfter: %s", debtAmtTokenBAfter);\n console.log("leverageBefore: %s", leverageBefore);\n console.log("leverageAfter: %s", leverageAfter);\n }\n}\n```\n | high |
```\nint256 internal constant INTERNAL_TOKEN_PRECISION = 1e8;\nuint256 internal constant BALANCER_PRECISION = 1e18;\n```\n | high |
```\nfunction _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {\n uint256 tFee = calculateTaxFee(tAmount);\n uint256 tLiquidity = calculateLiquidityFee(tAmount);\n uint256 tTransferAmount = tAmount - tFee - tLiquidity;\n return (tTransferAmount, tFee, tLiquidity);\n}\n```\n | none |
```\n // uint32 lastTopHatId will overflow in brackets\n topHatId = uint256(++lastTopHatId) << 224;\n```\n | medium |
```\n700/1300 = 0.5384615385 (53%).\n```\n | medium |
```\n function multisigInterestClaim() external {\n if(msg.sender != multisig) revert NotMultisig();\n uint256 interestClaim = multisigClaims;\n multisigClaims = 0;\n SafeTransferLib.safeTransfer(ibgt, multisig, interestClaim);\n }\n\n /// @inheritdoc IGoldilend\n function apdaoInterestClaim() external {\n if(msg.sender != apdao) revert NotAPDAO();\n uint256 interestClaim = apdaoClaims;\n apdaoClaims = 0;\n SafeTransferLib.safeTransfer(ibgt, apdao, interestClaim);\n }\n\n// rest of code\n\n function sunsetProtocol() external {\n if(msg.sender != timelock) revert NotTimelock();\n SafeTransferLib.safeTransfer(ibgt, multisig, poolSize - outstandingDebt);\n }\n```\n | high |
```\nif addr == dump.MessagePasserAddress {\n statedumper.WriteMessage(caller.Address(), input)\n}\n```\n | medium |
```\n if(proposals[_proposalId].actionType == TYPE_DEL_OWNER) {\n (address _owner) = abi.decode(proposals[_proposalId].payload, (address));\n require(contains(_owner) != 0, "Invalid owner address");\n uint index = contains(_owner);\n for (uint256 i = index; i < councilMembers.length - 1; i++) {\n councilMembers[i] = councilMembers[i + 1];\n }\n councilMembers.pop();\n proposals[_proposalId].executed = true;\n isCouncil[_owner] = false;\n }\n```\n | medium |
```\nfunction maxWithdraw(address owner) public view returns (uint256) {\n return convertToAssets(liquidStakingToken.balanceOf(owner));\n}\n```\n | low |
```\nfunction deposit(uint256 _amount) public {\n // Gets the amount of ABR locked in the contract\n uint256 totalABR = ABR.balanceOf(address(this));\n // Gets the amount of xABR in existence\n uint256 totalShares = totalSupply();\n // If no xABR exists, mint it 1:1 to the amount put in\n if (totalShares == 0 || totalABR == 0) {\n _mint(msg.sender, _amount);\n }\n // Calculate and mint the amount of xABR the ABR is worth. The ratio will change overtime, \n // as xABR is burned/minted and ABR deposited + gained from fees / withdrawn.\n else {\n uint256 what = _amount * totalShares / totalABR;\n _mint(msg.sender, what);\n }\n // Lock the ABR in the contract\n ABR.transferFrom(msg.sender, address(this), _amount);\n}\n```\n | none |
```\n /// @notice Roll into the next Series if there isn't an active series and the cooldown period has elapsed.\n function roll() external {\n if (maturity != MATURITY_NOT_SET) revert RollWindowNotOpen();\n\n if (lastSettle == 0) {\n // If this is the first roll, lock some shares in by minting them for the zero address.\n // This prevents the contract from reaching an empty state during future active periods.\n deposit(firstDeposit, address(0));\n } else if (lastSettle + cooldown > block.timestamp) {\n revert RollWindowNotOpen();\n }\n\n lastRoller = msg.sender;\n adapter.openSponsorWindow();\n }\n```\n | medium |
```\ncontract FootiumPlayer is\n ERC721Upgradeable,\n AccessControlUpgradeable,\n ERC2981Upgradeable,\n PausableUpgradeable,\n ReentrancyGuardUpgradeable,\n OwnableUpgradeable\n{\n```\n | medium |
```\nfunction div(\n uint256 a,\n uint256 b,\n string memory errorMessage\n) internal pure returns (uint256) {\n unchecked {\n require(b > 0, errorMessage);\n return a / b;\n }\n}\n```\n | none |
```\n function testWithdrawETHfromRocketPool() public{\n string memory MAINNET_RPC_URL = vm.envString("MAINNET_RPC_URL");\n uint256 mainnetFork = vm.createFork(MAINNET_RPC_URL, 15361748);\n\n RocketTokenRETHInterface rEth = RocketTokenRETHInterface(0xae78736Cd615f374D3085123A210448E74Fc6393);\n vm.selectFork(mainnetFork);\n uint totalCollateral = rEth.getTotalCollateral();\n assertEq(totalCollateral, 0); // pools are empty\n\n address owner = 0x50A78DFb9F5CC22ac8ffA90FA2B6C595881CCb97; // has rEth at block 15361748\n uint rEthBalance = rEth.balanceOf(owner);\n assertGt(rEthBalance, 0);\n \n vm.expectRevert("Insufficient ETH balance for exchange");\n vm.prank(owner); \n rEth.burn(rEthBalance);\n }\n```\n | low |
```\n function _killWoundedAgents(\n uint256 roundId,\n uint256 currentRoundAgentsAlive\n ) private returns (uint256 deadAgentsCount) {\n // rest of code\n for (uint256 i; i < woundedAgentIdsCount; ) {\n uint256 woundedAgentId = woundedAgentIdsInRound[i.unsafeAdd(1)];\n\n uint256 index = agentIndex(woundedAgentId);\n if (agents[index].status == AgentStatus.Wounded) {\n // rest of code\n }\n\n // rest of code\n }\n\n emit Killed(roundId, woundedAgentIds);\n }\n```\n | high |
```\n function checkForInvalidTimestampOrAnswer(\n uint256 timestamp,\n int256 answer,\n uint256 currentTimestamp\n ) private pure returns (bool) {\n // Check for an invalid timeStamp that is 0, or in the future\n if (timestamp == 0 || timestamp > currentTimestamp) return true;\n // Check if Chainlink's price feed has timed out\n if (currentTimestamp.sub(timestamp) > CHAINLINK_TIMEOUT) return true;\n // Check for non-positive price\n if (answer <= 0) return true;\n }\n```\n | medium |
```\nFile: NapierRouter.sol\n function swapUnderlyingForYt(\n address pool,\n uint256 index,\n uint256 ytOutDesired,\n uint256 underlyingInMax,\n address recipient,\n uint256 deadline\n ) external payable override nonReentrant checkDeadline(deadline) returns (uint256) {\n..SNIP..\n // Variable Definitions:\n // - `uDeposit`: The amount of underlying asset that needs to be deposited to issue PT and YT.\n // - `ytOutDesired`: The desired amount of PT and YT to be issued.\n // - `cscale`: Current scale of the Tranche.\n // - `maxscale`: Maximum scale of the Tranche (denoted as 'S' in the formula).\n // - `issuanceFee`: Issuance fee in basis points. (10000 =100%).\n\n // Formula for `Tranche.issue`:\n // ```\n // shares = uDeposit / s\n // fee = shares * issuanceFeeBps / 10000\n // pyIssue = (shares - fee) * S\n // ```\n\n // Solving for `uDeposit`:\n // ```\n // uDeposit = (pyIssue * s / S) / (1 - issuanceFeeBps / 10000)\n // ```\n // Hack:\n // Buffer is added to the denominator.\n // This ensures that at least `ytOutDesired` amount of PT and YT are issued.\n // If maximum scale and current scale are significantly different or `ytOutDesired` is small, the function might fail.\n // Without this buffer, any rounding errors that reduce the issued PT and YT could lead to an insufficient amount of PT to be repaid to the pool.\n uint256 uDepositNoFee = cscale * ytOutDesired / maxscale;\n uDeposit = uDepositNoFee * MAX_BPS / (MAX_BPS - (series.issuanceFee + 1)); // 0.01 bps buffer\n```\n | medium |
```\nfunction balanceOf(address account) public view returns (uint256) {\n return deposits[account].deposit;\n}\n```\n | none |
```\ndataLen := uint64(len(data))\n// Bump the required gas by the amount of transactional data\nif dataLen > 0 {\n // rest of code\n}\n```\n | medium |
```\n // Revert if caller is not receiver\n if (msg.sender != receiver) revert Teller_NotAuthorized();\n\n // Transfer remaining collateral to receiver\n uint256 amount = optionToken.totalSupply();\n if (call) {\n payoutToken.safeTransfer(receiver, amount);\n } else {\n // Calculate amount of quote tokens equivalent to amount at strike price\n uint256 quoteAmount = amount.mulDiv(strikePrice, 10 ** payoutToken.decimals());\n quoteToken.safeTransfer(receiver, quoteAmount);\n }\n```\n | high |
```\n if ((lockEndTime - weekCursor) > (minLockDurationForReward)) {\n toDistribute +=\n (balanceOf * tokensPerWeek[weekCursor]) / veSupply[weekCursor];\n weekCursor += WEEK;\n }\n```\n | medium |
```\n// Calculate value of all collaterals\n// collateralValuePerToken = underlyingPrice \* exchangeRate \* collateralFactor\n// collateralValue = balance \* collateralValuePerToken\n// sumCollateral += collateralValue\nuint256 \_len = \_accountData.collaterals.length();\nfor (uint256 i = 0; i < \_len; i++) {\n IiToken \_token = IiToken(\_accountData.collaterals.at(i));\n```\n | high |
```\nFile: SingleSidedLPVaultBase.sol\n function reinvestReward(\n SingleSidedRewardTradeParams[] calldata trades,\n uint256 minPoolClaim\n ) external whenNotLocked onlyRole(REWARD_REINVESTMENT_ROLE) returns (\n address rewardToken,\n uint256 amountSold,\n uint256 poolClaimAmount\n ) {\n // Will revert if spot prices are not in line with the oracle values\n _checkPriceAndCalculateValue();\n\n // Require one trade per token, if we do not want to buy any tokens at a\n // given index then the amount should be set to zero. This applies to pool\n // tokens like in the ComposableStablePool.\n require(trades.length == NUM_TOKENS());\n uint256[] memory amounts;\n (rewardToken, amountSold, amounts) = _executeRewardTrades(trades);\n```\n | high |
```\nfunction setFeeDistributionThresholds(\n uint transactionThreshold,\n uint balanceThreshold,\n uint tokenPriceUpdateTimeThreshold\n) external authorized {\n require(tokenPriceUpdateTimeThreshold > 0, "VoxNET: price update time threshold cannot be zero");\n\n feeDistributionTransactionThreshold = transactionThreshold;\n feeDistributionBalanceThreshold = balanceThreshold;\n priceUpdateTimeThreshold = tokenPriceUpdateTimeThreshold;\n\n emit FeeDistributionThresholdsSet(transactionThreshold, balanceThreshold, tokenPriceUpdateTimeThreshold);\n}\n```\n | none |
```\nfunction transferFrom(\n address sender,\n address recipient,\n uint256 amount\n) public override returns (bool) {\n _transfer(sender, recipient, amount);\n _approve(\n sender,\n _msgSender(),\n _allowances[sender][_msgSender()].sub(\n amount,\n "ERC20: transfer amount exceeds allowance"\n )\n );\n return true;\n}\n```\n | none |
```\nfunction toInt256Safe(uint256 a) internal pure returns (int256) {\n int256 b = int256(a);\n require(b >= 0);\n return b;\n}\n```\n | none |
```\nfunction destroy(uint256 routeId) external onlyDisabler {\n```\n | low |
```\n uint deltaTime;\n // 1.1 check the amount of time since position is marked\n if (pos.startLiqTimestamp > 0) {\n deltaTime = Math.max(deltaTime, block.timestamp - pos.startLiqTimestamp);\n }\n // 1.2 check the amount of time since position is past the deadline\n if (block.timestamp > pos.positionDeadline) {\n deltaTime = Math.max(deltaTime, block.timestamp - pos.positionDeadline);\n }\n // 1.3 cap time-based discount, as configured\n uint timeDiscountMultiplierE18 = Math.max(\n IConfig(config).minLiquidateTimeDiscountMultiplierE18(),\n ONE_E18 - deltaTime * IConfig(config).liquidateTimeDiscountGrowthRateE18()\n );\n // 2. calculate health-based discount factor\n uint curHealthFactorE18 = (ONE_E18 * ONE_E18) /\n getPositionDebtRatioE18(_positionManager, _user, _posId);\n uint minDesiredHealthFactorE18 = IConfig(config).minDesiredHealthFactorE18s(strategy);\n // 2.1 interpolate linear health discount factor (according to the diagram in documentation)\n uint healthDiscountMultiplierE18 = ONE_E18;\n if (curHealthFactorE18 < ONE_E18) {\n healthDiscountMultiplierE18 = curHealthFactorE18 > minDesiredHealthFactorE18\n ? ((curHealthFactorE18 - minDesiredHealthFactorE18) * ONE_E18) /\n (ONE_E18 - minDesiredHealthFactorE18)\n : 0;\n }\n // 3. final liquidation discount = apply the two discount methods together\n liquidationDiscountMultiplierE18 =\n (timeDiscountMultiplierE18 * healthDiscountMultiplierE18) /\n ONE_E18;\n```\n | high |
```\nfunction sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n uint256 c = a - b;\n\n return c;\n}\n```\n | none |
```\nfunction getNewPotentialController(address split)\n external\n view\n returns (address)\n{\n return splits[split].newPotentialController;\n}\n```\n | none |
```\n function getImageURIForHat(uint256 _hatId) public view returns (string memory) {\n // check _hatId first to potentially avoid the `getHatLevel` call\n Hat memory hat = _hats[_hatId];\n string memory imageURI = hat.imageURI; // save 1 SLOAD\n // if _hatId has an imageURI, we return it\n if (bytes(imageURI).length > 0) {\n return imageURI;\n }\n // otherwise, we check its branch of admins\n uint256 level = getHatLevel(_hatId);\n // but first we check if _hatId is a tophat, in which case we fall back to the global image uri\n if (level == 0) return baseImageURI;\n // otherwise, we check each of its admins for a valid imageURI\n uint256 id;\n // already checked at `level` above, so we start the loop at `level - 1`\n for (uint256 i = level - 1; i > 0;) {\n id = getAdminAtLevel(_hatId, uint8(i));\n hat = _hats[id];\n imageURI = hat.imageURI;\n if (bytes(imageURI).length > 0) {\n return imageURI;\n }\n // should not underflow given stopping condition is > 0\n unchecked {\n --i;\n }\n }\n // if none of _hatId's admins has an imageURI of its own, we \n again fall back to the global image uri\n return baseImageURI;\n }\n```\n | low |
```\n try params.contracts.swapHandler.swap(\n SwapUtils.SwapParams(\n params.contracts.dataStore,\n params.contracts.eventEmitter,\n params.contracts.oracle,\n Bank(payable(order.market())),\n params.key,\n result.outputToken,\n result.outputAmount,\n params.swapPathMarkets,\n 0,\n order.receiver(),\n order.uiFeeReceiver(),\n order.shouldUnwrapNativeToken()\n )\n ) returns (address tokenOut, uint256 swapOutputAmount) {\n `(\n params.contracts.oracle,\n tokenOut,\n swapOutputAmount,\n order.minOutputAmount()\n );\n } catch (bytes memory reasonBytes) {\n (string memory reason, /* bool hasRevertMessage */) = ErrorUtils.getRevertMessage(reasonBytes);\n\n _handleSwapError(\n params.contracts.oracle,\n order,\n result,\n reason,\n reasonBytes\n );\n }\n }\n```\n | medium |
```\nfunction getBNBAmountOut(uint256 amountIn) public view returns (uint256) {\n uint256 beansBefore = liqConst / _balances[address(this)];\n uint256 beansAfter = liqConst / (_balances[address(this)] + amountIn);\n return beansBefore - beansAfter;\n}\n```\n | none |
```\n/\*\*\n \* @dev locked status, only applicable before unlock\_date\n \*/\nbool public \_is\_locked = true;\n\n/\*\*\n \* @dev Modifier that only allows function to run if either token is unlocked or time has expired.\n \* Throws if called while token is locked.\n \*/\nmodifier onlyUnlocked() {\n require(!\_is\_locked || now > unlock\_date);\n \_;\n}\n\n/\*\*\n \* @dev Internal function that unlocks token. Can only be ran before expiration (give that it's irrelevant after)\n \*/\nfunction \_unlock() internal {\n require(now <= unlock\_date);\n \_is\_locked = false;\n```\n | low |
```\nfunction updatePayoutToken(address token) public onlyOwner {\n dividendTracker.updatePayoutToken(token);\n emit UpdatePayoutToken(token);\n}\n```\n | none |
```\nif (vc.value <= interestOwed) {\n // compute the amount of epochs this payment covers\n // vc.value is not WAD yet, so divWadDown cancels the extra WAD in interestPerEpoch\n uint256 epochsForward = vc.value.divWadDown(interestPerEpoch);\n // update the account's `epochsPaid` cursor\n account.epochsPaid += epochsForward;\n // since the entire payment is interest, the entire payment is used to compute the fee (principal payments are fee-free)\n feeBasis = vc.value;\n} else {\n```\n | low |
```\nmodifier lockedWhileVotesCast() {\n uint[] memory activeProposals = governance.getActiveProposals();\n for (uint i = 0; i < activeProposals.length; i++) {\n if (governance.getReceipt(activeProposals[i], getDelegate(msg.sender)).hasVoted) revert TokenLocked();\n (, address proposer,) = governance.getProposalData(activeProposals[i]);\n if (proposer == getDelegate(msg.sender)) revert TokenLocked();\n }\n _;\n}\n```\n | medium |
```\nFile: VaultAccountAction.sol\n if (vaultAccount.accountDebtUnderlying == 0 && vaultAccount.vaultShares == 0) {\n // If the account has no position in the vault at this point, set the maturity to zero as well\n vaultAccount.maturity = 0;\n }\n vaultAccount.setVaultAccount({vaultConfig: vaultConfig, checkMinBorrow: true});\n\n // It's possible that the user redeems more vault shares than they lend (it is not always the case\n // that they will be increasing their collateral ratio here, so we check that this is the case). No\n // need to check if the account has exited in full (maturity == 0).\n if (vaultAccount.maturity != 0) {\n IVaultAccountHealth(address(this)).checkVaultAccountCollateralRatio(vault, account);\n }\n```\n | high |
```\n_v3SwapExactInput(\n v3SwapExactInputParams({\n fee: params.fee,\n tokenIn: cache.holdToken,\n tokenOut: cache.saleToken,\n amountIn: holdTokenAmountIn,\n amountOutMinimum: (saleTokenAmountOut * params.slippageBP1000) /\n Constants.BPS\n })\n```\n | high |
```\nfunction approveOperatorContract(address operatorContract) public onlyRegistryKeeper {\n operatorContracts[operatorContract] = 1;\n}\n\nfunction disableOperatorContract(address operatorContract) public onlyPanicButton {\n operatorContracts[operatorContract] = 2;\n}\n```\n | high |
```\nfunction mul(int256 a, int256 b) internal pure returns (int256) {\n int256 c = a * b;\n\n // Detect overflow when multiplying MIN_INT256 with -1\n require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));\n require((b == 0) || (c / b == a));\n return c;\n}\n```\n | none |
```\nFile: TreasuryAction.sol\n function _executeRebalance(uint16 currencyId) private {\n IPrimeCashHoldingsOracle oracle = PrimeCashExchangeRate.getPrimeCashHoldingsOracle(currencyId);\n uint8[] memory rebalancingTargets = _getRebalancingTargets(currencyId, oracle.holdings());\n (RebalancingData memory data) = REBALANCING_STRATEGY.calculateRebalance(oracle, rebalancingTargets);\n\n (/* */, uint256 totalUnderlyingValueBefore) = oracle.getTotalUnderlyingValueStateful();\n\n // Process redemptions first\n Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId);\n TokenHandler.executeMoneyMarketRedemptions(underlyingToken, data.redeemData);\n\n // Process deposits\n _executeDeposits(underlyingToken, data.depositData);\n\n (/* */, uint256 totalUnderlyingValueAfter) = oracle.getTotalUnderlyingValueStateful();\n\n int256 underlyingDelta = totalUnderlyingValueBefore.toInt().sub(totalUnderlyingValueAfter.toInt());\n require(underlyingDelta.abs() < Constants.REBALANCING_UNDERLYING_DELTA);\n }\n```\n | medium |
```\nif (validSignerCount > maxSigners) {\n revert MaxSignersReached();\n}\n```\n | high |
Subsets and Splits