Farseen0/scar-pairs huggingface dataset:
MEDIUM severity: The `AssetManager.rebalance()` function is vulnerable to reverting when the balance of a specific to. The `AssetManager.rebalance()` function is vulnerable to reverting when the balance of a specific token address in a money market is zero. This occurs because the function attempts to withdraw tokens from each money market for rebalancing purposes, but when the balance of the token address is zero,...

Vulnerable code:
```\nfor (uint256 i = 0; i < moneyMarketsLength; i++) {\n    IMoneyMarketAdapter moneyMarket = moneyMarkets[i];\n    if (!moneyMarket.supportsToken(tokenAddress)) {\n        continue;\n    }\n    moneyMarket.withdrawAll(tokenAddress, address(this));\n\n    supportedMoneyMarkets[supportedMoneyMarketsSize] = moneyMarket;\n    supportedMoneyMarketsSize++;\n}\n```\n```\nfunction validateWithdraw(\n    DataTypes.ReserveCache memory reserveCache,\n    uint256 amount,\n    uint256 userBalance\n) internal pure {\n    require(amount!= 0, Errors.INVALID_AMOUNT);\n```
MEDIUM severity: The vulnerability arises from the division operation in the `currentRewardsPerToken` function, which. The vulnerability arises from the division operation in the `currentRewardsPerToken` function, which can lead to a loss of precision in the calculation of rewards. This is particularly concerning when the reward update time elapse is small, as it can result in a significant reduction in the calculat...

Vulnerable code:
```\nfunction currentRewardsPerToken() public view returns (uint256) {\n    if (totalBalance == 0) return rewardsPerTokenStored;\n\n    uint256 rewardsToApply = ((block.timestamp - lastRewardUpdate) * rewardRate) / REWARD_PERIOD;\n\n    return rewardsPerTokenStored + (rewardsToApply * 10 ** stakedTokenDecimals) / totalBalance;\n}\n```\n```\n/// @notice Amount of time (in seconds) that the reward rate is distributed over\nuint48 public constant REWARD_PERIOD = uint48(1 days);\n```
MEDIUM severity: The `Base._updateInterest` method is responsible for updating the interest accumulated on borrows be. The `Base._updateInterest` method is responsible for updating the interest accumulated on borrows before executing most methods in the contract. This method utilizes the contract's interest rate model to calculate the borrow interest rate. If the calculated value exceeds the `maxBorrowRate` (0.001e1...

Vulnerable code:
```\nfunction _updateInterest() internal virtual override {\n    InterestLocalVars memory _vars;\n    _vars.currentCash = _getCurrentCash();\n    _vars.totalBorrows = totalBorrows;\n    _vars.totalReserves = totalReserves;\n\n    _vars.borrowRate = interestRateModel.getBorrowRate(\n        _vars.currentCash,\n        _vars.totalBorrows,\n        _vars.totalReserves\n    );\n    require(\n        _vars.borrowRate <= maxBorrowRate,\n        "_updateInterest: Borrow rate is too high!"\n    );\n}\n```\n```\n/**\n * @dev Sets a new interest rate model.\n * @param _newInterestRateModel The new interest rate model.\n */\nfunction _setInterestRateModel(\n    IInterestRateModelInterface _newInterestRateModel\n) external virtual onlyOwner {\n    // Gets current interest rate model.\n    IInterestRateModelInterface _oldInterestRateModel = interestRateModel;\n\n    // Ensures the input address is the interest model contract.\n    require(\n        _newInterestRateModel.isInterestRateModel(),\n        "_setInterestRateModel: This is not the rate model contract!"\n    );\n\n    // Set to the new interest rate model.\n    interestRateModel = _newInterestRateModel;\n}\n```\n```\nbaseInterestPerBlock = 0\ninterestPerBlock = 5.074e10\nhighInterestPerBlock = 4.756e11\nhigh = 0.75e18\n```
MEDIUM severity: The `_getChainlinkResponse()` function, responsible for retrieving the price of tokens, is vulnerabl. The `_getChainlinkResponse()` function, responsible for retrieving the price of tokens, is vulnerable to returning stale results. This function relies on the `AggregatorV3Interface` contract's `latestRoundData()` method to fetch the latest price data from Chainlink. However, it does not perform any...

