Farseen0/scar-pairs huggingface dataset:
MEDIUM severity: The `_isExternalLendingUnhealthy()` function, which is called within the `checkRebalance()` method, . The `_isExternalLendingUnhealthy()` function, which is called within the `checkRebalance()` method, relies on stale factors to calculate the `targetAmount` in the `getTargetExternalLendingAmount()` function. This stale data is obtained from the `PrimeCashExchangeRate.getPrimeCashFactors()` function,...

Vulnerable code:
```\nfunction _isExternalLendingUnhealthy(\n    uint16 currencyId,\n    IPrimeCashHoldingsOracle oracle,\n    PrimeRate memory pr\n) internal view returns (bool isExternalLendingUnhealthy, OracleData memory oracleData, uint256 targetAmount) {\n    PrimeCashFactors memory factors = PrimeCashExchangeRate.getPrimeCashFactors(currencyId);\n    Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId);\n\n    targetAmount = ExternalLending.getTargetExternalLendingAmount(\n        underlyingToken,\n        factors,\n        rebalancingTargetData,\n        oracleData,\n        pr\n    );\n}\n```
MEDIUM severity: The TransactionManager contract's hard-coded chain ID, stored as an immutable state variable, can le. The TransactionManager contract's hard-coded chain ID, stored as an immutable state variable, can lead to issues in the event of a chain split. This is because the chain ID is set during the contract's deployment and remains constant, whereas a chain split would result in a new, distinct chain ID.\n...

Vulnerable code:
```\n/**\n * @dev The chain id of the contract, is passed in to avoid any evm issues\n */\nuint256 public immutable chainId;\n```\n```\nconstructor(uint256 _chainId) {\n    chainId = _chainId;\n    interpreter = new FulfillInterpreter(address(this));\n}\n```
MEDIUM severity: The `recoverFunds()` function is designed to recover mistakenly sent tokens, but it employs an unsaf. The `recoverFunds()` function is designed to recover mistakenly sent tokens, but it employs an unsafe transfer mechanism to send tokens back to the recipient. This approach is problematic because it does not account for the compatibility issues that may arise when dealing with a large number of non-...

