function
stringlengths 12
63.3k
| severity
stringclasses 4
values |
---|---|
```\nfunction totalFees() public view returns (uint256) {\n return _tFeeTotal;\n}\n```\n | none |
```\n/// Controlled Value) than the circulating (user-owned) FEI, i.e.\n/// a positive Protocol Equity.\n/// Note: the validity status is ignored in this function.\nfunction isOvercollateralized() external override view whenNotPaused returns (bool) {\n (,, int256 \_protocolEquity, bool \_valid) = pcvStats();\n require(\_valid, "CollateralizationOracle: reading is invalid");\n return \_protocolEquity > 0;\n}\n```\n | low |
```\nfunction setEarlySellTax(bool onoff) external onlyOwner {\n enableEarlySellTax = onoff;\n}\n```\n | none |
```\nfunction setReinvest(address account, bool value) external onlyOwner {\n autoReinvest[account] = value;\n}\n```\n | none |
```\n\_poolById[poolId].numberOfMakers = uint256(\_poolById[poolId].numberOfMakers).safeSub(1).downcastToUint32();\n```\n | medium |
```\nfunction trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b > a) return (false, 0);\n return (true, a - b);\n }\n}\n```\n | none |
```\nFile: BondBaseSDA.sol\n // Set last decay timestamp based on size of purchase to linearize decay\n uint256 lastDecayIncrement = debtDecayInterval.mulDiv(payout_, lastTuneDebt);\n metadata[id_].lastDecay += uint48(lastDecayIncrement);\n```\n | medium |
```\nconstructor(string memory name) EIP712(name, "1") {}\n```\n | none |
```\nuint256 pausedDuration = 10 days;\n```\n | low |
```\nfunction _doSafeBatchTransferAcceptanceCheck(\n address operator,\n address from,\n address to,\n uint256[] memory ids,\n uint256[] memory amounts,\n bytes memory data\n) private {\n if (to.isContract()) {\n try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (\n bytes4 response\n ) {\n if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {\n revert("ERC1155: ERC1155Receiver rejected tokens");\n }\n } catch Error(string memory reason) {\n revert(reason);\n } catch {\n revert("ERC1155: transfer to non ERC1155Receiver implementer");\n }\n }\n}\n```\n | none |
```\nfunction excludeFromFee(address account) public onlyOwner {\n _isExcludedFromFee[account] = true;\n}\n```\n | none |
```\nfunction div(uint256 a, uint256 b) internal pure returns (uint256) {\n return div(a, b, "SafeMath: division by zero");\n}\n```\n | none |
```\n// Redirect net portion of minor's side to maker\nif (fromPosition.long.gt(fromPosition.short)) {\n fundingValues.fundingMaker = fundingValues.fundingShort.mul(Fixed6Lib.from(fromPosition.skew().abs()));\n fundingValues.fundingShort = fundingValues.fundingShort.sub(fundingValues.fundingMaker);\n}\nif (fromPosition.short.gt(fromPosition.long)) {\n fundingValues.fundingMaker = fundingValues.fundingLong.mul(Fixed6Lib.from(fromPosition.skew().abs()));\n fundingValues.fundingLong = fundingValues.fundingLong.sub(fundingValues.fundingMaker);\n}\n```\n | medium |
```\n uint locked = \_getAndUpdateLockedAmount(from);\n if (locked > 0) {\n require(\_balances[from] >= locked.add(amount), "Token should be unlocked for burning");\n }\n//-------------------------------------------------------------------------\n\n \_callTokensToSend(\n operator, from, address(0), amount, data, operatorData\n );\n\n // Update state variables\n \_totalSupply = \_totalSupply.sub(amount);\n \_balances[from] = \_balances[from].sub(amount);\n```\n | high |
```\nfunction \_swapLidoForWETH(uint256 amountToSwap) internal {\n IUniswapSwapRouter.ExactInputSingleParams\n memory params = IUniswapSwapRouter.ExactInputSingleParams({\n tokenIn: address(ldo),\n tokenOut: address(weth),\n fee: UNISWAP\_FEE,\n recipient: address(this),\n deadline: block.timestamp,\n amountIn: amountToSwap,\n amountOutMinimum: 0,\n sqrtPriceLimitX96: 0\n });\n uniswapRouter.exactInputSingle(params);\n}\n```\n | medium |
```\nfunction registerClaimer(address \_claimerAddress, bool \_enabled) override external onlyClaimContract {\n // The name of the claiming contract\n string memory contractName = getContractName(msg.sender);\n // Record the block they are registering at\n uint256 registeredBlock = 0;\n // How many users are to be included in next interval\n uint256 claimersIntervalTotalUpdate = getClaimingContractUserTotalNext(contractName);\n // Ok register\n if(\_enabled) {\n // Make sure they are not already registered\n require(getClaimingContractUserRegisteredBlock(contractName, \_claimerAddress) == 0, "Claimer is already registered");\n // Update block number\n registeredBlock = block.number;\n // Update the total registered claimers for next interval\n setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.next", contractName)), claimersIntervalTotalUpdate.add(1));\n }else{\n setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.next", contractName)), claimersIntervalTotalUpdate.sub(1));\n }\n // Save the registered block\n setUint(keccak256(abi.encodePacked("rewards.pool.claim.contract.registered.block", contractName, \_claimerAddress)), registeredBlock);\n}\n```\n | low |
```\nfunction acceptControl(address split)\n external\n override\n onlySplitNewPotentialController(split)\n{\n delete splits[split].newPotentialController;\n emit ControlTransfer(split, splits[split].controller, msg.sender);\n splits[split].controller = msg.sender;\n}\n```\n | none |
```\nfunction getPositionValue() public view returns (uint256) {\n uint256 markPrice = getMarkPriceTwap(15);\n int256 positionSize = IAccountBalance(clearingHouse.getAccountBalance())\n .getTakerPositionSize(address(this), market);\n return markPrice.mulWadUp(_abs(positionSize));\n}\n\nfunction getMarkPriceTwap(uint32 twapInterval)\n public\n view\n returns (uint256)\n{\n IExchange exchange = IExchange(clearingHouse.getExchange());\n uint256 markPrice = exchange\n .getSqrtMarkTwapX96(market, twapInterval)\n .formatSqrtPriceX96ToPriceX96()\n .formatX96ToX10_18();\n return markPrice;\n}\n```\n | high |
```\ndaiAToken balance = 30000\nwethDebtToken balance = 10\n\nThe price of WETH when the trade was opened was ~ 3000 DAI\n```\n | high |
```\nFile: ERC4626Oracle.sol\n function getPrice(address token) external view returns (uint) {\n uint decimals = IERC4626(token).decimals();\n return IERC4626(token).previewRedeem(\n 10 ** decimals\n ).mulDivDown(\n oracleFacade.getPrice(IERC4626(token).asset()),\n 10 ** decimals\n );\n }\n```\n | medium |
```\nfunction eject(\n uint256 shares,\n address receiver,\n address owner\n) public returns (uint256 assets, uint256 excessBal, bool isExcessPTs) {\n\n // rest of code\n\n //@audit call of interest\n (excessBal, isExcessPTs) = _exitAndCombine(shares);\n\n _burn(owner, shares); // Burn after percent ownership is determined in _exitAndCombine.\n\n if (isExcessPTs) {\n pt.transfer(receiver, excessBal);\n } else {\n yt.transfer(receiver, excessBal);\n }\n\n //@audit entire asset (adapter.target) balance transferred to caller, which includes collected YT yield and combined\n asset.transfer(receiver, assets = asset.balanceOf(address(this)));\n\n emit Ejected(msg.sender, receiver, owner, assets, shares,\n isExcessPTs ? excessBal : 0,\n isExcessPTs ? 0 : excessBal\n );\n}\n\nfunction _exitAndCombine(uint256 shares) internal returns (uint256, bool) {\n uint256 supply = totalSupply; // Save extra SLOAD.\n\n uint256 lpBal = shares.mulDivDown(space.balanceOf(address(this)), supply);\n uint256 totalPTBal = pt.balanceOf(address(this));\n uint256 ptShare = shares.mulDivDown(totalPTBal, supply);\n\n // rest of code\n\n uint256 ytBal = shares.mulDivDown(yt.balanceOf(address(this)), supply);\n ptShare += pt.balanceOf(address(this)) - totalPTBal;\n\n unchecked {\n // Safety: an inequality check is done before subtraction.\n if (ptShare > ytBal) {\n\n //@audit call of interest\n divider.combine(address(adapter), maturity, ytBal);\n return (ptShare - ytBal, true);\n } else { // Set excess PTs to false if the balances are exactly equal.\n divider.combine(address(adapter), maturity, ptShare);\n return (ytBal - ptShare, false);\n }\n }\n}\n```\n | high |
```\nIs the admin/owner of the protocol/contracts TRUSTED or RESTRICTED?\n\nRestricted. The governor address should not be able to steal funds or prevent users from withdrawing. It does have access to the govern methods in Factory, and it could trigger liquidations by increasing nSigma. We consider this an acceptable risk, and the governor itself will have a timelock.\n```\n | medium |
```\naddress internal constant DIVIDER = 0x09B10E45A912BcD4E80a8A3119f0cfCcad1e1f12;\n```\n | medium |
```\nfunction sub(int256 a, int256 b) internal pure returns (int256) {\n int256 c = a - b;\n require((b >= 0 && c <= a) || (b < 0 && c > a));\n return c;\n}\n```\n | none |
```\nfunction verify(\n bytes32[] memory proof,\n bytes32 root,\n bytes32 leaf\n) internal pure returns (bool) {\n return processProof(proof, leaf) == root;\n}\n```\n | none |
```\nfunction setOperatorStrategyCap(\n RioLRTOperatorRegistryStorageV1.StorageV1 storage s,\n uint8 operatorId,\n IRioLRTOperatorRegistry.StrategyShareCap memory newShareCap\n ) internal {\n .\n OperatorUtilizationHeap.Data memory utilizationHeap = s.getOperatorUtilizationHeapForStrategy(newShareCap.strategy);\n // If the current cap is greater than 0 and the new cap is 0, remove the operator from the strategy.\n if (currentShareDetails.cap > 0 && newShareCap.cap == 0) {\n // If the operator has allocations, queue them for exit.\n if (currentShareDetails.allocation > 0) {\n operatorDetails.queueOperatorStrategyExit(operatorId, newShareCap.strategy);\n }\n // Remove the operator from the utilization heap.\n -> utilizationHeap.removeByID(operatorId);\n }\n .\n\n // Persist the updated heap to the active operators tracking.\n -> utilizationHeap.store(s.activeOperatorsByStrategyShareUtilization[newShareCap.strategy]);\n .\n }\n```\n | high |
```\nsetSettingUint('members.challenge.cooldown', 6172); // How long a member must wait before performing another challenge, approx. 1 day worth of blocks\nsetSettingUint('members.challenge.window', 43204); // How long a member has to respond to a challenge. 7 days worth of blocks\nsetSettingUint('members.challenge.cost', 1 ether); // How much it costs a non-member to challenge a members node. It's free for current members to challenge other members.\n```\n | high |
```\nassert(amount < targetReserveBalance);\n```\n | low |
```\nfunction swapTokensForEth(uint256 tokenAmount) private {\n // generate the uniswap pair path of token -> weth\n address[] memory path = new address[](2);\n path[0] = address(this);\n path[1] = dexRouter.WETH();\n\n _approve(address(this), address(dexRouter), tokenAmount);\n\n // make the swap\n dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(\n tokenAmount,\n 0, // accept any amount of ETH\n path,\n address(this),\n block.timestamp\n );\n}\n```\n | none |
```\n uint256 minPrice = base.getPrice(tokens[0]);\n for(uint256 i = 1; i != length; ++i) {\n uint256 price = base.getPrice(tokens[i]);\n minPrice = (price < minPrice) ? price : minPrice;\n }\n return minPrice.mulWadDown(pool.getRate());\n```\n | high |
```\n function testInsolvency() public {\n \n // ============== Setup Scenario ==============\n uint256 interestRateOne = 0.05 * 10**18; // Collateral // Quote (loaned token, short position)\n address poolThreeAddr = erc20PoolFactory.deployPool(address(dai), address(weth), interestRateOne);\n ERC20Pool poolThree = ERC20Pool(address(poolThreeAddr));\n vm.label(poolThreeAddr, "DAI / WETH Pool Three");\n\n // Setup scenario and send liquidity providers some tokens\n vm.startPrank(address(daiDoner));\n dai.transfer(address(charlie), 3200 ether);\n vm.stopPrank();\n\n vm.startPrank(address(wethDoner));\n weth.transfer(address(bob), 1000 ether);\n vm.stopPrank();\n\n // ==============================================\n\n\n // Note At the time (24/01/2023) of writing ETH is currently 1,625.02 DAI,\n // so this would be a popular bucket to deposit in.\n\n // Start Scenario\n // The lower dowm we go the cheaper wETH becomes - At a concentrated fenwick index of 5635, 1 wETH = 1600 DAI (Approx real life price)\n uint256 fenwick = 5635;\n\n vm.startPrank(address(alice));\n weth.deposit{value: 2 ether}();\n weth.approve(address(poolThree), 2.226 ether);\n poolThree.addQuoteToken(2 ether, fenwick); \n vm.stopPrank();\n\n vm.startPrank(address(bob));\n weth.deposit{value: 9 ether}();\n weth.approve(address(poolThree), 9 ether);\n poolThree.addQuoteToken(9 ether, fenwick); \n vm.stopPrank();\n\n assertEq(weth.balanceOf(address(poolThree)), 11 ether);\n\n\n // ======================== start testing ========================\n\n vm.startPrank(address(bob));\n bytes32 poolSubsetHashes = keccak256("ERC20_NON_SUBSET_HASH");\n IPositionManagerOwnerActions.MintParams memory mp = IPositionManagerOwnerActions.MintParams({\n recipient: address(bob),\n pool: address(poolThree),\n poolSubsetHash: poolSubsetHashes\n });\n positionManager.mint(mp);\n positionManager.setApprovalForAll(address(rewardsManager), true);\n rewardsManager.stake(1);\n vm.stopPrank();\n\n\n assertEq(dai.balanceOf(address(charlie)), 3200 ether);\n vm.startPrank(address(charlie)); // Charlie runs away with the weth tokens\n dai.approve(address(poolThree), 3200 ether);\n poolThree.drawDebt(address(charlie), 2 ether, fenwick, 3200 ether);\n vm.stopPrank();\n\n vm.warp(block.timestamp + 62 days);\n\n\n vm.startPrank(address(bob));\n weth.deposit{value: 0.5 ether}();\n weth.approve(address(poolThree), 0.5 ether);\n poolThree.kick(address(charlie)); // Kick off liquidation\n vm.stopPrank();\n\n vm.warp(block.timestamp + 10 hours);\n\n assertEq(weth.balanceOf(address(poolThree)), 9020189981190878108); // 9 ether\n\n\n vm.startPrank(address(bob));\n // Bob Takes a (pretend) flashloan of 1000 weth to get cheap dai tokens\n weth.approve(address(poolThree), 1000 ether);\n poolThree.take(address(charlie), 1000 ether , address(bob), "");\n weth.approve(address(poolThree), 1000 ether);\n poolThree.take(address(charlie), 1000 ether , address(bob), "");\n weth.approve(address(poolThree), 1000 ether);\n poolThree.take(address(charlie), 1000 ether , address(bob), "");\n weth.approve(address(poolThree), 1000 ether);\n poolThree.take(address(charlie), 1000 ether, address(bob), "");\n \n poolThree.settle(address(charlie), 100);\n vm.stopPrank();\n\n\n assertEq(weth.balanceOf(address(poolThree)), 9152686732755985308); // Pool balance is still 9 ether instead of 11 ether - insolvency. \n assertEq(dai.balanceOf(address(bob)), 3200 ether); // The original amount that charlie posted as deposit\n\n\n vm.warp(block.timestamp + 2 hours);\n // users attempt to withdraw after shaken by a liquidation\n vm.startPrank(address(alice));\n poolThree.removeQuoteToken(2 ether, fenwick);\n vm.stopPrank();\n\n vm.startPrank(address(bob));\n poolThree.removeQuoteToken(9 ether, fenwick);\n vm.stopPrank();\n\n assertEq(weth.balanceOf(address(bob)), 1007664981389220443074); // 1007 ether, originally 1009 ether\n assertEq(weth.balanceOf(address(alice)), 1626148471550317418); // 1.6 ether, originally 2 ether\n\n }\n```\n | medium |
```\nfunction getNonce(address sender, uint192 key)\npublic view override returns (uint256 nonce) {\n return nonceSequenceNumber[sender][key] | (uint256(key) << 64);\n}\n```\n | none |
```\nrequire(\_proposal.voters[\_voter].nonce < \_relayerNonce, "INVALID\_NONCE");\n```\n | low |
```\n function _routerSwap(\n uint16 _dstChainId,\n uint256 _srcPoolId,\n uint256 _dstPoolId,\n uint256 _amount,\n uint256 _slippage,\n address payable _oft,\n address _erc20\n ) private {\n bytes memory _dst = abi.encodePacked(connectedOFTs[_oft][_dstChainId].dstOft);\n IERC20(_erc20).safeApprove(address(router), _amount);\n router.swap{value: msg.value}(\n _dstChainId,\n _srcPoolId,\n _dstPoolId,\n payable(this),\n _amount,\n _computeMinAmount(_amount, _slippage),\n IStargateRouterBase.lzTxObj({dstGasForCall: 0, dstNativeAmount: 0, dstNativeAddr: "0x0"}),\n _dst,\n "0x"\n );\n }\n```\n | medium |
```\nfunction withdrawInsurance(uint256 amount, address to)\n external\n nonReentrant\n onlyOwner\n{\n if (amount == 0) {\n revert ZeroAmount();\n }\n\n insuranceDeposited -= amount;\n\n vault.withdraw(insuranceToken(), amount);\n IERC20(insuranceToken()).transfer(to, amount);\n\n emit InsuranceWithdrawn(msg.sender, to, amount);\n}\n```\n | high |
```\n function fund(IMarket market) external {\n if (!instances(IInstance(address(market)))) revert FactoryNotInstanceError();\n market.claimFee();\n }\n```\n | high |
```\nfunction setIncludeDividends(address account) public onlyOwner {\n dividendTracker.includeFromDividends(account);\n dividendTracker.setBalance(account, getMultiplier(account));\n}\n```\n | none |
```\nfunction dismissSlashProposal(uint256 \_proposalId, string[] calldata \_evidence) external onlyRole(SLASHING\_ARBITER\_ROLE) {\n \_transition(\_proposalId, DISMISSED);\n \_submitEvidence(\_proposalId, DISMISSED, \_evidence);\n \_returnDeposit(\_proposalId);\n \_unfreeze(\_proposalId);\n}\n```\n | high |
```\nfunction isExcludedFromAutoClaim(address account) external view onlyOwner returns (bool) {\n return excludedFromAutoClaim[account];\n}\n```\n | none |
```\nfunction setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {\n require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");\n\n _setAutomatedMarketMakerPair(pair, value);\n}\n```\n | none |
```\nFile: ERC20.sol\n function _mint(address account, uint256 amount) internal virtual {\n..SNIP..\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n unchecked {\n // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.\n _balances[account] += amount;\n }\n..SNIP..\n _afterTokenTransfer(address(0), account, amount);\n }\n```\n | high |
```\n function _swapFarmEmissionTokens() internal { IERC20Upgradeable boo = IERC20Upgradeable(BOO);\n uint256 booBalance = boo.balanceOf(address(this));\n if (booToUsdcPath.length < 2 || booBalance == 0) {\n return;\n }\n boo.safeIncreaseAllowance(SPOOKY_ROUTER, booBalance);\n uint256[] memory amounts = \n IUniswapV2Router02(SPOOKY_ROUTER).getAmountsOut(booBalance, booToUsdcPath);\n uint256 amountOutMin = (amounts[amounts.length - 1] * MAX_SLIPPAGE) / PERCENT_DIVISOR;\n IUniswapV2Router02(SPOOKY_ROUTER).swapExactTokensForTokensSupportingFeeOnTransferTokens( booBalance, amountOutMin, booToUsdcPath, address(this), block.timestamp );\n }\n```\n | medium |
```\ntoken.safeTransferFrom(\_from, address(this), \_amount);\n```\n | medium |
```\nfor (uint i = 0; i < shares.length; ++i) {\n skaleToken.send(address(skaleBalances), shares[i].amount, abi.encode(shares[i].holder));\n\n uint created = delegationController.getDelegation(shares[i].delegationId).created;\n uint delegationStarted = timeHelpers.getNextMonthStartFromDate(created);\n skaleBalances.lockBounty(shares[i].holder, timeHelpers.addMonths(delegationStarted, 3));\n}\n```\n | high |
```\nfunction sendInterests(Loan storage loan, Provision storage provision) internal returns (uint256 sent) {\n uint256 interests = loan.payment.paid - loan.lent;\n if (interests == loan.payment.minInterestsToRepay) {\n // this is the case if the loan is repaid shortly after issuance\n // each lender gets its minimal interest, as an anti ddos measure to spam offer\n sent = provision.amount + (interests / loan.nbOfPositions);\n } else {\n /* provision.amount / lent = share of the interests belonging to the lender. The parenthesis make the\n calculus in the order that maximizes precison */\n sent = provision.amount + (interests * (provision.amount)) / loan.lent; <- audit-issue minimal interest isn't guaranteed\n }\n loan.assetLent.checkedTransfer(msg.sender, sent);\n}\n```\n | medium |
```\nfunction \_stakeDAIx(address \_user, uint256 \_amount, address \_policyBookAddr) internal {\n require (\_amount > 0, "BMIDAIStaking: Can't stake zero tokens");\n\n PolicyBook \_policyBook = PolicyBook(\_policyBookAddr);\n // transfer DAI from PolicyBook to yield generator\n daiToken.transferFrom(\_policyBookAddr, address(defiYieldGenerator), \_amount); \n\n // transfer bmiDAIx from user to staking\n \_policyBook.transferFrom(\_user, address(this), \_amount); \n\n \_mintNFT(\_user, \_amount, \_policyBook);\n}\n```\n | high |
```\nfunction _setTransceiver(address transceiver) internal returns (uint8 index) {\n /* snip */\n if (transceiver == address(0)) {\n revert InvalidTransceiverZeroAddress();\n }\n\n if (_numTransceivers.registered >= MAX_TRANSCEIVERS) {\n revert TooManyTransceivers();\n }\n\n if (transceiverInfos[transceiver].registered) {\n transceiverInfos[transceiver].enabled = true;\n } else {\n /* snip */\n}\n```\n | medium |
```\nfunction ownerToggleSalesTax(bool state) external onlyOwner() {\n toggleSalesTax(state);\n emit ToggledSalesTax(state);\n}\n```\n | none |
```\nfunction _setOwner(address newOwner) private {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n}\n```\n | none |
```\nfunction donationAddress() public view returns (address) {\n return _donationAddress;\n}\n```\n | none |
```\n/// @notice Adds an external ERC721 token 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/// NOTE: The NFT must already be owned by the Prize-Pool\n/// @param \_externalErc721 The address of an ERC721 token to be awarded\n/// @param \_tokenIds An array of token IDs of the ERC721 to be awarded\nfunction addExternalErc721Award(address \_externalErc721, uint256[] calldata \_tokenIds) external onlyOwnerOrListener {\n // require(\_externalErc721.isContract(), "PeriodicPrizeStrategy/external-erc721-not-contract");\n require(prizePool.canAwardExternal(\_externalErc721), "PeriodicPrizeStrategy/cannot-award-external");\n \n if (!externalErc721s.contains(\_externalErc721)) {\n externalErc721s.addAddress(\_externalErc721);\n }\n\n for (uint256 i = 0; i < \_tokenIds.length; i++) {\n uint256 tokenId = \_tokenIds[i];\n require(IERC721(\_externalErc721).ownerOf(tokenId) == address(prizePool), "PeriodicPrizeStrategy/unavailable-token");\n externalErc721TokenIds[\_externalErc721].push(tokenId);\n }\n\n emit ExternalErc721AwardAdded(\_externalErc721, \_tokenIds);\n}\n```\n | medium |
```\n function triggerRoot() external {\n bytes32 rootCandidateAValue = rootCandidateA.value;\n if (rootCandidateAValue != rootCandidateB.value || rootCandidateAValue == bytes32(0)) revert RootCandidatesInvalid();\n root = Root({value: rootCandidateAValue, lastUpdatedAt: block.timestamp});\n emit RootChanged(msg.sender, rootCandidateAValue);\n }\n```\n | medium |
```\nfunction sendValue(address payable recipient, uint256 amount) internal {\n require(\n address(this).balance >= amount,\n "Address: insufficient balance"\n );\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{value: amount}("");\n require(\n success,\n "Address: unable to send value, recipient may have reverted"\n );\n}\n```\n | none |
```\n /**\n * @notice Get token A and token B's LP token amount required for a given value\n * @param givenValue Given value needed, expressed in 1e30 -------------------------- refer this\n * @param marketToken LP token address\n * @param indexToken Index token address\n * @param longToken Long token address\n * @param shortToken Short token address\n * @param isDeposit Boolean for deposit or withdrawal\n * @param maximize Boolean for minimum or maximum price\n * @return lpTokenAmount Amount of LP tokens; expressed in 1e18 --------------> refer this\n */\n function getLpTokenAmount(\n uint256 givenValue,\n address marketToken,\n address indexToken,\n address longToken,\n address shortToken,\n bool isDeposit,\n bool maximize\n ) public view returns (uint256) {\n uint256 _lpTokenValue = getLpTokenValue(\n marketToken,\n indexToken,\n longToken,\n shortToken,\n isDeposit,\n maximize\n );\n\n\n return givenValue * SAFE_MULTIPLIER / _lpTokenValue;\n }\n```\n | low |
```\nfunction processAccount(address payable account, bool automatic) public onlyOwner\n returns (bool)\n{\n if (dividendsPaused) {\n return false;\n }\n\n bool reinvest = autoReinvest[account];\n\n if (automatic && reinvest && !allowAutoReinvest) {\n return false;\n }\n\n uint256 amount = reinvest\n ? _reinvestDividendOfUser(account)\n : _withdrawDividendOfUser(account);\n\n if (amount > 0) {\n lastClaimTimes[account] = block.timestamp;\n if (reinvest) {\n emit DividendReinvested(account, amount, automatic);\n } \n else {\n emit Claim(account, amount, automatic);\n }\n return true;\n }\n\n return false;\n}\n```\n | none |
```\nfunction mod(uint256 a, uint256 b) internal pure returns (uint256) {\n return a % b;\n}\n```\n | none |
```\nfunction _withdraw(address account) internal returns (uint256 withdrawn) {\n // leave balance of 1 for gas efficiency\n // underflow if ethBalance is 0\n withdrawn = ethBalances[account] - 1;\n ethBalances[account] = 1;\n account.safeTransferETH(withdrawn);\n}\n```\n | none |
```\nfunction owner() public view returns (address) {\n return _owner;\n}\n```\n | none |
```\nfunction _distributeETH(\n address split,\n address[] memory accounts,\n uint32[] memory percentAllocations,\n uint32 distributorFee,\n address distributorAddress\n) internal {\n uint256 mainBalance = ethBalances[split];\n uint256 proxyBalance = split.balance;\n // if mainBalance is positive, leave 1 in SplitMain for gas efficiency\n uint256 amountToSplit;\n unchecked {\n // underflow should be impossible\n if (mainBalance > 0) mainBalance -= 1;\n // overflow should be impossible\n amountToSplit = mainBalance + proxyBalance;\n }\n if (mainBalance > 0) ethBalances[split] = 1;\n // emit event with gross amountToSplit (before deducting distributorFee)\n emit DistributeETH(split, amountToSplit, distributorAddress);\n if (distributorFee != 0) {\n // given `amountToSplit`, calculate keeper fee\n uint256 distributorFeeAmount = _scaleAmountByPercentage(\n amountToSplit,\n distributorFee\n );\n unchecked {\n // credit keeper with fee\n // overflow should be impossible with validated distributorFee\n ethBalances[\n distributorAddress != address(0) ? distributorAddress : msg.sender\n ] += distributorFeeAmount;\n // given keeper fee, calculate how much to distribute to split recipients\n // underflow should be impossible with validated distributorFee\n amountToSplit -= distributorFeeAmount;\n }\n }\n unchecked {\n // distribute remaining balance\n // overflow should be impossible in for-loop index\n // cache accounts length to save gas\n uint256 accountsLength = accounts.length;\n for (uint256 i = 0; i < accountsLength; ++i) {\n // overflow should be impossible with validated allocations\n ethBalances[accounts[i]] += _scaleAmountByPercentage(\n amountToSplit,\n percentAllocations[i]\n );\n }\n }\n // flush proxy ETH balance to SplitMain\n // split proxy should be guaranteed to exist at this address after validating splitHash\n // (attacker can't deploy own contract to address with high balance & empty sendETHToMain\n // to drain ETH from SplitMain)\n // could technically check if (change in proxy balance == change in SplitMain balance)\n // before/after external call, but seems like extra gas for no practical benefit\n if (proxyBalance > 0) SplitWallet(split).sendETHToMain(proxyBalance);\n}\n```\n | none |
```\nfunction add(uint x, uint y) internal pure returns (uint z) {\n require((z = x + y) >= x, "add-overflow");\n}\n```\n | low |
```\nreceive() external payable {}\n```\n | none |
```\nuint256 realDebt = borrows.div(record.interestIndex == 0 ? 1e18 : record.interestIndex).mul(info.borrowIndex);\n```\n | medium |
```\nfunction toggleSalesTax(bool state) private {\n timeSalesTaxEnabled = block.timestamp;\n salesTaxEnabled = state;\n}\n```\n | none |
```\nfunction changeWalletLimit(uint256 newLimit) external onlyOwner {\n require(\n newLimit >= _totalSupply / 100,\n "New wallet limit should be at least 1% of total supply"\n );\n maxBag = newLimit;\n emit MaxBagChanged(newLimit);\n}\n```\n | none |
```\nmapping(uint256 => EnumerableSetUpgradeable.AddressSet)\n internal commitmentBorrowersList;\n \nfunction updateCommitmentBorrowers(\n uint256 _commitmentId,\n address[] calldata _borrowerAddressList\n ) public commitmentLender(_commitmentId) {\n delete commitmentBorrowersList[_commitmentId];\n _addBorrowersToCommitmentAllowlist(_commitmentId, _borrowerAddressList);\n }\n```\n | medium |
```\nfunction _prepareTake(\n Liquidation memory liquidation_,\n uint256 t0Debt_,\n uint256 collateral_,\n uint256 inflator_\n ) internal view returns (TakeLocalVars memory vars) {\n // rest of code// rest of code..\n vars.auctionPrice = _auctionPrice(liquidation_.referencePrice, kickTime);\n vars.bondFactor = liquidation_.bondFactor;\n vars.bpf = _bpf(\n vars.borrowerDebt,\n collateral_,\n neutralPrice,\n liquidation_.bondFactor,\n vars.auctionPrice\n );\n```\n | medium |
```\n function _sendPayout(\n address recipient_,\n uint256 payoutAmount_,\n Routing memory routingParams_,\n bytes memory\n ) internal {\n \n if (fromVeecode(derivativeReference) == bytes7("")) {\n Transfer.transfer(baseToken, recipient_, payoutAmount_, true);\n }\n else {\n \n DerivativeModule module = DerivativeModule(_getModuleIfInstalled(derivativeReference));\n\n Transfer.approve(baseToken, address(module), payoutAmount_);\n\n=> module.mint(\n recipient_,\n address(baseToken),\n routingParams_.derivativeParams,\n payoutAmount_,\n routingParams_.wrapDerivative\n );\n```\n | medium |
```\nfunction init(address accountantaddress) external {\n require(!initialized);\n initialized = true;\n accountant = zAuctionAccountant(accountantaddress);\n}\n```\n | medium |
```\nfunction safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 value\n) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n}\n```\n | none |
```\nfunction checkGasV1(bytes calldata _message)\n public\n view\n returns (uint256, uint256)\n {\n uint256 gas1 = gasleft();\n bytes32 versionedHash = Hashing.hashCrossDomainMessageV1(\n 0,\n address(this),\n address(this),\n 0,\n 0,\n _message\n );\n uint256 gas2 = gasleft();\n return (_message.length, (gas1 - gas2));\n }\n```\n | medium |
```\n function claimReward() external onlyOwner {\n for (uint256 marketId; marketId < totalMarkets; marketId++) {\n _registrations[marketId].read().market.claimReward();\n _registrations[marketId].read().market.reward().push(factory().owner());\n }\n }\n```\n | medium |
```\nFile: StrategyUtils.sol\n function _checkPriceLimit(\n StrategyContext memory strategyContext,\n uint256 oraclePrice,\n uint256 poolPrice\n ) internal pure {\n uint256 lowerLimit = (oraclePrice * \n (VaultConstants.VAULT_PERCENT_BASIS - strategyContext.vaultSettings.oraclePriceDeviationLimitPercent)) / \n VaultConstants.VAULT_PERCENT_BASIS;\n uint256 upperLimit = (oraclePrice * \n (VaultConstants.VAULT_PERCENT_BASIS + strategyContext.vaultSettings.oraclePriceDeviationLimitPercent)) / \n VaultConstants.VAULT_PERCENT_BASIS;\n\n if (poolPrice < lowerLimit || upperLimit < poolPrice) {\n revert Errors.InvalidPrice(oraclePrice, poolPrice);\n }\n }\n```\n | medium |
```\nrequire(weightSum >= 1e18 && weightSum <= 4e18, "Basket weight must be >= 100 && <= 400%");\n```\n | low |
```\nfunction SetZauction(address zauctionaddress) external onlyAdmin{\n zauction = zauctionaddress;\n emit ZauctionSet(zauctionaddress);\n}\n```\n | medium |
```\n function _allocate(bytes memory _data, address _sender) internal virtual override {\n …\n\n // check that the recipient has voice credits left to allocate\n if (!_hasVoiceCreditsLeft(voiceCreditsToAllocate, allocator.voiceCredits)) revert INVALID();\n\n _qv_allocate(allocator, recipient, recipientId, voiceCreditsToAllocate, _sender);\n }\n```\n | high |
```\nfunction emergencyShutdown() external onlyRole("emergency_shutdown") {\n active = false;\n\n // If necessary, defund sDAI.\n uint256 sdaiBalance = sdai.balanceOf(address(this));\n if (sdaiBalance != 0) defund(sdai, sdaiBalance);\n\n // If necessary, defund DAI.\n uint256 daiBalance = dai.balanceOf(address(this));\n if (daiBalance != 0) defund(dai, daiBalance);\n\n emit Deactivated();\n}\n```\n | medium |
```\n// ABI encode calldata for `fillOrder`\nbytes memory fillOrderCalldata = abi.encodeWithSelector(\n IExchangeCore(address(0)).fillOrder.selector,\n order,\n takerAssetFillAmount,\n signature\n);\n\n(bool didSucceed, bytes memory returnData) = address(this).delegatecall(fillOrderCalldata);\n```\n | medium |
```\n uint256 relayerFee = _relayerFee != 0 ? _relayerFee : msg.value;\n IConnext(connext).xcall{value: relayerFee}(\n _destinationDomain, // _destination: Domain ID of the destination chain\n target, // _to: address of the target contract\n address(0), // _asset: use address zero for 0-value transfers\n msg.sender, // _delegate: address that can revert or forceLocal on destination\n 0, // _amount: 0 because no funds are being transferred\n 0, // _slippage: can be anything between 0-10000 because no funds are being transferred\n _callData // _callData: the encoded calldata to send\n );\n }\n```\n | high |
```\nFile: BalancerComposableAuraVault.sol\n function _checkPriceAndCalculateValue() internal view override returns (uint256) {\n (uint256[] memory balances, uint256[] memory spotPrices) = SPOT_PRICE.getComposableSpotPrices(\n BALANCER_POOL_ID,\n address(BALANCER_POOL_TOKEN),\n PRIMARY_INDEX()\n );\n\n // Spot prices are returned in native decimals, convert them all to POOL_PRECISION\n // as required in the _calculateLPTokenValue method.\n (/* */, uint8[] memory decimals) = TOKENS();\n for (uint256 i; i < spotPrices.length; i++) {\n spotPrices[i] = spotPrices[i] * POOL_PRECISION() / 10 ** decimals[i];\n }\n\n return _calculateLPTokenValue(balances, spotPrices);\n }\n```\n | high |
```\n function afterDepositExecution(\n bytes32 depositKey,\n IDeposit.Props memory /* depositProps */,\n IEvent.Props memory /* eventData */\n ) external onlyController {\n GMXTypes.Store memory _store = vault.store();\n\n if (\n _store.status == GMXTypes.Status.Deposit &&\n _store.depositCache.depositKey == depositKey\n ) {\n vault.processDeposit();\n } else if (\n _store.status == GMXTypes.Status.Rebalance_Add &&\n _store.rebalanceCache.depositKey == depositKey\n ) {\n vault.processRebalanceAdd();\n } else if (\n _store.status == GMXTypes.Status.Compound &&\n _store.compoundCache.depositKey == depositKey\n ) {\n vault.processCompound();\n } else if (\n _store.status == GMXTypes.Status.Withdraw_Failed &&\n _store.withdrawCache.depositKey == depositKey\n ) {\n vault.processWithdrawFailureLiquidityAdded();\n } else if (_store.status == GMXTypes.Status.Resume) {\n // This if block is to catch the Deposit callback after an\n // emergencyResume() to set the vault status to Open\n vault.processEmergencyResume();\n }\n \n\n@ > // The function does nothing as the conditions are not met\n }\n```\n | medium |
```\nunction testAttack() public {\n mockRootPrice(WSTETH, 1_123_300_000_000_000_000); //wstETH\n mockRootPrice(CBETH, 1_034_300_000_000_000_000); //cbETH\n\n IBalancerMetaStablePool pool = IBalancerMetaStablePool(WSTETH_CBETH_POOL);\n\n address[] memory assets = new address[](2);\n assets[0] = WSTETH;\n assets[1] = CBETH;\n uint256[] memory amounts = new uint256[](2);\n amounts[0] = 10_000 ether;\n amounts[1] = 0;\n\n IBalancerVault.JoinPoolRequest memory joinRequest = IBalancerVault.JoinPoolRequest({\n assets: assets,\n maxAmountsIn: amounts, // maxAmountsIn,\n userData: abi.encode(\n IBalancerVault.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT,\n amounts, //maxAmountsIn,\n 0\n ),\n fromInternalBalance: false\n });\n\n IBalancerVault.SingleSwap memory swapRequest = IBalancerVault.SingleSwap({\n poolId: 0x9c6d47ff73e0f5e51be5fd53236e3f595c5793f200020000000000000000042c,\n kind: IBalancerVault.SwapKind.GIVEN_IN,\n assetIn: WSTETH,\n assetOut: CBETH,\n amount: amounts[0],\n userData: abi.encode(\n IBalancerVault.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT,\n amounts, //maxAmountsIn,\n 0\n )\n });\n\n IBalancerVault.FundManagement memory funds = IBalancerVault.FundManagement({\n sender: address(this),\n fromInternalBalance: false,\n recipient: payable(address(this)),\n toInternalBalance: false\n });\n\n emit log_named_uint("Gas before price1", gasleft());\n uint256 price1 = oracle.getPriceInEth(WSTETH_CBETH_POOL);\n emit log_named_uint("price1", price1);\n emit log_named_uint("Gas after price1 ", gasleft());\n }\n```\n | medium |
```\nfunction hash256(bytes memory \_b) internal pure returns (bytes32) {\n return abi.encodePacked(sha256(abi.encodePacked(sha256(\_b)))).toBytes32();\n}\n```\n | low |
```\nFile: BaseLSTAdapter.sol\n function prefundedDeposit() external nonReentrant returns (uint256, uint256) {\n..SNIP..\n uint256 stakeAmount;\n unchecked {\n stakeAmount = availableEth + queueEthCache - targetBufferEth; // non-zero, no underflow\n }\n // If the stake amount exceeds 95% of the available ETH, cap the stake amount.\n // This is to prevent the buffer from being completely drained. This is not a complete solution.\n //\n // The condition: stakeAmount > availableEth, is equivalent to: queueEthCache > targetBufferEth\n // Possible scenarios:\n // - Target buffer percentage was changed to a lower value and there is a large withdrawal request pending.\n // - There is a pending withdrawal request and the available ETH are not left in the buffer.\n // - There is no pending withdrawal request and the available ETH are not left in the buffer.\n uint256 maxStakeAmount = (availableEth * 95) / 100;\n if (stakeAmount > maxStakeAmount) {\n stakeAmount = maxStakeAmount; // max 95% of the available ETH\n }\n\n /// INTERACT ///\n // Deposit into the yield source\n // Actual amount of ETH spent may be less than the requested amount.\n stakeAmount = _stake(stakeAmount); // stake amount can be 0\n```\n | medium |
```\nfunction setIsPool(address contractAddress, bool contractIsPool) public onlyOwner {\n isPool[contractAddress] = contractIsPool;\n emit IsPool(contractAddress, contractIsPool);\n}\n```\n | none |
```\n/// @dev Set read-only mode (state cannot be changed).\nfunction setReadOnlyMode(bool shouldSetReadOnlyMode)\n external\n onlyAuthorized\n{\n // solhint-disable-next-line not-rely-on-time\n uint96 timestamp = block.timestamp.downcastToUint96();\n if (shouldSetReadOnlyMode) {\n stakingContract = readOnlyProxy;\n readOnlyState = IStructs.ReadOnlyState({\n isReadOnlyModeSet: true,\n lastSetTimestamp: timestamp\n });\n```\n | medium |
```\n function takeOverPool(GoatTypes.InitParams memory initParams) external {\n if (_vestingUntil != _MAX_UINT32) {\n revert GoatErrors.ActionNotAllowed();\n }\n\n GoatTypes.InitialLPInfo memory initialLpInfo = _initialLPInfo;\n\n GoatTypes.LocalVariables_TakeOverPool memory localVars;\n address to = msg.sender;\n localVars.virtualEthOld = _virtualEth;\n localVars.bootstrapEthOld = _bootstrapEth;\n localVars.initialTokenMatchOld = _initialTokenMatch;\n\n (localVars.tokenAmountForPresaleOld, localVars.tokenAmountForAmmOld) = _tokenAmountsForLiquidityBootstrap(\n localVars.virtualEthOld,\n localVars.bootstrapEthOld,\n initialLpInfo.initialWethAdded,\n localVars.initialTokenMatchOld\n );\n\n // new token amount for bootstrap if no swaps would have occured\n (localVars.tokenAmountForPresaleNew, localVars.tokenAmountForAmmNew) = _tokenAmountsForLiquidityBootstrap(\n initParams.virtualEth, initParams.bootstrapEth, initParams.initialEth, initParams.initialTokenMatch\n );\n\n // team needs to add min 10% more tokens than the initial lp to take over\n localVars.minTokenNeeded =\n ((localVars.tokenAmountForPresaleOld + localVars.tokenAmountForAmmOld) * 11000) / 10000;\n\n481 if ((localVars.tokenAmountForAmmNew + localVars.tokenAmountForPresaleNew) < localVars.minTokenNeeded) {\n revert GoatErrors.InsufficientTakeoverTokenAmount();\n }\n\n localVars.reserveEth = _reserveEth;\n\n // Actual token amounts needed if the reserves have updated after initial lp mint\n (localVars.tokenAmountForPresaleNew, localVars.tokenAmountForAmmNew) = _tokenAmountsForLiquidityBootstrap(\n initParams.virtualEth, initParams.bootstrapEth, localVars.reserveEth, initParams.initialTokenMatch\n );\n localVars.reserveToken = _reserveToken;\n\n // amount of tokens transferred by the new team\n uint256 tokenAmountIn = IERC20(_token).balanceOf(address(this)) - localVars.reserveToken;\n\n if (\n tokenAmountIn\n < (\n localVars.tokenAmountForPresaleOld + localVars.tokenAmountForAmmOld - localVars.reserveToken\n + localVars.tokenAmountForPresaleNew + localVars.tokenAmountForAmmNew\n )\n ) {\n revert GoatErrors.IncorrectTokenAmount();\n }\n\n localVars.pendingLiquidityFees = _pendingLiquidityFees;\n localVars.pendingProtocolFees = _pendingProtocolFees;\n\n // amount of weth transferred by the new team\n uint256 wethAmountIn = IERC20(_weth).balanceOf(address(this)) - localVars.reserveEth\n - localVars.pendingLiquidityFees - localVars.pendingProtocolFees;\n\n if (wethAmountIn < localVars.reserveEth) {\n revert GoatErrors.IncorrectWethAmount();\n }\n\n _handleTakeoverTransfers(\n IERC20(_weth), IERC20(_token), initialLpInfo.liquidityProvider, localVars.reserveEth, localVars.reserveToken\n );\n\n uint256 lpBalance = balanceOf(initialLpInfo.liquidityProvider);\n _burn(initialLpInfo.liquidityProvider, lpBalance);\n\n // new lp balance\n lpBalance = Math.sqrt(uint256(initParams.virtualEth) * initParams.initialTokenMatch) - MINIMUM_LIQUIDITY;\n _mint(to, lpBalance);\n\n _updateStateAfterTakeover(\n initParams.virtualEth,\n initParams.bootstrapEth,\n initParams.initialTokenMatch,\n wethAmountIn,\n tokenAmountIn,\n lpBalance,\n to,\n initParams.initialEth\n );\n }\n```\n | medium |
```\n(\n uint256 initialPrice,\n uint256 scalingFactor,\n uint256 timeCoefficient,\n uint256 bucketSize,\n bool isDecreasing,\n uint256 maxPrice,\n uint256 minPrice\n) = getDecodedData(_priceAdapterConfigData);\n\nuint256 timeBucket = _timeElapsed / bucketSize;\n\nint256 expArgument = int256(timeCoefficient * timeBucket);\n\nuint256 expExpression = uint256(FixedPointMathLib.expWad(expArgument));\n\nuint256 priceChange = scalingFactor * expExpression - WAD;\n```\n | medium |
```\nconstructor(string memory name, string memory version) {\n _name = name.toShortStringWithFallback(_nameFallback);\n _version = version.toShortStringWithFallback(_versionFallback);\n _hashedName = keccak256(bytes(name));\n _hashedVersion = keccak256(bytes(version));\n\n _cachedChainId = block.chainid;\n _cachedDomainSeparator = _buildDomainSeparator();\n _cachedThis = address(this);\n}\n```\n | none |
```\nfunction _placePerpOrder(\n uint256 amount,\n bool isShort,\n bool amountIsInput,\n uint160 sqrtPriceLimit\n) private returns (uint256, uint256) {\n uint256 upperBound = 0; // 0 = no limit, limit set by sqrtPriceLimit\n\n IClearingHouse.OpenPositionParams memory params = IClearingHouse\n .OpenPositionParams({\n baseToken: market,\n isBaseToQuote: isShort, // true for short\n isExactInput: amountIsInput, // we specify exact input amount\n amount: amount, // collateral amount - fees\n oppositeAmountBound: upperBound, // output upper bound\n // solhint-disable-next-line not-rely-on-time\n deadline: block.timestamp,\n sqrtPriceLimitX96: sqrtPriceLimit, // max slippage\n referralCode: 0x0\n });\n\n (uint256 baseAmount, uint256 quoteAmount) = clearingHouse.openPosition(\n params\n );\n\n uint256 feeAmount = _calculatePerpOrderFeeAmount(quoteAmount);\n totalFeesPaid += feeAmount;\n\n emit PositionOpened(isShort, amount, amountIsInput, sqrtPriceLimit);\n return (baseAmount, quoteAmount);\n}\n\nfunction _calculatePerpOrderFeeAmount(uint256 amount)\n internal\n view\n returns (uint256)\n{\n return amount.mulWadUp(getExchangeFeeWad());\n}\n```\n | medium |
```\nfunction sendValue(address payable recipient, uint256 amount) internal {\n require(\n address(this).balance >= amount,\n "Address: insufficient balance"\n );\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{value: amount}("");\n require(\n success,\n "Address: unable to send value, recipient may have reverted"\n );\n}\n```\n | none |
```\n (lpPrice(\n virtualPrice,\n base.getPrice(tokens[1]),\n ethPrice,\n base.getPrice(tokens[0])\n ) * 1e18) / ethPrice;\n```\n | high |
```\nfunction _takeWalletFee(uint256 tWallet) private {\n uint256 currentRate = _getRate();\n uint256 rWallet = tWallet.mul(currentRate);\n _rOwned[address(this)] = _rOwned[address(this)].add(rWallet);\n if (_isExcluded[address(this)])\n _tOwned[address(this)] = _tOwned[address(this)].add(tWallet);\n}\n```\n | none |
```\nfunction _convertToToken(address token, address receiver) internal returns (uint256 amountOut) {\n // this value should be whatever glp is received by calling withdraw/redeem to junior vault\n uint256 outputGlp = fsGlp.balanceOf(address(this));\n\n // using min price of glp because giving in glp\n uint256 glpPrice = _getGlpPrice(false);\n\n // using max price of token because taking token out of gmx\n uint256 tokenPrice = gmxVault.getMaxPrice(token);\n\n // apply slippage threshold on top of estimated output amount\n uint256 minTokenOut = outputGlp.mulDiv(glpPrice * (MAX_BPS - slippageThreshold), tokenPrice * MAX_BPS);\n\n // will revert if atleast minTokenOut is not received\n amountOut = rewardRouter.unstakeAndRedeemGlp(address(token), outputGlp, minTokenOut, receiver);\n}\n```\n | medium |
```\nfunction freezeSchains(uint nodeIndex) external allow("SkaleManager") {\n SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));\n bytes32[] memory schains = schainsInternal.getActiveSchains(nodeIndex);\n for (uint i = 0; i < schains.length; i++) {\n Rotation memory rotation = rotations[schains[i]];\n if (rotation.nodeIndex == nodeIndex && now < rotation.freezeUntil) {\n continue;\n }\n string memory schainName = schainsInternal.getSchainName(schains[i]);\n string memory revertMessage = "Node cannot rotate on Schain ";\n revertMessage = revertMessage.strConcat(schainName);\n revertMessage = revertMessage.strConcat(", occupied by Node ");\n revertMessage = revertMessage.strConcat(rotation.nodeIndex.uint2str());\n string memory dkgRevert = "DKG process did not finish on schain ";\n ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));\n require(\n skaleDKG.isLastDKGSuccessful(keccak256(abi.encodePacked(schainName))),\n dkgRevert.strConcat(schainName));\n require(rotation.freezeUntil < now, revertMessage);\n \_startRotation(schains[i], nodeIndex);\n }\n}\n```\n | medium |
```\nfunction set(uint256 \_pid, uint128 \_allocPoint, IRewarder \_rewarder, bool overwrite) public onlyGovernor {\n totalAllocPoint = (totalAllocPoint - poolInfo[\_pid].allocPoint) + \_allocPoint;\n poolInfo[\_pid].allocPoint = \_allocPoint.toUint64();\n\n if (overwrite) {\n rewarder[\_pid] = \_rewarder;\n }\n\n emit LogSetPool(\_pid, \_allocPoint, overwrite ? \_rewarder : rewarder[\_pid], overwrite);\n}\n```\n | low |
```\nfunction safeApprove(\n IERC20 token,\n address spender,\n uint256 value\n) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n "SafeERC20: approve from non-zero to non-zero allowance"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n}\n```\n | none |
```\nfunction abs(int256 a) internal pure returns (int256) {\n require(a != MIN_INT256);\n return a < 0 ? -a : a;\n}\n```\n | none |
```\nfunction createSender(bytes calldata initCode) external returns (address sender) {\n address factory = address(bytes20(initCode[0 : 20]));\n bytes memory initCallData = initCode[20 :];\n bool success;\n /* solhint-disable no-inline-assembly */\n assembly {\n success := call(gas(), factory, 0, add(initCallData, 0x20), mload(initCallData), 0, 32)\n sender := mload(0)\n }\n if (!success) {\n sender = address(0);\n }\n}\n```\n | none |
```\nif (upcomingMilestone != 0) revert MILESTONES_ALREADY_SET();\n```\n | medium |
```\nFile: BalancerSpotPrice.sol\n function _calculateStableMathSpotPrice(\n..SNIP..\n // Apply scale factors\n uint256 secondary = balances[index2] * scalingFactors[index2] / BALANCER_PRECISION;\n\n uint256 invariant = StableMath._calculateInvariant(\n ampParam, StableMath._balances(scaledPrimary, secondary), true // round up\n );\n\n spotPrice = StableMath._calcSpotPrice(ampParam, invariant, scaledPrimary, secondary);\n..SNIP..\n```\n | high |
Subsets and Splits