Vulnerable code:
```\nfunction _getChainlinkResponse(address _feed) internal view returns (ChainlinkResponse memory) {\n    ChainlinkResponse memory _chainlinkResponse;\n\n    _chainlinkResponse.decimals = AggregatorV3Interface(_feed).decimals();\n\n    (\n      uint80 _latestRoundId,\n      int256 _latestAnswer,\n      uint256 _startedAt,\n      uint256 _latestTimestamp,\n      uint80 _answeredInRound\n    ) = AggregatorV3Interface(_feed).latestRoundData();\n\n    _chainlinkResponse.roundId = _latestRoundId;\n    _chainlinkResponse.answer = _latestAnswer;\n    _chainlinkResponse.timestamp = _latestTimestamp;\n    _chainlinkResponse.success = true;\n\n    return _chainlinkResponse;\n}\n```
MEDIUM severity: The `_debt_interest_since_last_update` function calculates interest accrued over a specific interval. The `_debt_interest_since_last_update` function calculates interest accrued over a specific interval by multiplying the time elapsed since the last update by the current interest per second and the total debt amount. However, the calculation is flawed due to an incorrect division operation. Instead...

Vulnerable code:
```\ndef _debt_interest_since_last_update(_debt_token: address) -> uint256:\n    return (\n        (block.timestamp - self.last_debt_update[_debt_token]) * \n        self._current_interest_per_second(_debt_token) * \n        self.total_debt_amount[_debt_token] / \n        PERCENTAGE_BASE / \n        PRECISION\n    )\n```\n```\nassert (\n    expected_interest_per_second\n    == vault_configured.internal._current_interest_per_second(usdc.address)\n)\n\nexpected_interest_per_second = 9512937595129375\n```\n```\n(self.timestamp - self.last_debt_update[_debt_token]) * self._current_interest_per_second(_debt_token) * self.total_debt_amount[_debt_token] / PERCENTAGE_BASE / PRECISION\n```
MEDIUM severity: The `keep-tecdsa` vulnerability occurs when a keep cannot be closed due to the bonds being completel. The `keep-tecdsa` vulnerability occurs when a keep cannot be closed due to the bonds being completely reassigned or seized, leaving at least one member with zero `lockedBonds`. This situation arises when the `closeKeep()` function is called, which attempts to release bonds to the keep members using...

Vulnerable code:
```\nfunction closeKeep() external onlyOwner onlyWhenActive {\n    require(\n       !isSigningInProgress() || hasSigningTimedOut(),\n        "Requested signing has not timed out yet"\n    );\n\n    isActive = false;\n\n    freeMembersBonds();\n\n    emit KeepClosed();\n}\n\nfunction freeMembersBonds() internal {\n    for (uint256 i = 0; i < members.length; i++) {\n        keepBonding.freeBond(members[i], uint256(address(this)));\n    }\n}\n```\n```\nfunction freeBond(address operator, uint256 referenceID) public {\n    address holder = msg.sender;\n    bytes32 bondID = keccak256(abi.encodePacked(operator, holder, referenceID));\n\n    require(lockedBonds[bondID] > 0, "Bond not found");\n\n    uint256 amount = lockedBonds[bondID];\n    lockedBonds[bondID] = 0;\n    unbondedValue[operator] = amount;\n}\n```
MEDIUM severity: The `SocketDeployFactory.destroy` function, when called, initiates a self-destruct mechanism that te. The `SocketDeployFactory.destroy` function, when called, initiates a self-destruct mechanism that terminates the associated route and transfers any accumulated Ether (ETH) to the `SocketDeployFactory` contract. However, this process leaves the ETH balances locked within the factory contract, renderi...

Vulnerable code:
```\nfunction destroy(uint256 routeId) external onlyDisabler {\n```
MEDIUM severity: The vulnerability allows an attacker to intentionally manipulate their position to bypass efficiency. The vulnerability allows an attacker to intentionally manipulate their position to bypass efficiency and liquidity removal limits, effectively liquidating their own position at almost no cost. This is achieved by exploiting the difference in how the margined and maintained amounts are calculated.\n\...