Vulnerable code:
```\nif (token == quoteAsset || token == baseAsset || token == weth) {\n    revert CannotRecoverRestrictedToken(address(this));\n}\ntoken.transfer(recipient, token.balanceOf(address(this)));\n```
MEDIUM severity: When a user submits the initial batch of compressed block data after migrating to an updated contrac. When a user submits the initial batch of compressed block data after migrating to an updated contract, the finalization process fails. This occurs in the `_finalizeCompressedBlocks` function, where the `startingDataParentHash` variable is unexpectedly empty. As a result, the `startingParentFinalStat...

Vulnerable code:
```\nif (stateRootHashes[currentL2BlockNumber]!= _finalizationData.parentStateRootHash):\n    revert StartingRootHashDoesNotMatch()\n```\n```\nif (finalizationDataDataHashesLength!= 0) {\n    bytes32 startingDataParentHash = dataParents[finalizationData.dataHashes[0]];\n    \n    if (startingDataParentHash!= finalizationData.dataParentHash) {\n        revert ParentHashesDoesNotMatch(startingDataParentHash, finalizationData.dataParentHash);\n    }\n    \n    bytes32 startingParentFinalStateRootHash = dataFinalStateRootHashes[startingDataParentHash];\n    \n    if (startingParentFinalStateRootHash!= finalizationData.parentStateRootHash) {\n        revert FinalStateRootHashDoesNotMatch(startingParentFinalStateRootHash, finalizationData.parentStateRootHash);\n    }\n}\n```
MEDIUM severity: The `recover()` function in the `SecondaryRewarder` contract, which is responsible for retrieving to. The `recover()` function in the `SecondaryRewarder` contract, which is responsible for retrieving tokens sent to the address or excess reward tokens, may not be able to successfully recover tokens of a specific type, such as `USDT`. This is because the `IERC20.transfer()` method, used to execute the...

Vulnerable code:
```\nfunction recover(address token, uint256 amount) external onlyOwner {\n    if (Constants.ETH_ADDRESS == token) {\n        (bool status,) = msg.sender.call{value: amount}("");\n        require(status);\n    } else {\n        IERC20(token).transfer(msg.sender, amount);\n    }\n}\n```
MEDIUM severity: The vulnerability, known as "bad debt" or "shortfall" liquidation, occurs when a liquidation process. The vulnerability, known as "bad debt" or "shortfall" liquidation, occurs when a liquidation process leaves a user with a negative collateral balance. This can happen when a user's position is liquidated, and the liquidation fee exceeds the user's remaining collateral. In this scenario, the user's a...

Vulnerable code:
```\nit('panprog bad debt liquidation bankrun', async () => {\n\n    function setupOracle(price: string, timestamp: number, nextTimestamp: number) {\n        const oracleVersion = {\n            price: parse6decimal(price),\n            timestamp: timestamp,\n            valid: true,\n        };\n        oracle.at.whenCalledWith(oracleVersion.timestamp).returns(oracleVersion);\n        oracle.status.returns([oracleVersion, nextTimestamp]);\n        oracle.request.returns();\n    }\n\n    var riskParameter = {\n        maintenance: parse6decimal('0.01'),\n        takerFee: parse6decimal('0.00'),\n        takerSkewFee: 0,\n        takerImpactFee: 0,\n        makerFee: parse6decimal('0.00'),\n        makerImpactFee: 0,\n        makerLimit: parse6decimal('1000'),\n        efficiencyLimit: parse6decimal('0.2'),\n        liquidationFee: parse6decimal('0.50'),\n        minLiquidationFee: parse6decimal('10'),\n        maxLiquidationFee: parse6decimal('1000'),\n        utilizationCurve: {\n            minRate: parse6decimal('0.0'),\n            maxRate: parse6decimal('1.00'),\n            targetRate: parse6decimal('0.10'),\n            targetUtilization: parse6decimal('0.50'),\n        },\n        pController: {\n            k: parse6decimal('40000'),\n            max: parse6decimal('1.20'),\n        },\n        minMaintenance: parse6decimal('10'),\n        virtualTaker: parse6decimal('0'),\n        staleAfter: 14400,\n        makerReceiveOnly: false,\n    };\n\n    var marketParameter = {\n        fundingFee: parse6decimal('0.0'),\n        interestFee: parse6decimal('0.0'),\n        oracleFee: parse6decimal('0.0'),\n        riskFee: parse6decimal('0.0'),\n        positionFee: parse6decimal('0.0'),\n        maxPendingGlobal: 5,\n        maxPendingLocal: 3,\n        settlementFee: parse6decimal('0'),\n        makerRewardRate: parse6decimal('0'),\n        longRewardRate: parse6decimal('0'),\n        shortRewardRate: parse6decimal('0'),\n        makerCloseAlways: false,\n        takerCloseAlways: false,\n        closed: false,\n    };\n\n    await market.connect(owner).updateRiskParameter(riskParameter);\n    await market.connect(owner\n```\n```\ncollateral before liquidation: 10000000 + 500000000 + 500000000 = 1010000000\ncollateral after liquidation: -100000080 + 550000000 + 550000000 = 999999920\n```
MEDIUM severity: The `_removeBasset` function in the codebase contains a vulnerability that can lead to tokens being . The `_removeBasset` function in the codebase contains a vulnerability that can lead to tokens being left stuck in the vault. Although the function checks if the vault balance is zero before removal, this validation is insufficient due to the asynchronous nature of interest collection.\n\nThe issue a...

Vulnerable code:
```\nrequire(bAsset.vaultBalance == 0, "bAsset vault must be empty")\n```
MEDIUM severity: The vulnerability arises from an incorrect calculation of the `borrowingCollateral` variable, which . The vulnerability arises from an incorrect calculation of the `borrowingCollateral` variable, which can lead to a denial-of-service (DoS) attack for positions within the current tick range. The calculation, `borrowingCollateral = cache.borrowedAmount - cache.holdTokenBalance`, is susceptible to unde...

Vulnerable code:
```\nuint256 borrowingCollateral = cache.borrowedAmount - cache.holdTokenBalance;\n```
MEDIUM severity: The `RocketMinipoolBase` contract's `delegateUpgrade` and `delegateRollback` functions provide the m. The `RocketMinipoolBase` contract's `delegateUpgrade` and `delegateRollback` functions provide the minipool owner with the ability to switch between different delegate implementations. Although this feature allows for the potential rollback of malfunctioning upgrades, it also enables the owner to ra...

Vulnerable code:
```\nfunction _slash() private {\n    // Get contracts\n    RocketNodeStakingInterface rocketNodeStaking = RocketNodeStakingInterface(getContractAddress("rocketNodeStaking"));\n\n    // Slash required amount and reset storage value\n    uint256 slashAmount = nodeSlashBalance;\n    nodeSlashBalance = 0;\n    rocketNodeStaking.slashRPL(nodeAddress, slashAmount);\n\n    // Record slashing\n    slashed = true;\n}\n```\n```\nfunction _slash() private {\n    // Get contracts\n    RocketNodeStakingInterface rocketNodeStaking = RocketNodeStakingInterface(getContractAddress("rocketNodeStaking"));\n\n    // Slash required amount and reset storage value\n    uint256 slashAmount = nodeSlashBalance;\n    nodeSlashBalance = 0;\n    rocketNodeStaking.slashRPL(nodeAddress, slashAmount);\n}\n```
MEDIUM severity: The CrossDomainMessenger vulnerability is a critical issue that can result in the permanent loss of . The CrossDomainMessenger vulnerability is a critical issue that can result in the permanent loss of user funds. The problem arises when the `OptimismPortal` successfully ensures that the called function will not revert, but does not guarantee any remaining buffer for continued execution on the calli...

Vulnerable code:
```\nfunction gas(uint256 _amountToLeave) internal view {\n    uint256 i = 0;\n    while (gasleft() > _amountToLeave) {\n        i++;\n    }\n}\n```
MEDIUM severity: The `recreateBlockheaders` method is designed to recalculate the blockhashes from a list of RLP-enco. The `recreateBlockheaders` method is designed to recalculate the blockhashes from a list of RLP-encoded `_blockheaders` and update the `blockhashMapping` accordingly. However, the method fails to validate the input `_blockheaders` array, which can lead to unexpected behavior. Specifically, if `_bloc...

Vulnerable code:
```\nfunction recreateBlockheaders(uint _blockNumber, bytes[] memory _blockheaders) public {\n    bytes32 currentBlockhash = blockhashMapping[_blockNumber];\n    require(currentBlockhash!= 0x0, "parentBlock is not available");\n\n    bytes32 calculatedHash = reCalculateBlockheaders(_blockheaders, currentBlockhash);\n    require(calculatedHash!= 0x0, "invalid headers");\n```\n```\nbytes32 calculatedHash = reCalculateBlockheaders(_blockheaders, currentBlockhash);\n```\n```\nfunction reCalculateBlockheaders(bytes[] memory _blockheaders, bytes32 _bHash) public pure returns (bytes32 bhash) {\n    bytes32 currentBlockhash = _bHash;\n    bytes32 calcParent = 0x0;\n    bytes32 calcBlockhash = 0x0;\n\n    for (uint i = 0; i < _blockheaders.length; i++) {\n        (calcParent, calcBlockhash) = getParentAndBlockhash(_blockheaders[i]);\n        if (calcBlockhash!= currentBlockhash) {\n            return 0x0;\n        }\n        currentBlockhash = calcParent;\n    }\n\n    return currentBlockhash;\n}\n```\n```\nfunction addBlockhash(uint _blockNumber, bytes32 calculatedHash) public {\n    /// we should never fail this assert, as this would mean that we were able to recreate a invalid blockchain\n    assert(_blockNumber > _blockheaders.length);\n    uint bnr = _blockNumber - _blockheaders.length;\n    blockhashMapping[bnr] = calculatedHash;\n    emit LogBlockhashAdded(bnr, calculatedHash);\n}\n```
MEDIUM severity: The `InvestorBasedRateLimiter` contract's `initializeInvestorStateDefault` function is designed to a. The `InvestorBasedRateLimiter` contract's `initializeInvestorStateDefault` function is designed to associate a newly created investor with one or more addresses. However, a vulnerability exists in the `for` loop that iterates over the provided `addresses` array. Specifically, an attacker can bypass...

Vulnerable code:
```\nfunction initializeInvestorStateDefault(\n    address[] memory addresses\n) external onlyRole(CONFIGURER_ROLE) {\n    _initializeInvestorState(\n        addresses,\n        defaultMintLimit,\n        defaultRedemptionLimit,\n        defaultMintLimitDuration,\n        defaultRedemptionLimitDuration\n    );\n}\n\nfunction _initializeInvestorState(\n    address[] memory addresses,\n    uint256 mintLimit,\n    uint256 redemptionLimit,\n    uint256 mintLimitDuration,\n    uint256 redemptionLimitDuration\n) internal {\n    uint256 investorId = ++investorIdCounter;\n\n    for (uint256 i = 0; i < addresses.length; i++) {\n        if (addressToInvestorId[addresses[i]]!= 0) {\n            revert AddressAlreadyAssociated();\n        }\n        _setAddressToInvestorId(addresses[i], investorId);\n    }\n\n    investorIdToMintState[investorId] = RateLimit({\n        currentAmount: 0,\n        limit: mintLimit,\n        lastResetTime: block.timestamp,\n        limitDuration: mintLimitDuration\n    });\n    investorIdToRedemptionState[investorId] = RateLimit({\n        currentAmount: 0,\n        limit: redemptionLimit,\n        lastResetTime: block.timestamp,\n        limitDuration: redemptionLimitDuration\n    });\n}\n```
MEDIUM severity: The `_makePayment` function in the `LienToken` contract is logically inconsistent with the way the l. The `_makePayment` function in the `LienToken` contract is logically inconsistent with the way the lien stack is managed, leading to issues when paying off multiple liens. The function loops through the `openLiens` array, making payments to each lien in sequence. However, the `_deleteLienPosition` f...

Vulnerable code:
```\nfunction _makePayment(uint256 collateralId, uint256 totalCapitalAvailable)\n  internal\n{\n  uint256[] memory openLiens = liens[collateralId];\n  uint256 paymentAmount = totalCapitalAvailable;\n\n  for (uint256 i = 0; i < openLiens.length; ++i) {\n    uint256 capitalSpent = _payment(\n      collateralId,\n      uint8(i),\n      paymentAmount,\n      address(msg.sender)\n    );\n    paymentAmount -= capitalSpent;\n  }\n}\n```\n```\nfunction _deleteLienPosition(uint256 collateralId, uint256 position) public {\n    uint256[] storage stack = liens[collateralId];\n    require(position < stack.length, "index out of bounds");\n\n    emit RemoveLien(\n        stack[position],\n        lienData[stack[position]].collateralId,\n        lienData[stack[position]].position\n    );\n\n    for (uint256 i = position; i < stack.length - 1; i++) {\n        stack[i] = stack[i + 1];\n    }\n    stack.pop();\n}\n```
MEDIUM severity: The vulnerability lies in the implementation of the `RocketStorage` system, which allows any registe. The vulnerability lies in the implementation of the `RocketStorage` system, which allows any registered contract to modify settings belonging to other parts of the system. This is due to the fact that the Access Control List (ACL) for changing settings is not properly restricted, allowing any contra...

Vulnerable code:
```\nmodifier onlyLatestRocketNetworkContract() {\n    if (boolStorage[keccak256(abi.encodePacked("contract.storage.initialised"))] == true) {\n        require(boolStorage[keccak256(abi.encodePacked("contract.exists", msg.sender))], "Invalid or outdated network contract");\n    }\n}\n```\n```\nfunction setAddress(bytes32 _key, address _value) public override external {\n    addressStorage[_key] = _value;\n}\n\nfunction setUint(bytes32 _key, uint _value) public override external {\n    uintStorage[_key] = _value;\n}\n```
MEDIUM severity: The `setValidatorAddress` function in the smart contract allows a validator to migrate to a new addr. The `setValidatorAddress` function in the smart contract allows a validator to migrate to a new address, stacking their existing stake onto the new address without checking the `validatorMaxStake` threshold. This vulnerability enables a validator to bypass the intended limit on their stake, potentia...

Vulnerable code:
```\nfunction setValidatorAddress(uint128 validatorId, address newAddress) external whenNotPaused {\n    v.stakings[newAddress].shares += v.stakings[msg.sender].shares;\n    v.stakings[newAddress].staked += v.stakings[msg.sender].staked;\n    delete v.stakings[msg.sender];\n```
MEDIUM severity: The vulnerability lies in the implementation of ZeroExTransactions, a type of meta transaction suppo. The vulnerability lies in the implementation of ZeroExTransactions, a type of meta transaction supported by the Exchange. Specifically, the gas limit of these transactions is not strictly enforced, allowing relayers to manipulate the outcome of the transaction by choosing a low gas limit. This can h...

Vulnerable code:
```\nstruct ZeroExTransaction {\n    uint256 salt;  // Arbitrary number to ensure uniqueness of transaction hash.\n    uint256 expirationTimeSeconds;  // Timestamp in seconds at which transaction expires.\n    uint256 gasPrice;  // gasPrice that transaction is required to be executed with.\n    address signerAddress;  // Address of transaction signer.\n    bytes data;  // AbiV2 encoded calldata.\n}\n```\n```\ntransactionsExecuted[transactionHash] = true;\n(bool didSucceed, bytes memory returnData) = \n    address(this).delegatecall(transaction.data);\n```
MEDIUM severity: The CVX/AURA distribution calculation in the WAuraPools.sol contract is flawed, leading to a loss of. The CVX/AURA distribution calculation in the WAuraPools.sol contract is flawed, leading to a loss of rewards for users at the end of each cliff. The issue arises when users withdraw their AURA tokens, as the contract claims rewards for all vault participants, including those who have not yet withdra...

Vulnerable code:
```\nif (cliff < totalCliffs) {\n    uint256 reduction = ((totalCliffs - cliff) * 5) / 2 + 700;\n    mintAmount = (mintRequestAmount * reduction) / totalCliffs;\n\n    uint256 amtTillMax = emissionMaxSupply - emissionsMinted;\n    if (mintAmount > amtTillMax) {\n        mintAmount = amtTillMax;\n    }\n}\n```
MEDIUM severity: The vulnerability lies in the lack of proper handling and validation of return values from functions. The vulnerability lies in the lack of proper handling and validation of return values from functions that return values throughout the source code. Specifically, the functions `intakeNumeraire` and `outputNumeraire` are called multiple times, but the returned values are not processed or checked for...

Vulnerable code:
```\nfunction intakeNumeraire(int128 _amount) public returns (uint256 amount_) {\n    amount_ = _amount * (1e18) / (1e3 * 1e3);\n\n    dai.transferFrom(msg.sender, address(this), amount_);\n}\n```\n```\nfunction outputNumeraire(address _dst, int128 _amount) public returns (uint256 amount_) {\n    amount_ = _amount * 1e18;\n\n    dai.transfer(_dst, uint256(amount_));\n\n    return amount_;\n}\n```\n```\nshell.numeraires[i].addr.intakeNumeraire(\n    _shells.mul(shell.weights[i])\n)\n```\n```\nshell.numeraires[i].addr.intakeNumeraire(\n    _oBals[i].mul(_multiplier)\n)\n```\n```\nshell.reserves[i].addr.outputNumeraire(msg.sender, _oBals[i].mul(_multiplier))\n```\n```\nunit\n    intakeAmount = shell.numeraires[i].addr.intakeNumeraire(_shells.mul(shell.weights[i]))\n    require(intakeAmount > 0, "Must intake a positive number of tokens")\n```
MEDIUM severity: The `FliquidatorFTM` contract's `setFlashCloseFee` function allows authorized parties to set the fla. The `FliquidatorFTM` contract's `setFlashCloseFee` function allows authorized parties to set the flash close fee factor, which is represented by two integers, `_newFactorA` and `_newFactorB`, denoting the numerator and denominator, respectively. However, the function lacks input validation, allowing...

Vulnerable code:
```\nfunction setFlashCloseFee(uint64 _newFactorA, uint64 _newFactorB) external isAuthorized {\n    flashCloseF.a = _newFactorA;\n    flashCloseF.b = _newFactorB;\n}\n```
MEDIUM severity: The vulnerability is related to the calculation of the `gamma` value in the `_calcQuoteAmountSellBas. The vulnerability is related to the calculation of the `gamma` value in the `_calcQuoteAmountSellBase` function. When the `gamma` value is calculated, it is possible for it to be equal to zero due to the way the calculation is performed. This can occur when the `baseAmount` is large enough to cause...

Vulnerable code:
```\nfunction _calcQuoteAmountSellBase(\n        address baseToken,\n        uint256 baseAmount,\n        IWooracleV2.State memory state\n    ) private view returns (uint256 quoteAmount, uint256 newPrice) {\n    require(state.woFeasible, "WooPPV2:!ORACLE_FEASIBLE");\n\n    DecimalInfo memory decs = decimalInfo(baseToken);\n\n    uint256 gamma;\n    {\n        uint256 notionalSwap = (baseAmount * state.price * decs.quoteDec) / decs.baseDec / decs.priceDec;\n        require(notionalSwap <= tokenInfos[baseToken].maxNotionalSwap, "WooPPV2:!maxNotionalValue");\n\n        gamma = (baseAmount * state.price * state.coeff) / decs.priceDec / decs.baseDec;\n        require(gamma <= tokenInfos[baseToken].maxGamma, "WooPPV2:!gamma");\n\n        quoteAmount = (\n            (\n                (baseAmount * state.price * decs.quoteDec) / decs.priceDec\n            ) *\n            (\n                uint256(1e18) - gamma - state.spread\n            ) /\n            uint256(1e18) /\n            decs.baseDec\n        );\n    }\n\n    newPrice = ((uint256(1e18) - gamma) * state.price) / uint256(1e18);\n}\n```\n```\nfunction test_SwapsHappenPriceIsNotUpdatedDueToRoundDown() public {\n    uint usdcAmount = 1_000_000 * 1e18;\n    uint wooAmount = 100_000 * 1e18;\n    uint wethAmount = 1_000 * 1e18;\n    deal(USDC, ADMIN, usdcAmount);\n    deal(WOO, ADMIN, wooAmount);\n    deal(WETH, ADMIN, wethAmount);\n\n    vm.startPrank(ADMIN);\n    IERC20(USDC).approve(address(pool), type(uint256).max);\n    IERC20(WOO).approve(address(pool), type(uint256).max);\n    IERC20(WETH).approve(address(pool), type(uint256).max);\n    pool.depositAll(USDC);\n    pool.depositAll(WOO);\n    pool.depositAll(WETH);\n    vm.stopPrank();\n\n    uint wooAmountForTapir = 1e10 * 1000;\n    vm.startPrank(TAPIR);\n    deal(WOO, TAPIR, wooAmountForTapir);\n    IERC20(USDC).approve(address(router), type(uint256).max);\n    IERC20(WOO).approve(address(router), type(uint256).max);\n    IERC20(WETH).approve(address(router), type(uint256).max);\n    vm.stopPrank();\n\n    // WHERE THE MAGIC HAPPENS\n    uint128 price;\n    (price,) = oracle.woPrice(WOO);\n    console.log("price", price);\n\n    uint cumulative;\n    for (uint i = 0; i < 1000; ++i) {\n        vm.prank(TAPIR);\n        cumulative += router.swap(WOO, USDC, wooAmountForTapir / 1000, 0, payable(TAPIR), TAPIR);\n    }\n\n    (uint128 newPrice,) = oracle.woPrice(WOO);\n    console.log("price", newPrice);\n\n    // price hasnt changed although there are significant amount of tokens are being traded by TAPIR\n    assertEq(newPrice, price);\n}\n```