Vulnerable code:
```\nif (\n   !context.currentPosition.local.margined(\n        context.latestVersion,\n        context.riskParameter,\n        context.pendingCollateral\n    )\n) {\n    revert MarketInsufficientMarginError();\n}\n```\n```\nif (\n   !PositionLib.maintained(\n        context.maxPendingMagnitude,\n        context.latestVersion,\n        context.riskParameter,\n        context.pendingCollateral\n    )\n) {\n    revert MarketInsufficientMaintenanceError();\n}\n```
MEDIUM severity: The UniProxy.depositSwap function in the UniProxy contract contains a vulnerability that can result . The UniProxy.depositSwap function in the UniProxy contract contains a vulnerability that can result in users' funds being left in the contract instead of being deposited. This occurs when the swap amount is calculated using the `amountOut` variable, which is the actual amount of tokens to be swapped...

Vulnerable code:
```\nelse {\n    swap = uint256(swapAmount);\n    IHypervisor(pos).token0().transferFrom(msg.sender, address(this), deposit0 + swap);\n\n    amountOut = router.exactInput(\n        ISwapRouter.ExactInputParams(\n            path,\n            address(this),\n            block.timestamp + swapLife,\n            swap,\n            deposit1\n        )\n    );\n\n    require(amountOut > 0, "Swap failed");\n\n    if (positions[pos].version < 2) {\n        shares = IHypervisor(pos).deposit(deposit0, deposit1, address(this));\n        IHypervisor(pos).transfer(to, shares);\n    }\n```
MEDIUM severity: The `OrchidDirectory.lift()` function in the provided code snippet exhibits a vulnerability related . The `OrchidDirectory.lift()` function in the provided code snippet exhibits a vulnerability related to inconsistent parameter ordering. Specifically, the `stakee` parameter is declared before `staker`, which may lead to confusion and potential errors in the code's execution.\n\nIn Solidity, the lack...

Vulnerable code:
```\nfunction lift(bytes32 key, Stake storage stake, uint128 amount, address stakee, address staker) private {\n    // Your code here\n}\n```
MEDIUM severity: When an ERC777 token, tokenX, is used in the BufferBinaryPool, a vulnerability arises in the `_provi. When an ERC777 token, tokenX, is used in the BufferBinaryPool, a vulnerability arises in the `_provide` function. Specifically, when tokenX is an ERC777 token, the `tokensToSend` function of the account is called before sending tokens through `tokenX.transferFrom`. This allows users to manipulate th...

Vulnerable code:
```\nrequire(\n    balance + tokenXAmount <= maxLiquidity,\n    "Pool has already reached its max limit"\n);\n```
MEDIUM severity: The `openPositionFarm` function in the AuraSpell contract is designed to open a position for the Aur. The `openPositionFarm` function in the AuraSpell contract is designed to open a position for the AuraSpell by depositing collateral, borrowing tokens, and joining a pool. However, the function contains a critical flaw in its logic. Specifically, the function only borrows one type of token from the b...

Vulnerable code:
```\nfunction openPositionFarm(\n    OpenPosParam calldata param\n) \n    external \n    existingStrategy(param.strategyId)\n    existingCollateral(param.strategyId, param.collToken)\n{\n    // 1. Deposit isolated collaterals on Blueberry Money Market\n    _doLend(param.collToken, param.collAmount);\n\n    // 2. Borrow specific amounts\n    uint256 borrowBalance = _doBorrow(\n        param.borrowToken,\n        param.borrowAmount\n    );\n\n    // 3. Add liquidity on Balancer, get BPT\n    {\n        IBalancerVault vault = wAuraPools.getVault(lpToken);\n        _ensureApprove(param.borrowToken, address(vault), borrowBalance);\n\n        (address[] memory tokens, uint256[] memory balances, ) = wAuraPools\n           .getPoolTokens(lpToken);\n        uint[] memory maxAmountsIn = new uint[](2);\n        maxAmountsIn[0] = IERC20(tokens[0]).balanceOf(address(this));\n        maxAmountsIn[1] = IERC20(tokens[1]).balanceOf(address(this));\n\n        uint totalLPSupply = IBalancerPool(lpToken).totalSupply();\n        uint poolAmountFromA = (maxAmountsIn[0] * totalLPSupply) / balances[0];\n        uint poolAmountFromB = (maxAmountsIn[1] * totalLPSupply) / balances[1];\n        uint poolAmountOut = poolAmountFromA > poolAmountFromB\n           ? poolAmountFromB\n            : poolAmountFromA;\n\n        bytes32 poolId = bytes32(param.farmingPoolId);\n        if (poolAmountOut > 0) {\n            vault.joinPool(\n                poolId,\n                address(this),\n                address(this),\n                IBalancerVault.JoinPoolRequest(\n                    tokens,\n                    maxAmountsIn,\n                    "",\n                    false\n                )\n            );\n        }\n    }\n```
MEDIUM severity: The FulfillInterpreter's fallback handling mechanism is flawed due to an incorrect order of actions.. The FulfillInterpreter's fallback handling mechanism is flawed due to an incorrect order of actions. When a transaction is fulfilled and the `callTo` is not a contract address, the funds are first transferred to the `FulfillInterpreter` instance, and then the `execute` method is called. If the call...

Vulnerable code:
```\nbool isNative = LibAsset.isNativeAsset(assetId);\nif (!isNative) {\n    LibAsset.increaseERC20Allowance(assetId, callTo, amount);\n}\n\nif (Address.isContract(callTo)) {\n    bool success;\n    bytes memory returnData;\n    (success, returnData) = callTo.call{value: isNative? amount : 0}(callData);\n}\n\nif (!success) {\n    LibAsset.transferAsset(assetId, fallbackAddress, amount);\n    if (!isNative) {\n        LibAsset.decreaseERC20Allowance(assetId, callTo, amount);\n    }\n}\n```
MEDIUM severity: The use of `abi.encodePacked()` with dynamic types when passing the result to a hash function such a. The use of `abi.encodePacked()` with dynamic types when passing the result to a hash function such as `keccak256()` can lead to unintended consequences. This is because `abi.encodePacked()` does not pad the input data to a fixed length, which can result in hash collisions.\n\nFor instance, consider...

Vulnerable code:
```\nreturn keccak256(abi.encodePacked(deployer, poolName));\n```\n```\nreturn keccak256(\n    abi.encodePacked(\n        resultsHash,\n        block.chainid,\n        address(this)\n    )\n);\n```\n```\npragma solidity ^0.8.0;\n\ncontract UserRegistry {\n    mapping (bytes32 => mapping (address => bytes32)) _signatureHashes;\n\n    function registerSignature(bytes32 _documentHash, bytes32 _signature) public {\n        _signatureHashes[_documentHash][msg.sender] = keccak256(abi.encodePacked(_signature));\n    }\n}\n```
MEDIUM severity: The StableBPT valuation calculation in the `StableBPTOracle.sol` contract is flawed and can be explo. The StableBPT valuation calculation in the `StableBPTOracle.sol` contract is flawed and can be exploited to cause protocol insolvency. Specifically, the code block responsible for calculating the price of the pool's assets uses a simplistic approach that is not suitable for Balancer pools.\n\nThe co...

Vulnerable code:
```\nuint256 minPrice = base.getPrice(tokens[0]);\n\nfor (uint256 i = 1; i!= length; ++i) {\n    uint256 price = base.getPrice(tokens[i]);\n    minPrice = (price < minPrice)? price : minPrice;\n}\n\nreturn minPrice.mulWadDown(pool.getRate());\n```
MEDIUM severity: The `_capFeeAmount` function in the `PantherSwapCompoundingStrategyToken` is intended to cap the siz. The `_capFeeAmount` function in the `PantherSwapCompoundingStrategyToken` is intended to cap the size of fees based on the Panther token's transfer limit. This function is crucial in ensuring that the transfer size does not exceed the predetermined limit. However, the implementation of this function...

Vulnerable code:
```\nfunction _capFeeAmount(uint256 _amount) internal view returns (uint256 _capped, uint256 _retained) {\n    _retained = 0;\n    uint256 _limit = _calcMaxRewardTransferAmount();\n    if (_amount > _limit) {\n        _amount = _limit;\n        _retained = _amount.sub(_limit);\n    }\n    return (_amount, _retained);\n}\n```
MEDIUM severity: The `_hashLeaf` method is a critical component of the smart contract's validation mechanism, respons. The `_hashLeaf` method is a critical component of the smart contract's validation mechanism, responsible for verifying the integrity of a leaf node. The method accepts three inputs: `user_id`, `user_amount`, and `leaf`, which are used to generate a unique hash value using the Keccak-256 algorithm. S...

Vulnerable code:
```\nfunction _hashLeaf(uint32 user_id, uint256 user_amount, bytes32 leaf) private returns (bool) {\n    return true;\n}\n```\n```\nbytes32 leaf_hash = keccak256(abi.encodePacked(keccak256(abi.encodePacked(user_id, user_amount))));\n```\n```\nreturn leaf == leaf_hash;\n```
MEDIUM severity: The `getParentAndBlockhash` function is responsible for extracting the parent hash and calculated bl. The `getParentAndBlockhash` function is responsible for extracting the parent hash and calculated blockhash from an RLP-encoded blockheader blob. This function is used to add blockhashes to the registry that are older than 256 blocks, as they are not directly accessible to the EVM. The method assume...

Vulnerable code:
```\nfunction getParentAndBlockhash(bytes memory _blockheader) public pure returns (bytes32 parentHash, bytes32 bhash) {\n    uint8 first = uint8(_blockheader[0]);\n\n    require(first > 0xf7, "invalid offset");\n    uint8 offset = first - 0xf7 + 2;\n\n    assembly {\n        mstore(0x20, _blockheader)\n        parentHash := mload(add(add(mload(0x20), 0x20), offset))\n    }\n    bhash = keccak256(_blockheader);\n}\n```
MEDIUM severity: The vulnerability arises from the fact that the `L2CrossDomainMessenger.relayMessage` function relie. The vulnerability arises from the fact that the `L2CrossDomainMessenger.relayMessage` function relies on the `successfulMessages` state variable to check if a legacy message has already been relayed. However, during the migration to Bedrock, the storage of the contract is wiped, effectively resettin...

Vulnerable code:
```\nif (version == 0):\n    bytes32 oldHash = Hashing.hashCrossDomainMessageV0(_target, _sender, _message, _nonce)\n    require(\n        successfulMessages[oldHash] == false,\n        "CrossDomainMessenger: legacy withdrawal already relayed"\n    )\n```\n```\nif err := WipePredeployStorage(db); err!= nil {\n    return nil, fmt.Errorf("cannot wipe storage: %w", err)\n}\n```
MEDIUM severity: The MiniGovernance contract's senate initialization process is vulnerable to an unintended extension. The MiniGovernance contract's senate initialization process is vulnerable to an unintended extension of senate validity. Specifically, the `GEM._setSenate` function sets the new senate's validity period to `block.timestamp + SENATE_VALIDITY`, which is then overwritten by `self.SENATE_EXPIRY = block....

Vulnerable code:
```\nGEM._setSenate(newSenate, block.timestamp + SENATE_VALIDITY)\n```\n```\nself.SENATE_EXPIRY = block.timestamp + _senatePeriod\n```
MEDIUM severity: The `_calculateMaxBorrowCollateral` function in the AaveLeverageStrategyExtension contract contains . The `_calculateMaxBorrowCollateral` function in the AaveLeverageStrategyExtension contract contains a critical flaw in its calculation of the net repayment limit. Specifically, it incorrectly applies the `unutilizedLeveragePercentage` when calculating `netRepayLimit`, leading to an incorrect determi...

Vulnerable code:
```\nelse {\n    uint256 netRepayLimit = _actionInfo.collateralValue\n       .preciseMul(liquidationThresholdRaw.mul(10 ** 14))\n       .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));\n\n    return _actionInfo.collateralBalance\n       .preciseMul(netRepayLimit.sub(_actionInfo.borrowValue))\n       .preciseDiv(netRepayLimit);\n}\n```
MEDIUM severity: This vulnerability allows an attacker to liquidate a debt outstanding above the minimum borrow size . This vulnerability allows an attacker to liquidate a debt outstanding above the minimum borrow size without liquidating the entire debt outstanding, leaving accounts with small debt that are not profitable to unwind if it needs to liquidate. This is possible due to an incorrect mathematical formula...

Vulnerable code:
```\nFile: VaultValuation.sol\n\nif depositUnderlyingInternal < maxLiquidatorDepositLocal:\n    if liquidating past the debt outstanding above the min borrow, then the entire\n    debt outstanding must be liquidated.\n\n    (debtOutstanding - depositAmountUnderlying) is the post liquidation debt. As an\n    edge condition, when debt outstanding is discounted to present value, the account\n    may be liquidated to zero while their debt outstanding is still greater than the\n    min borrow size (which is normally enforced in notional terms -- i.e. non present\n    value). Resolving this would require additional complexity for not much gain. An\n    account within 20% of the minBorrowSize in a vault that has fCash discounting enabled\n    may experience a full liquidation as a result.\n\n    require(\n        h.debtOutstanding[currencyIndex].sub(depositUnderlyingInternal) < minBorrowSize,\n        "Must Liquidate All Debt"\n    )\n```\n```\nrequire(\n    h.debtOutstanding[currencyIndex].sub(depositUnderlyingInternal) < minBorrowSize,\n    "Must Liquidate All Debt"\n);\n```\n```\nrequire(\n  (-100 USDC - 70 USDC) < 50 USDC\n);\n===\nrequire(\n  (-170 USDC) < 50 USDC\n);\n===\nrequire(true);\n```
MEDIUM severity: The `getCurrentState()` function calculates the current state of pool variables based on the current. The `getCurrentState()` function calculates the current state of pool variables based on the current time and other functions use it to update the contract state. Specifically, it calculates the interest accrued for debt from the last timestamp. However, due to a division error, in certain scenarios...

Vulnerable code:
```\nuint _timeDelta = block.timestamp - _lastAccrueInterestTime;\n\nif (_timeDelta == 0) {\n    return (_currentTotalSupply, _accruedFeeShares, _currentCollateralRatioMantissa, _currentTotalDebt);\n}\n\nuint _supplied = _totalDebt + _loanTokenBalance;\nuint _util = getUtilizationMantissa(_totalDebt, _supplied);\n\n_currentCollateralRatioMantissa = getCollateralRatioMantissa(\n    _util,\n    _lastAccrueInterestTime,\n    block.timestamp,\n    _lastCollateralRatioMantissa,\n    COLLATERAL_RATIO_FALL_DURATION,\n    COLLATERAL_RATIO_RECOVERY_DURATION,\n    MAX_COLLATERAL_RATIO_MANTISSA,\n    SURGE_MANTISSA\n);\n\nif (_totalDebt == 0) {\n    return (_currentTotalSupply, _accruedFeeShares, _currentCollateralRatioMantissa, _currentTotalDebt);\n}\n\nuint _borrowRate = getBorrowRateMantissa(_util, SURGE_MANTISSA, MIN_RATE, SURGE_RATE, MAX_RATE);\nuint _interest = _totalDebt * _borrowRate * _timeDelta / (365 * 1e18);\n_currentTotalDebt += _interest;\n```
MEDIUM severity: The `keep-tecdsa` vulnerability occurs when the caller sends more Ether than is contained in the sig. The `keep-tecdsa` vulnerability occurs when the caller sends more Ether than is contained in the signer subsidy pool, causing the excess value to be burned. This issue arises from the inconsistent tracking of the subsidy pool's balance and the distribution of funds to signers.\n\nIn the `BondedECDSA...

Vulnerable code:
```\nuint256 signerSubsidy = subsidyPool < msg.value\n   ? subsidyPool\n    : msg.value;\n\nif (signerSubsidy > 0) {\n    subsidyPool -= signerSubsidy;\n    keep.distributeETHToMembers.value(signerSubsidy)();\n```\n```\n(bool success,) = address(randomBeacon).call.gas(400000).value(msg.value)(\n    abi.encodeWithSignature(\n        "requestRelayEntry(address,string,uint256)",\n        address(this),\n        "setGroupSelectionSeed(uint256)",\n        callbackGas\n    )\n);\n\nif (!success) {\n    subsidyPool += msg.value; // beacon is busy\n}\n```